之前寫過一篇獲取properties文件裏面的值:
Springboot 指定獲取自己寫的配置properties文件的值
https://blog.csdn.net/qq_35387940/article/details/90714123
現在補充多一篇,指定獲取yml裏面的配置值 。
內容:
這裏分別介紹兩種方式,都是基於註解實現,分別是:
@Value("${xxxxx.xx}")
@ConfigurationProperties(prefix = "xxxxx")
進入主題:
@Value("${xxxxx.xx}")
使用這種方式非常簡單(每一個註解獲取一個對應的配置值),
在yml裏面加入我們的自定義配置項,如(大小寫隨意,調用時對應好就行):
指定獲取這些值去使用,如:
@Value("${myKey.tua}")
private String tuaKey;
@Value("${myKey.aco}")
private String acoKey;
@Value("${mynum.new}")
private String myNum;
@GetMapping("/getMyTest")
public void getMyTest(){
System.out.println("tuaKey:"+tuaKey);
System.out.println("acoKey:"+acoKey);
System.out.println("myNum:"+myNum);
}
可以看到結果,獲取正常:
@ConfigurationProperties(prefix = "xxxxx")
使用這種方式也非常簡單(一次性將多個配置值獲取並示例化成bean放入到spring容器裏面),
在yml裏面加入我們的自定義配置項,如(注意,使用一開始的key參數使用小寫,使用大寫會出錯,因爲prefix不支持駝峯命名和下劃線形式):
然後我們建一個對於這些配置項的實體類,並使用上註解 @ConfigurationProperties ,如:
prefix指前綴,一般也就是第一個,我們這個例子的第一個是myinfo
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author : JCccc
* @CreateTime : 2020/5/19
* @Description :
**/
@Component
@ConfigurationProperties(prefix = "myinfo")
public class MyInfo {
private String name;
private Integer age;
private String description;
@Override
public String toString() {
return "MyTest{" +
"name='" + name + '\'' +
", age=" + age +
", description='" + description + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
指定獲取這些值去使用,也就是相當於使用這個類,直接配合@Autowired 使用即可:
@Autowired
MyInfo myInfo;
@GetMapping("/getMyTest")
public void getMyTest(){
System.out.println("myInfo:"+myInfo.toString());
System.out.println("myInfo name:"+myInfo.getName());
}
可以看到結果,獲取正常:
ok,該篇就到此。