2017-07-04 46 views
0

我有我的不同環境的配置文件:prod.properties,dev.propertites和test.properties。用於junit測試的setProperty和ActiveProfiles註釋的區別

屬性文件是通過使用

$應用context.xml文件加載{} spring.profiles.active的.properties

並傳遞-Dspring.profiles.active標誌。這適用於我的3環境。

針對JUnit測試我想在我的測試類使用

@ActiveProfiles( 「測試」)

但是$(spring.profiles.active)沒有解決。但當我使用

System.getProperties()。setProperty(「spring.profiles.active」, 「test」);

它解決得很好。

我知道@ActiveProfiles僅適用於測試類,但爲什麼不設置spring.profiles.active屬性?它隻影響使用哪些bean?

這也不能說明誰最適合處理配置文件和屬性文件。 Spring profiles and Testing

更新: 我迄今採取使用我的應用程序上下文文件如下:

<beans profile="dev,prod"> 
<context:property-placeholder 
     location="classpath:META-INF/properties/generic.properties, 
     classpath:META-INF/properties/${spring.profiles.active}/${spring.profiles.active}.properties"/> 
     <context:component-scan base-package="com.my.package.to.scan"/> 
</beans>  

<beans profile="test"> 
    <context:property-placeholder 
     location="classpath:META-INF/properties/generic.properties, 
     classpath:META-INF/properties/test/test.properties"/> 
<context:component-scan base-package="com.my.package.to.scan"/> 
</beans> 

回答

0

正如其名稱所暗示@ActiveProfile 小號,這是配置文件的陣列。

/** 
* The bean definition profiles to activate. 
* <p>This attribute may <strong>not</strong> be used in conjunction with 
* {@link #value}, but it may be used <em>instead</em> of {@link #value}. 
*/ 
@AliasFor("value") 
String[] profiles() default {}; 

試用@ActiveProfiles({"test"})

+0

我希望它是那麼簡單...仍然沒有拿起它...造成:java.io.FileNotFoundException:類路徑資源[META-INF/properties/$ {spring.profiles.active}/$ {spring.profiles.active} .properties]無法打開,因爲它不存在 –

+0

爲了讓它起作用,我必須在應用程序內容文件中爲屬性佔位符定義bean配置文件。對於我的envinronments,我在屬性文件路徑中保存了$ {spring.profiles.active}屬性,但爲了junit的目的,我使用它進行了硬編碼。 –

+0

@MichoRizo FileNotFoundException與您最初提到的有所不同。因爲它可以分享進一步的信息,如項目結構您的文件位置。如果您提出新問題,我認爲這不需要進行硬編碼,因此更好。 – Rohit

相關問題