栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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...    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/649203.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号