Spring测试从XML和注释加载bean配置?

时间:2018-03-27 14:15:57

标签: spring junit dependency-injection spring-test

这是我的Spring Junit

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath*:/META-INF/spring/*.xml" ,
             "classpath*:META-INF/spring/datasource-testcontext.xml"})

    @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
            DbUnitTestExecutionListener.class })
    public class GenericDaoTest {

        @Test
        public void testFind() throws Exception {

        }

          @Configuration
          @ComponentScan("com.myComp.user")
          public static class SpringConfig {

          }

但仍然无法找到com.myComp.user.UserDAO注释的@Component。不确定我在这里缺少什么?

以下是我得到的例外

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myComp.user.UserDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

1 个答案:

答案 0 :(得分:0)

您无法同时声明@Configuration个类 XML配置文件。

您必须选择其中一种格式,然后导入另一种格式。

一种选择是摆脱静态嵌套@Configuration类,只需在声明的XML配置文件中配置组件扫描。

另一种选择是通过@Configuration类导入XML配置,如下所示。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({
    DependencyInjectionTestExecutionListener.class,
    DbUnitTestExecutionListener.class
})
public class GenericDaoTest {

    @Test
    public void testFind() {
    }

    @Configuration
    @ComponentScan("com.myComp.user")
    @ImportResource({
        "classpath*:/META-INF/spring/*.xml",
        "classpath*:META-INF/spring/datasource-testcontext.xml"
    })
    public static class SpringConfig {
    }

}