Spring?Boot?如何正確讀取配置文件屬性
前言
項目中經(jīng)常會經(jīng)常讀取配置文件中的屬性的值,Spring Boot提供了很多注解讀取配置文件屬性,那么如何正確使用呢?

@Value
@Value用來讀取application.yml配置文件中屬性的值。
示例代碼
application.yml文件中屬性:
//定義屬性 fileName : test isFile : false filePath : c://test
@value讀取application.yml屬性值:
@Configuration
public class FileConfig
{
@Value("${fileName}")
private final String fileName;
@Value("${isFile}")
private boolean isFile;
@Value("${filePath}")
private static String filePath;
}測試:
@Autowired
private FileConfig fileConfig;
@GetMapping("getFileConfig")
public void getFileConfig()
{
logger.info("fileConfig:{}",fileConfig);
}運行結(jié)果:
fileConfig:FileConfig [fileName=, isFile=false, filePath=null]
特別注意:
- @Value不能將屬性值讀取靜態(tài)變量,否則讀取的值為空。
- @Value不能將屬性值讀取常量,否則讀取的值為空。
- @Value不能讀取boolean類型的值,經(jīng)過測試Spring Boot2.1的版本是無效的,2.2以上版本支持。
所以個人建議非必要情況,盡量少用@Value注解讀取屬性值。
@ConfigurationProperties
讀取配置文件值并且轉(zhuǎn)換成類對象,便于獲取值和修改屬性值。
示例代碼
application.yml文件中屬性:
http:
pool:
# 連接超時
connectTimeout: 5000
#獲取連接池中連接超時
connectionRequestTimeout: 1000
#每個路由連接數(shù)量
defaultMaxPerRoute: 50
# /連接池中最大連接數(shù)
maxTotal: 50
# 服務(wù)器返回數(shù)據(jù)(response)的時間
socketTimeout: 5000
#定義不活動的時間(以毫秒為單位),連接回收
validateAfterInactivity: 30000 @ConfigurationProperties讀取application.yml中以http.pool開頭的屬性值:
//以http.pool開頭
@Component
@ConfigurationProperties(prefix = "http.pool")
public class HttpClientConfig implements Serializable
{
private static final long serialVersionUID = -4608251658338406043L;
/**
* 最大連接數(shù)
*/
private Integer maxTotal;
/**
* 路由是對最大連接數(shù)的細(xì)分
* 每個路由基礎(chǔ)的連接數(shù)
*/
private Integer defaultMaxPerRoute;
/**
* 連接超時時間
*/
private Integer connectTimeout;
/**
* 從連接池中獲取連接的超時時間
*/
private Integer connectionRequestTimeout;
/**
* 服務(wù)器返回數(shù)據(jù)(response)的時間
*/
private Integer socketTimeout;測試:
@GetMapping("getHttpClientConfig")
public void getHttpClientConfig()
{
String json=FastJsonUtil.toJSONString(httpClientConfig);
logger.info("fileConfig:{}",json);
}屬性嵌套:
@ConfigurationProperties 可以嵌套List、map、class
config:
url:http://localhsot:8080
gaode-map:
host: https://restapi.amap.com/v3
key: 1234
@ConfigurationProperties(prefix="config")
public class Config
{
//高德地圖信息
private GaodeMap gaodeMap;
}特別注意:
- 默認(rèn)情況不會將實體注入到spring的容器中,需要結(jié)合
@EnableConfigurationProperties或者@Component一起使用,否則注入對象為空。
@EnableConfigurationProperties
將@ConfigurationProperties讀取對象注入到spring容器中。例如上述示例也可以采用@EnableConfigurationProperties 來注入
@EnableConfigurationProperties(HttpClientConfig.class)
public class FileController
{
private Logger logger = LoggerFactory.getLogger(FileController.class);
@Autowired
private FileConfig fileConfig;
@GetMapping("getHttpClientConfig")
public void getHttpClientConfig()
{
String json=FastJsonUtil.toJSONString(httpClientConfig);
logger.info("fileConfig:{}",json);
}
}@ConfigurationPropertiesScan
用來掃描@ConfigurationProperties實體類并將類注入到Spring容器,上述示例可以如下使用
@ConfigurationPropertiesScan("com.xx.fw.config")
public class FwCoreApplication
{
public static void main(String[] args)
{
SpringApplication.run(FwCoreApplication.class, args);
}
}@PropertySource
@PropertySource 主要用于讀取指定的配置文件,需要結(jié)合@ConfigurationProperties 注解一起使用實現(xiàn)配置文件和Java Bean的注入操作。
示例代碼
屬性文件user.properteis:
user.id=222 user.name=劍圣 user.age=28
實體類定義:
@Component
@ConfigurationProperties(prefix = "user")
@PropertySource(value = {"classpath:user.properties"})
public class UserConfig
{
private String id;
private String name;
private int age;
}測試:
@GetMapping("getUserConfig")
public void getUserConfig()
{
String json=FastJsonUtil.toJSONString(userConfig);
logger.info("userConfig:{}",json);
}輸出結(jié)果:
c.s.fw.controller.FileController - userConfig:{"age":28,"id":"123","name":"admin"}總結(jié)
重點講解了通過各種注解讀取配置文件種屬性值,每種方式都是各自的優(yōu)缺點,項目中一定要統(tǒng)一規(guī)范使用,便于項目維護和排查問題。
到此這篇關(guān)于Spring Boot 如何正確讀取配置文件屬性的文章就介紹到這了,更多相關(guān)Spring Boot 讀取文件屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JSP 開發(fā)之 releaseSession的實例詳解
這篇文章主要介紹了JSP 開發(fā)之 releaseSession的實例詳解的相關(guān)資料,需要的朋友可以參考下2017-07-07
MyBatis中resultType和parameterType和resultMap使用總結(jié)
這篇文章主要介紹了MyBatis中resultType和parameterType和resultMap使用總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
java byte數(shù)組與16進制間相互轉(zhuǎn)換的示例
這篇文章主要介紹了java byte數(shù)組與16進制間相互轉(zhuǎn)換的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-10-10

