首页 >> 知识 >> SpringBoot根据环境加载不同的properties配置文件

SpringBoot根据环境加载不同的properties配置文件

一、背景需求 在项目中遇到多个环境配置的问题,yml可以配置springboot的配置,自己想自定义properties文件来配置自定义的内容,避免频繁改环境引起配置文件频繁修改,可以实现不同的环境加载不同的properties自定义的配置文件。 二、问题解决 采用springboot自带的@Profile注解来加载不同的properties配置文件,实现不同的环境加载不同的properties配置文件; 目录结构如下: application-${env}.yml是springboot各个环境的具体配置,config_dev.properties和config_prod.properties对应开发环境和生产环境的自定义配置,spring.profile.active指定了采用了那个环境,根据采用的环境来加载自定义配置文件; 三、代码配置 application-dev.properties

配置client网关调用本地测试API的地址client.access.ip = 172.23.17.178 配置client网关调用本地测试API的端口client.access.port = 9080 配置client网关调用Remote API的公共前缀client.access.prefix = /api/yjs/v1/index/

application-prod.properties

配置client网关调用Remote API的地址yjs.client.access.ip = api.ok.un-net.com 配置client网关调用Remote API的端口yjs.client.access.port = 80 配置client网关调用Remote API的公共前缀yjs.client.access.prefix = /api/yjs/v1/index/

开发环境的自定义配置文件加载

package com.careland.processonline.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile;import org.springframework.context.annotation.PropertySource;import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;@Profile("dev")@Configuration@PropertySource(value = "classpath:conf/application-dev.properties", ignoreResourceNotFound = true, encoding = "UTF-8")public class PropertyDevelopmentConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }}

生产环境的自定义配置文件加载

package com.careland.processonline.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile;import org.springframework.context.annotation.PropertySource;import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;@Profile("prod")@Configuration@PropertySource(value = "classpath:conf/application-prod.properties", ignoreResourceNotFound = true, encoding = "UTF-8")public class PropertyProductConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }}

自定义配置文件的配置读取类:

package com.careland.processonline.Factory;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component@SuppressWarnings("all")public class PropertyFactory { /**调用API服务的IP地址*/ private static String ACCESS_IP; @Value("${systemconfig.serverip}") public void setAccessIp(String accessIp) { ACCESS_IP = accessIp; } public static String getAccessIp() { return ACCESS_IP; }}
网站地图