2015-10-14 76 views
0

我的测试类都被注解如下:运行AnnotationConfigApplicationContext从弹簧试验

@RunWith(SpringJUnit4ClassRunner.class) 
@Transactional(propagation= Propagation.REQUIRED) 
@ContextConfiguration(classes = { TestLocalPersisterConfiguration.class }) 
@ActiveProfiles(EnvironmentProfile.TEST_LOCAL) 
public class MyTestClass { 
    // run someMethod here that loads AnnotationConfigApplicationContext in Java class 
} 

从测试I类运行从主类中的方法,并尝试加载AnnotationConfigApplicationContext`:

// Java class method that is run from test class  
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestLocalPersisterConfiguration.class, ProdPersisterConfiguration.class); 
GCThreadStopRepository repository = applicationContext.getBean(GCThreadStopRepository.class); 

但是,春天抱怨No qualifying bean of type [ca.nbc.data.sql.repository.GCThreadStopRepository] is defined

我不知道为什么会发生这种情况,以及如何解决这个问题。

GCThreadStopRepository注有@Repository

TestLocalPersisterConfiguration延伸GenericPersisterConfiguration,它具有以下扫描和负载bean定义:

@Bean 
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
    String persistenceUnitName = environment.getProperty(PROPERTY_PERSISTENCE_UNIT); 
    final LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean(); 
    emfBean.setPersistenceUnitName(persistenceUnitName); 
    emfBean.setPackagesToScan("ca.nbc.data.sql"); 
    emfBean.setPersistenceXmlLocation("classpath:META-INF/persistence.xml"); 
    emfBean.setDataSource(dataSource()); 
    if(getJpaProperties() != null) { 
    emfBean.setJpaProperties(getJpaProperties()); 
    } 
    return emfBean; 
} 

UPDATE:

我发现,当AnnotationConfigApplicationContext在Java类被启动时,@ActiveProfiles(EnvironmentProfile.TEST_LOCAL)从测试类设置不传播到Java类,即。在Java类中运行applicationContext.getEnvironment().getActiveProfiles()会返回一个空数组。

有没有办法将@ActiveProfiles(EnvironmentProfile.TEST_LOCAL)传播到系统范围?

+0

究竟为什么你自己加载它?你似乎缺少'@ ContextConfiguration'和基于spring的测试类的观点。在那个Spring旁边使用了基于代理的应用程序,所以如果你的'GCThreadStopRepository'实现了一个接口,它将只能作为那些接口而不是具体类(它隐藏在代理中)。 –

回答

0

你不应该把自己初始化应用程序上下文,你实际上已经拥有了它,一旦你使用@ContextConfiguration

所有你需要做的是:

@Autowired 
GCThreadStopRepository repository; 

你只需要确保豆在@Configuration类定义您扫描 - 无论是在定义它:

@ContextConfiguration(classes = {YourClass.class}) 

或@Configuration类本身 - @ComponentScan为@Component或@Import添加另一个@Configuration类

为了使用ActiveProfiles您需要在您的类上定义@Profile。如果一个类没有定义@Profile - 它将在所有配置文件中处于活动状态。根据配置文件,只有定义了@Profile的类才会被包含/排除在扫描之外。 所以这不是问题。 您需要添加

@ComponentScan("ca.nbc.data.sql.repository") 

在TestLocalPersisterConfiguration - 这将扫描包装并阅读@Repository

+0

感谢您的回复。 'main'方法中Java类中的AnnotationConfigApplicationContext不是由我写的,而是由另一个开发者编写的。他从测试类运行这个方法。我实际上意识到这个问题是因为我在测试类中设置的@ActiveProfiles没有传播到主类,有没有办法将从Spring测试类中设置的@ActiveProfiles集传播到系统范围? – czchlong