Spring mvc无法在junit测试中自动装配dao类

问题描述 投票:0回答:1

我有一个使用javaconfig配置的spring mvc web应用程序,我试图在junit测试类上自动装载我的dao类,我使用@EnableWebMvc作为servlet配置,但是它给了我以下异常:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.jahidul.islam.test.tests.TestJunit': Unsatisfied dependency expressed through field 'strengthDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jahidul.islam.dao.StrengthDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)

我的测试类用于junit测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
    @ContextConfiguration(loader=AnnotationConfigWebContextLoader.class),
    @ContextConfiguration(classes=WebAppInitializer.class)
})
public class TestJunit {

    @Autowired
    WebApplicationContext context;

    @Autowired
    StrengthDao strengthDao;

    @Test
    public void test() {
        System.out.println(strengthDao.getStrength(1));
    }

}

我的WebAppInitializer类初始化所有配置:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {WebAppBeanConfig.class, WebAppDaoConfig.class, WebAppServiceConfig.class, WebSecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] {WebAppServletConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        return new Filter[]{new HiddenHttpMethodFilter()};
    }

    @Override
    protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
        final DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return dispatcherServlet;
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.setInitParameter("spring.profiles.active", "production");
    }

}

我的Dao类用于使用hibernate从mysql数据库中获取数据:

@Component("strengthDao")
@Transactional
public class StrengthDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session session() {
        return sessionFactory.getCurrentSession();
    }

    public List<Strength> getAllStrengths(int perPage, int offset) {
        CriteriaBuilder builder = session().getCriteriaBuilder();
        CriteriaQuery<Strength> criteriaQuery = builder.createQuery(Strength.class);
        Root<Strength> root = criteriaQuery.from(Strength.class);
        criteriaQuery.select(root);
        return (List<Strength>) session().createQuery(criteriaQuery).setFirstResult(offset).setMaxResults(perPage).getResultList();
    }

    public long strengthCount() {
        CriteriaBuilder builder = session().getCriteriaBuilder();
        CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
        Root<Strength> root = criteriaQuery.from(Strength.class);
        criteriaQuery.select(builder.count(root));
        return (long) session().createQuery(criteriaQuery).getSingleResult();
    }

    public void saveOrUpdateStrength(Strength strength) {
        session().saveOrUpdate(strength);
    }

    public Strength getStrength(int id) {
        return (Strength) session().get(Strength.class, id);
    }

    public void deleteStrength(Strength strength) {
        session().delete(strength);
    }

}
spring-mvc junit4
1个回答
0
投票

将componentScan注释添加到TestJunit类以自动检测@Repository组件。或者使用@Bean注释在TestJunit类中创建一个java配置bean

@Bean 
public StrengthDao StrengthDao(){
  return new StrengthDao ();
}
© www.soinside.com 2019 - 2024. All rights reserved.