本地和产品环境的不同属性变量(春季)

本地和产品环境的不同属性变量(春季),第1张

本地和产品环境的不同属性变量(春季)

您可以基于当前的一个或多个d簧轮廓来加载属性。要设置d簧轮廓,我主要将系统属性设置为

spring.profiles.active
所需的值,例如
development
production

这个概念很简单。从系统属性中读取当前活动的配置文件。生成文件名并使用加载属性文件

PropertySourcesPlaceholderConfigurer
。使用
PropertySourcesPlaceholderConfigurer
会更容易通过
@Value
注释访问这些属性。请注意,此示例假定一个配置文件处于活动状态。当多个配置文件处于活动状态时,可能需要格外小心。

基于Java的配置

@Configurationpublic class MyApplicationConfiguration {    @Bean    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {        String activeProfile = System.getProperty("spring.profiles.active", "production");        String propertiesFilename = "app-" + activeProfile + ".properties";        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();        configurer.setLocation(new ClassPathResource(propertiesFilename));        return configurer;    }}

您还可以导入带有注释的多个配置类

@Profile
。Spring将根据当前活动的配置文件选择要使用的配置。每个类都可以将其自己的版本添加
PropertySourcesPlaceholderConfigurer
到应用程序上下文中。

@Configuration@import({Development.class, Production.class})public class MyApplicationConfiguration {}@Configuration@Profile("development")public class Development {}@Configuration@Profile // The defaultpublic class Production {}

正如Emerson
Farrugia在评论中所指出的,

@Profile
选择班级方法有点过于激烈
PropertySourcesPlaceholderConfigurer
。注释
@Bean
声明会容易得多。

@Configurationpublic class MyApplicationConfiguration {    @Bean    @Profile("development")    public static PropertySourcesPlaceholderConfigurer developmentPropertyPlaceholderConfigurer() {        // instantiate and return configurer...    }    @Bean    @Profile // The default    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {        // instantiate and return configurer...    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5651397.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存