2017-01-25 17 views
0

所以我有一個彈簧4的應用程序。 它包含3個屬性文件:春天,切換屬性文件根據型材

application.properties 
application-dev.properties 
application-prod.properties 

在application.properties的頭,我指定我想要的輪廓:

spring.profiles.active=dev 

所以在其他兩個文件:

application-dev.properties 
application-prod.properties 

我碰到他們重複條目,因此讓我們在dev文件說我有: host=foo 和督促我有:然後host=bar 春根據當前情景拿起值。 爲了告訴Spring文件所在的位置,我有一個配置類:

@Configuration 
@ComponentScan(basePackages = "my.base.package") 
@PropertySource({ "classpath:application.properties", "classpath:application-dev.properties", "classpath:application-prod.properties" }) 
public class ServiceSpringConfiguration 
{ 
    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() 
    { 
    return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

但我已經注意到了,這樣一來,春節的負荷從所有文件中的所有特性,並且不會允許重複,只是加載無論配置文件如何,您都會要求提供。 我如何告訴Spring根據選定的配置文件加載文件? 我會想到春天掃描文件的名稱和嘗試匹配的配置文件名稱....

順便說一句我指的是財產,像這樣:

@Value("${host}") 
    private String  host; 
+0

春季啓動爲您完成此,通常彈簧沒有。因此,無論是使用Spring Boot還是使用自己的機制來構建(附加)屬性資源。如果您已經使用了Spring啓動,然後刪除'@ PropertySource',讓春天啓動處理加載(你不需要'PropertySourcesPlaceholderConfigurer'以及在這種情況下)。 –

+0

謝謝你,我已經實現了接受的答案,它的工作得很好,但我會看看Spring Boot docs,thx的建議, – JBoy

回答

2

一個容易和簡單的解決方案是使用屬性'spring.profiles.active'的值加載正確的application.properties。

在您的例子,這將是這樣的:

@Configuration 
@ComponentScan(basePackages = "my.base.package") 
@PropertySource({ "classpath:application.properties", "classpath:application-${spring.profiles.active}.properties"}) 
public class ServiceSpringConfiguration 

注意,該解決方案配備了一個問題,因爲你可以有severals活泉水配置文件,它不會工作了。

另一個解決方案是通過配置文件來創建severals配置類:

@Configuration 
@Profile('dev') 
@PropertySource("classpath:application-dev.properties") 
public class Devconfiguration { 
} 

@Configuration 
@Profile('prod') 
@PropertySource("classpath:application-prod.properties") 
public class Prodconfiguration { 
}