2013-06-26 35 views
13

如何在春季通過註釋設置活動配置文件?如何在春季通過註釋設置活動配置文件?

例如:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = { ApplicationConfig.class }, loader = AnnotationConfigContextLoader.class) 
@ActiveProfiles(profiles = {ApplicationProfiles.TEST}) 
public class CacheManagerTest { 
    ... 
} 

對於JUnit測試這個完美的作品,但我怎麼能初始化生產應用程序上下文? (我沒有任何主要的方法/сlasses)

+1

你在prod應用程序中使用什麼類型的配置?這是一個網絡應用程序? –

+0

嗨@馬拉霍夫,希望我的回答可以解決你的問題。使用標準系統屬性是在生產環境中啓用配置文件的常用方式。如果這對你有效,請不要忘記標記我的答案是正確的。乾杯。 –

回答

8

如果使用作出獨立的應用程序或傳遞活動的配置文件,這些方式的Web應用程序,根據Spring blog

激活Web應用

<servlet> 
    <servlet-name>dispatcher</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>spring.profiles.active</param-name> 
     <param-value>production</param-value> 
    </init-param> 
</servlet> 

激活與手動創建的上下文

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); 
ctx.getEnvironment().setActiveProfiles("dev"); 
ctx.load("classpath:/com/bank/config/xml/*-config.xml"); 
ctx.refresh(); 
+0

我沒有web.xml(這不是web應用程序)。如果手動激活,則通過配置文件丟失該想法。 – Malahov

+0

第一個代碼塊是錯誤的。 @Profile不會「激活」一個配置文件,它只是描述了在激活配置文件時激活該配置。 –

+0

@Jonathan,刪除了有關JavaConfig的錯誤信息。 –

12

可以在有效簡表(一個或多個)在運行時使用的傳屬性:

-Dspring.profiles.active="profile1,profile2" 

SpringSource blog post上引入型材。

+0

你能鏈接到這個特性的文檔嗎? –

相關問題