2015-10-14 80 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