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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章