springboot如何讀取配置文件到靜態(tài)工具類
springboot讀取配置文件到靜態(tài)工具類
通常我們讀取配置文件可以用@Value注解和@Configuration,@ConfigurationProperties(prefix = "xxx")等注解,但是這種方式是無法把配置讀取到靜態(tài)變量的,如果我們想在項(xiàng)目初始化時(shí)把配置文件加載到一個(gè)工具類,然后通過靜態(tài)變量的方式調(diào)用的話我們就不能使用這兩種方法。
我們可以用Environment 來解決
不廢話了,直接上代碼
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
*
* @Description: 配置常量類——根據(jù)不同的spring-profile加載不同的配置
* @author: eric.zhang
* @date: 2018年7月20日 上午10:59:24
*/
@Component
public class ConfigConstant {
@Autowired
private Environment env;
public static String url;
public static String param;
@PostConstruct
public void readConfig() {
url = env.getProperty("config.url");
param = env.getProperty("config.param");
}
}
我寫完以后發(fā)現(xiàn)有些麻煩,下面是改進(jìn)的方法,不需要每個(gè)配置都去get一下,只需要把配置文件的key與工具類的靜態(tài)變量名寫成一樣的即可。
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
*
* @Description: 配置常量類——根據(jù)不同的spring-profile加載不同的配置,變量名要與配置文件里寫的名一致
* @author: eric.zhang
* @date: 2018年7月20日 上午10:59:24
*/
@Component
public class ConfigConstant {
@Autowired
private Environment env;
public static String url;
public static String name;
@PostConstruct
public void readConfig() throws Exception {
String prefix = "config.";
Field[] fields = ConfigConstant.class.getFields();
for(Field field : fields ){
field.set(null, getProperty(prefix + field.getName()));
}
}
private String getProperty(String key) throws UnsupportedEncodingException {
return new String(env.getProperty(key).getBytes("ISO-8859-1"), "UTF-8");
}
}
大哥說這樣寫依賴spring, 單測(cè)調(diào)代碼的時(shí)候不方便,所以又寫了一個(gè)不依賴spring的版本。
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Properties;
/**
*
* @Description: 配置常量類——根據(jù)不同的spring-profile加載不同的配置
* 變量名把配置文件的key中的"."替換成"_"命名
* @author: eric.zhang
* @date: 2018年7月20日 上午10:59:24
*/
public class ConfigConstant {
public static String CONFIG_URL;
public static String CONFIG_NAME;
static {
try {
Properties props = new Properties();
props.load(new InputStreamReader(
ConfigConstant.class.getClassLoader().getResourceAsStream("application.properties"),
"UTF-8"));
String profile = props.getProperty("spring.profiles.active");
String envFile = "application-" + profile + ".properties";
Properties envProps = new Properties();
envProps.load(new InputStreamReader(
ConfigConstant.class.getClassLoader().getResourceAsStream(envFile), "UTF-8"));
Field[] fields = ConfigConstant.class.getFields();
for (Field field : fields) {
field.set(null, envProps.getProperty(field.getName().replace("_", ".").toLowerCase()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
將配置文件的值加載到工具類的靜態(tài)變量中(多環(huán)境運(yùn)行加載)
首先創(chuàng)建一個(gè)SpringBoot項(xiàng)目
項(xiàng)目結(jié)構(gòu):

創(chuàng)建pom文件,映入maven工程依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.csrcb</groupId>
<artifactId>spring_static</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
創(chuàng)建配置文件
在resource目錄下,創(chuàng)建配置文件application.yml,創(chuàng)建幾個(gè)不同環(huán)境的application-dev,application-sit、application-prod.yml的配置文件,稍后做測(cè)試使用,看是否加載不同環(huán)境下的配置參數(shù)的值
application.yml很簡(jiǎn)單就一個(gè)端口號(hào)的配置:

在application-dev.yml(開發(fā)環(huán)境的配置參數(shù)的值)、以及sit(測(cè)試)、uat(驗(yàn)證)、prod(生產(chǎn))環(huán)境設(shè)置一些值

不同環(huán)境下的測(cè)試的配置參數(shù)的值不一致,為了測(cè)試參數(shù)名設(shè)置相同下,是否取得對(duì)應(yīng)運(yùn)行環(huán)境的值
創(chuàng)建實(shí)體類
1.創(chuàng)建加載配置文件的配置類
/**
* @Classname TestConfig
* @Description 加載配置文件的配置類
* @Date 2020/6/16 16:28
* @Created by gangye
*/
@Configuration
@Data
public class TestConfig {
@Value("${ftp.username}")
private String username;
@Value("${ftp.passwd}")
private String passwd;
@PostConstruct
public void init(){
ClientUtil.setConfigInfo(this);
}
}
2.創(chuàng)建工具類,工具類獲得配置類的參數(shù)值
/**
* @Classname ClientUtil
* @Description 工具類,將配置文件的數(shù)據(jù)通過config引入到靜態(tài)變量中
* @Date 2020/6/16 16:29
* @Created by gangye
*/
@Slf4j
public class ClientUtil {
private static String USERNAME;
private static String PASSWD;
public static void setConfigInfo(TestConfig testConfig) {
ClientUtil.USERNAME = testConfig.getUsername();
ClientUtil.PASSWD = testConfig.getPasswd();
}
public static String getValue(){
log.info("獲得配置文件的username的值:{}",USERNAME);
return USERNAME;
}
}
3.創(chuàng)建路由,模擬調(diào)用
/**
* @Classname controller
* @Date 2020/6/16 16:35
* @Created by gangye
*/
@RestController
@RequestMapping(value = "/test")
public class TestController {
@GetMapping("/getvalue")
public String getValue(){
return ClientUtil.getValue();
}
}
4.創(chuàng)建啟動(dòng)類,在啟動(dòng)類中添加Bean,為了防止啟動(dòng)時(shí)配置類的@Value注解找不到配置文件中的值,一個(gè)配置文件找不到繼續(xù)找
/**
* @Classname AppStart
* @Description 啟動(dòng)類
* @Date 2020/6/16 16:26
* @Created by gangye
*/
@SpringBootApplication
public class AppStart {
public static void main(String[] args) {
SpringApplication.run(AppStart.class,args);
}
}
啟動(dòng)時(shí)添加對(duì)應(yīng)的運(yùn)行環(huán)境設(shè)置

-Dspring.profiles.active=sit
若springboot版本低可能會(huì)出現(xiàn)
java.lang.IllegalArgumentException: Could not resolve placeholder ‘username' in value “${ftp.username}”這樣的報(bào)錯(cuò)
解決辦法:在啟動(dòng)類中添加下面的代碼
/**
* Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder ‘name' in value “${name}”
* @Description 為了防止啟動(dòng)時(shí)配置類的@Value注解找不到配置文件中的值,一個(gè)配置文件找不到繼續(xù)找
* @Date 2020年6月17日14:40:08
* @return
*/
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
c.setIgnoreUnresolvablePlaceholders(true);
return c;
}

再次啟動(dòng)環(huán)境(sit下)
在瀏覽器中輸入:http://localhost:8000/test/getvalue

再指定prod環(huán)境下的運(yùn)行

使用瀏覽器請(qǐng)求路由

關(guān)鍵使用了@Value注解以及@PostConstruct注解
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring boot使用logback日志級(jí)別打印控制操作
這篇文章主要介紹了spring boot使用logback日志級(jí)別打印控制操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
使用SpringBoot中的Schedule定時(shí)發(fā)送郵件的方法
在SpringBoot中,你可以使用@Scheduled注解來創(chuàng)建定時(shí)任務(wù),@Scheduled注解可以應(yīng)用于方法上,表示這個(gè)方法是一個(gè)定時(shí)任務(wù),可以根據(jù)指定的時(shí)間間隔或固定時(shí)間執(zhí)行,本文就給大家介紹一下如何使用SpringBoot中的Schedule定時(shí)發(fā)送郵件,需要的朋友可以參考下2023-08-08
JDK8通過Stream 對(duì)List,Map操作和互轉(zhuǎn)的實(shí)現(xiàn)
這篇文章主要介紹了JDK8通過Stream 對(duì)List,Map操作和互轉(zhuǎn)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Java實(shí)現(xiàn)簡(jiǎn)單文件過濾器功能
下面小編就為大家分享一篇Java實(shí)現(xiàn)簡(jiǎn)單文件過濾器功能,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01
本地編譯打包項(xiàng)目部署到服務(wù)器并且啟動(dòng)方式
這篇文章主要介紹了本地編譯打包項(xiàng)目部署到服務(wù)器并且啟動(dòng)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Java基本概念監(jiān)視器實(shí)習(xí)原理解析
這篇文章主要介紹了Java基本概念監(jiān)視器實(shí)習(xí)原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Java如果在try里面執(zhí)行return還會(huì)不會(huì)執(zhí)行finally
這篇文章主要介紹了Java如果在try里面執(zhí)行return,那么還會(huì)不會(huì)執(zhí)行finally,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
Spring AOP如何實(shí)現(xiàn)注解式的Mybatis多數(shù)據(jù)源切換詳解
這篇文章主要給大家介紹了關(guān)于Spring AOP如何實(shí)現(xiàn)注解式的Mybatis多數(shù)據(jù)源切換的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

