java讀取配置文件自定義字段(yml、properties)
一、概述
在springboot項(xiàng)目配置文件中設(shè)置自定義字段,項(xiàng)目代碼按需讀取,想換重要參數(shù)時(shí)直接更改配置文件即可,這篇文章說(shuō)一說(shuō)配置文件自定義字段的方法。
二、實(shí)現(xiàn)方法
方法1 @Value
使用org.springframework.beans.factory.annotation包下的@Value注解讀取yml文件里面的字段,代碼如下:
yml文件
server: port: 8080 #自定義參數(shù)字段 student: name: Simon age: 23 sex: male height: 185
讀取
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Value("${student.name}")
private String name;
@Value("${student.age}")
private String age;
@Value("${student.sex}")
private String sex;
@Value("${student.height}")
private String height;
@RequestMapping("/1")
public Object test(){
log.info("我叫"+name+",性別是:"+sex+",今年"+age+"歲,我還是個(gè)"+height+"cm大高個(gè)的帥小伙!");
return "我叫"+name+",性別是:"+sex+",今年"+age+"歲,我還是個(gè)"+height+"cm大高個(gè)的帥小伙!";
}
}測(cè)試結(jié)果

方法2:Environment
與@value類似,注入Environment通過(guò)配置參數(shù)的前綴拿到任何配置文件里配置參數(shù)的值,優(yōu)點(diǎn)是隨時(shí)隨地,便捷,但是配置參數(shù)數(shù)量多的時(shí)候,會(huì)造成代碼冗余。
/**
* @ClassName TestController
* @Author
* @Date 2023/2/28 0028 16:52
*/
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private Environment environmentConfig;
@PostMapping("/environment")
public String testEnvironment(){
String number = environmentConfig.getProperty("school.role.teacher.number");
String age = environmentConfig.getProperty("student.age");
System.out.println("number = " + number);
System.out.println("age = " + age);
return null;
}
}
方法3:@PropertySource()、@ConfigurationProperties()
組合使用@PropertySource()、@ConfigurationProperties()兩個(gè)注解對(duì)springboot項(xiàng)目的properties配置文件的的讀取。
properties文件
student.name=simon student.age=23 student.sex=male student.height= 185 student.self-assessment=handsome
?。?!注意:這里與方法一yml文件采取@Value的方式讀取不同,讀取properties文件需要建一個(gè)讀取類(Studentconfig),將properties文件中想讀取得字段都注入進(jìn)去作為該類的屬性,再將Student通過(guò)@Configuration注解將其當(dāng)作Bean交給容器管理,需要用的時(shí)候?qū)tudent整個(gè)類注入,在調(diào)用get方法得到其屬性(即配置文件中的自定義字段)
StudentConfig類
@Configuration
@PropertySource("classpath:application.properties")//讀取配置文件
@ConfigurationProperties(prefix="student")//讀取節(jié)點(diǎn)
@Data
public class StudentConfig {
private String name;
private String sex;
private int age;
private int height;
private String selfAssessment;
}細(xì)節(jié)注意
Configuration注解的prefix有書寫規(guī)范,據(jù)我本人經(jīng)驗(yàn)總結(jié)
- 不可用大寫字母
- 不可寫下劃線,兩個(gè)單詞需隔開的話使用橫線
- 不能使用數(shù)字(有博主說(shuō)可以用數(shù)字我自己試了下是不可以的,希望大家避坑)




讀?。▽tudentConfig整個(gè)類注入,再使用get方法調(diào)用)
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private StudentConfig student;
@RequestMapping("/properties")
public Object test2(){
return "我叫"+student.getName()+"" +
",性別是:"+student.getSex()+
",今年"+student.getAge()+
"歲,我還是個(gè)"+student.getHeight()+"cm大高個(gè)的帥小伙!" +
"我對(duì)自己的評(píng)價(jià)是"+student.getSelfAssessment();
}得到結(jié)果

