JBo*_*Boy 0 configuration spring
所以我有一个Spring 4应用程序。它包含3个属性文件:
application.properties
application-dev.properties
application-prod.properties
Run Code Online (Sandbox Code Playgroud)
在application.properties的标题中,我指定了所需的配置文件:
spring.profiles.active=dev
Run Code Online (Sandbox Code Playgroud)
因此,在其他两个文件中:
application-dev.properties
application-prod.properties
Run Code Online (Sandbox Code Playgroud)
我在他们之间有重复的条目,所以可以说在dev文件中我有:
host=foo
在产品中我有:
host=bar
Spring然后根据当前活动的配置文件获取值。为了告诉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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是我注意到,以这种方式,Spring从所有文件中加载了所有属性,并且不允许重复,并且无论配置文件如何,都只加载了您要求的属性。如何告诉Spring根据所选配置文件加载文件?我希望Spring扫描文件名并尝试匹配配置文件名。
顺便说一句,我指的是这样的财产:
@Value("${host}")
private String host;
Run Code Online (Sandbox Code Playgroud)
一种简单的解决方案是使用属性“ spring.profiles.active”的值来加载正确的application.properties。
在您的示例中,它将是这样的:
@Configuration
@ComponentScan(basePackages = "my.base.package")
@PropertySource({ "classpath:application.properties", "classpath:application-${spring.profiles.active}.properties"})
public class ServiceSpringConfiguration
Run Code Online (Sandbox Code Playgroud)
请注意,此解决方案会带来问题,因为您可能有多个活动的弹簧轮廓,并且它将不再起作用。
另一个解决方案是按配置文件创建几个配置类:
@Configuration
@Profile('dev')
@PropertySource("classpath:application-dev.properties")
public class Devconfiguration {
}
Run Code Online (Sandbox Code Playgroud)
和
@Configuration
@Profile('prod')
@PropertySource("classpath:application-prod.properties")
public class Prodconfiguration {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4224 次 |
| 最近记录: |