我正在將所有Spring配置轉移到Java代碼。我遇到了一個問題,我現在想根據命令行開關或maven配置文件等來設置我正在使用的配置文件......我也想避免在每個測試中放置所有相同的註釋類。這不是一個Web應用程序,而是一個功能測試套件。Java Spring ApplicationContext配置
這裏是我的嘗試:
public class CompanyApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
final AnnotationConfigApplicationContext rootContext = new AnnotationConfigApplicationContext();
rootContext.getEnvironment().setActiveProfiles(System.getProperty("spring.profile.active", "local"));
rootContext.register(LocalConfiguration.class, SauceLabsConfiguration.class);
}
}
然後,我必須標註有以下我的測試:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CompanyApplicationContextInitializer.class)
然而,當我嘗試運行我的測試,我的自動連接件不被定位。我在正確的軌道上嗎?我怎樣才能在這個類中編程來設置我的ApplicationContext?
我希望避免有一個基礎測試類,它定義了所有的配置選項,但它看起來像我不會有選擇(目前)。我希望避免必須在每個測試類上放置哪個配置文件處於活動狀態(這很容易在這裏使用JVM屬性完成),但我絕對希望避免必須在每個測試類上放置ContextConfiguration註釋,因此將其升級到基準測試將緩解該問題。 – Scott 2012-04-30 12:40:37
@ActiveProfiles註解可以在基類中使用,它將應用於所有的子類。此外,該註釋具有許多屬性,包括一個名爲inheritLocations的屬性。看到Javadoc。 – 2012-07-13 19:38:35