spring - 未定义名为 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' 的 bean

标签 spring junit dependency-injection spring-test spring-junit

我正在尝试运行完整的 junit 测试类包,并且我的域类有一个审核类,如下所示:

    @PrePersist
    public void prePersist(AuditableEntity e) {

      UserService userService = SpringBeanFactory.getBean(UserService.class);  
      // some auditing here  
    }

- SpringBeanFactory 类:

public class SpringBeanFactory {

    private static ApplicationContext applicationContext;

    public static <T> T getBean(final String name, final Class<T> requiredType) {
        T bean = null;
        if (applicationContext != null) {
            bean = applicationContext.getBean(name, requiredType);
        }
        return bean;
    }

    public static <T> T getBean(final Class<T> requiredType) {
        T bean = null;
        if (applicationContext != null) {
            bean = applicationContext.getBean(requiredType);
        }
        return bean;
    }

    public static void setApplicationContext(final ApplicationContext applicationContext) {
        if (SpringBeanFactory.applicationContext == null) {
            SpringBeanFactory.applicationContext = applicationContext;
        }
    }

}

-测试类配置:

@Autowired
private ApplicationContext applicationContext;

@Before
public void before() throws Exception {

    SpringBeanFactory.setApplicationContext(applicationContext);

}

-SpringTestingConfig 类:

@Configuration
@ComponentScan(basePackages = "com.myapp.data", excludeFilters = { @Filter(Configuration.class) })
@PropertySource("classpath:/test.properties")
@Profile("test")
public class SpringTestingConfig {

    private static Logger log = (Logger)LoggerFactory.getLogger(SpringTestingConfig.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public DataSource XdataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        if(log.isDebugEnabled()) log.debug("profile.name", "test");
        System.setProperty("profile.name", "test");

        dataSource.setDriverClassName("org.h2.Driver");
        String schemaName = ConfigurationUtil.config().getString("db.schema.name").toLowerCase();
        log.debug("SCHEMA IS " + schemaName);
        String url = "jdbc:h2:mem:test;MODE=Mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS " +schemaName +"\\;" + "SET SCHEMA "+schemaName;
        dataSource.setUrl(url);
        //dataSource.setUrl("jdbc:h2:mem:test;MODE=Mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS "    + schemaName);

        dataSource.setUsername("sa");

        //use your own local mysql in tests here...
//      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//      dataSource.setUrl("jdbc:mysql://localhost:3306/mv_tests?characterEncoding=UTF-8");
//      dataSource.setUsername("tomcat");
//      dataSource.setPassword("tomcat");
//        
        return dataSource;
    }

    @Bean
    public DataSource dataSource() {

        SpringBeanFactory.setApplicationContext(applicationContext);
        LoggerUtils.setAllApplicationLogs("DEBUG");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        if(log.isDebugEnabled()) {
            log.debug("profile.name", "test");
        }
        System.setProperty("profile.name", "test");

        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        String schemaName = ConfigurationUtil.config().getString("db.schema.name");
        String username = ConfigurationUtil.config().getString("db.username");
        String password = ConfigurationUtil.config().getString("db.password");
        if( log.isDebugEnabled() ) {
            log.debug( "SCHEMA IS " + schemaName );
            log.debug( "Username IS " + username );
            log.debug( "Password IS " + password );
        }

        dataSource.setUrl("jdbc:mysql://localhost:3306/"+schemaName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

}

-测试类注释:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SpringConfig.class, SpringTestingConfig.class, SpringLocalContainerJPAConfig.class, CustomConfiguration.class })
@Transactional

当我的测试方法尝试保存实体时,它会调用 PrePersist 方法,该方法又调用获取 spring 服务:

UserService userService = SpringBeanFactory.getBean(UserService.class);

这又会产生以下异常:

Error creating bean with name 'userService': 
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private com.motivosity.data.repository.UserRepository com.motivosity.service.impl.UserServiceImpl.userRepository; 
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepositoryImpl': 
Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'springLocalContainerJPAConfig': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: 
javax.sql.DataSource com.motivosity.data.config.SpringLocalContainerJPAConfig.dataSource; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'springTestingConfig': Initialization of bean failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'org.springframework.cache.annotation.ProxyCachingConfiguration': 
Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined

我必须提到,当运行完整的测试类包时会出现此异常,但是当单独运行此测试类时不会产生异常。

顺便说一句,我正在使用spring 3.2.3.RELEASE

更新:当我将 Spring 版本升级到最新版本 4.0.3 时,我在同一 get UserService 行上收到一个新的异常:

org.springframework.context.support.GenericApplicationContext@3aa54263 has been closed already

请告知如何解决此异常。

最佳答案

当您使用@DirtiesContext注释测试类或测试方法时,您是在告诉Spring在该测试类或之后关闭ApplicationContext方法。因此,如果您稍后尝试从封闭上下文中检索 bean,您将得到一个像您所看到的异常。

我的猜测是,您在测试套件中的其他测试类中使用了 @DirtiesContext ,结果 SpringBeanFactory.setApplicationContext() 中的逻辑被破坏,因为它可以潜在地维护对封闭上下文的引用。因此,您需要允许为每个测试设置当前 ApplicationContext。换句话说,删除 null - 检查如下

public static void setApplicationContext(final ApplicationContext applicationContext) {
    // always set the current context
    SpringBeanFactory.applicationContext = applicationContext;
}

希望这有帮助!

- Sam(Spring TestContext 框架的作者)

关于spring - 未定义名为 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' 的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23579561/

相关文章:

c# - N 层架构中的 Autofac 模块

dependency-injection - 依赖注入(inject)框架的目的

java - Bolt 的 Apache Storm Junit 测试用例

java - Android 测试项目中的 Junit 4 运行程序 "Sample Project"

java - 使用 jUnit 在 Hibernate 和 Spring 中神奇地更新实体

java - Spring LocalResolver 基于查询参数 'lang=en' ?

c# - 如何在 Startup.cs 中使用通用类型注册接口(interface)

java - 多节点行为

java - 用于自动化测试的嵌入式 jetty

java - Hibernate如何获取更新的属性