三、使用@value注解讀取yml失效的場(chǎng)景及解決辦法
springboot項(xiàng)目中常用到@value這個(gè)注解來(lái)獲取yml配置文件中的值。但是實(shí)際開發(fā)中我們常常會(huì)忽略的的幾個(gè)導(dǎo)致它失效的原因
1.@value("${pdf.saveUrl}")當(dāng)中的路徑問(wèn)題。這也是大家所熟知的。
2.@value修飾的變量是final、static關(guān)鍵字。(這個(gè)是我們?nèi)粘懘a中常常遇到的,也是我親身經(jīng)歷的問(wèn)題。)
3.構(gòu)造方法調(diào)用該注解修飾的字段也會(huì)失效,大家不妨嘗試一下。
4.實(shí)體類沒有@Component或這@Service或者別的能注入類的注解。也會(huì)失效。
5.采用new class來(lái)創(chuàng)建對(duì)象,調(diào)用@value修飾的字段,也同樣會(huì)失效,實(shí)際開發(fā)中我們還是要用spring的ioc容器來(lái)創(chuàng)建該對(duì)象,@Autowired,@Resource或者構(gòu)造器的方式(這個(gè)是千萬(wàn)不能范的錯(cuò)誤寫法)
四、嵌套讀取properties文件的方法(讀取類繼承HashMap類)
在項(xiàng)目中有時(shí)候需要接入許多不同的企業(yè),每個(gè)企業(yè)需要不同的配置參數(shù),將不同的配置參數(shù)寫到配置文件,通過(guò)企業(yè)傳遞來(lái)的值取得不同的配置參數(shù)。
這里以學(xué)校的老師和學(xué)生為例,在不同角色和不同科目下得到的參數(shù)信息
配置文件
#老師 ##人數(shù) school.role.teacher.number=50 ##老師著裝 school.role.teacher.wearing=suit ##職責(zé) school.role.teacher.job=teach ##科目 ###數(shù)學(xué)老師的stereotype ####性格 school.role.teacher.subject.math.character=serious ####性別 school.role.teacher.subject.math.sex=male ####年齡 school.role.teacher.subject.math.age=old ###英語(yǔ)老師的imagination ####性格 school.role.teacher.subject.english.character= optimistic ####性別 school.role.teacher.subject.english.sex=female ####年齡 school.role.teacher.subject.english.age=young #學(xué)生 #數(shù)量 school.role.student.number=1000 #學(xué)生著裝 school.role.student.wearing=uniform #任務(wù) school.role.student.job=study ##科目 ###數(shù)學(xué)課上表現(xiàn) school.role.student.subject.math.performance=cautious ###英語(yǔ)課上表現(xiàn) school.role.student.subject.english.performance=happy
配置類
package com.example.test.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.HashMap;
/**
* @ClassName TestConfig
* @Author
* @Date 2023/2/28 0028 15:26
*/
@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "school.role")
public class TestConfig extends HashMap<String,TestConfigItem> {
}角色層
package com.example.test.config;
import lombok.Data;
/**
* @ClassName TestConfigItem
* @Author
* @Date 2023/2/28 0028 15:27
*/
@Data
public class TestConfigItem {
/**
* 數(shù)量
*/
private int number;
/**
* 穿著
*/
private String wearing;
/**
* 職責(zé)
*/
private String job;
/**
* 科目
*/
private InnerConfig subject;
}package com.example.test.config;
import lombok.Data;
import java.util.HashMap;
/**
* @ClassName InnerConfig
* @Author
* @Date 2023/2/28 0028 15:48
*/
@Data
public class InnerConfig extends HashMap<String,InnerConfigItem> {
}科目層
package com.example.test.config;
import lombok.Data;
/**
* @ClassName InnerConfigItem
* @Author
* @Date 2023/2/28 0028 15:49
*/
@Data
public class InnerConfigItem {
/**
* 性格
*/
private String character;
/**
*性別
*/
private String sex;
/**
*年齡
*/
private String age;
/**
*學(xué)生表現(xiàn)
*/
private String performance;
}讀取
package com.example.test.controller;
import com.example.test.config.InnerConfigItem;
import com.example.test.config.TestConfig;
import com.example.test.config.TestConfigItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName TestController
* @Author
* @Date 2023/2/28 0028 16:52
*/
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestConfig config;
@GetMapping("/properties/{role}/{subject}")
public String testProperties(@PathVariable String role,@PathVariable String subject){
String result= null;
TestConfigItem testConfigItem = config.get(role);
int number = testConfigItem.getNumber();
String wearing = testConfigItem.getWearing();
String job = testConfigItem.getJob();
InnerConfigItem innerConfigItem = testConfigItem.getSubject().get(subject);
String age = innerConfigItem.getAge();
String character = innerConfigItem.getCharacter();
String sex = innerConfigItem.getSex();
if ("student".equals(role)){
String performance = innerConfigItem.getPerformance();
result = "目前角色是"+role+",人數(shù)為"+number+",職責(zé)是"+job+",穿著"+wearing+"。在"+subject+"課上的表現(xiàn)是"+performance+"。";
return result;
}
result = "目前角色是"+role+",人數(shù)為"+number+",職責(zé)是"+job+",穿著"+wearing+"。" +
"在"+subject+"課上是"+character+"的,年齡是"+age+",性別是"+sex+"。";
return result;
}
}結(jié)果




到此這篇關(guān)于java讀取配置文件自定義字段(yml、properties)的文章就介紹到這了,更多相關(guān)java讀取配置文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot多數(shù)據(jù)源實(shí)現(xiàn)方式
本文介紹了多數(shù)據(jù)源配置的重要性以及在SpringBoot中如何配置單個(gè)默認(rèn)數(shù)據(jù)源和多個(gè)數(shù)據(jù)源,此外,還討論了如何整合MyBatis、實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源路由、事務(wù)管理以及使用dynamic-datasource-spring-boot-starter框架來(lái)簡(jiǎn)化多數(shù)據(jù)源管理2025-01-01
手寫java性能測(cè)試框架的實(shí)現(xiàn)示例
這篇文章主要為大家介紹了java實(shí)現(xiàn)性能測(cè)試框架示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
解決java轉(zhuǎn)義json出現(xiàn)\u0000 等亂碼的問(wèn)題
這篇文章主要介紹了解決java轉(zhuǎn)義json出現(xiàn)\u0000 等亂碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
Java根據(jù)模板導(dǎo)出Excel報(bào)表并復(fù)制模板生成多個(gè)Sheet頁(yè)
本文主要介紹了Java根據(jù)模板導(dǎo)出Excel報(bào)表并復(fù)制模板生成多個(gè)Sheet頁(yè)的方法,具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-03-03

