SpringBoot獲取配置文件中的配置項的常用方式
SpringBoot中獲取配置項的常用方式
主要是@Value注解、使用Environment對象、@ConfigurationProperties注解
在application.properties配置文件中,有一個配置項:test.config.version=111
配置項的名稱是:test.config.version,對應(yīng)的值為111

在SpringBoot中,如何獲取它的具體值?
一、@Value注解
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
// 冒號后面可以設(shè)置該配置項的默認(rèn)缺省值,當(dāng)這個配置項不存在或者值為空的時候,它的值就是冒號后面的值
@Value("test.config.version:222")
private String conf;
@RequestMapping("/config2")
public String getConfig2(){
log.info("test.config.version :{} " , conf);
return conf;
}
}
結(jié)果:

二、使用Environment對象
實現(xiàn)EnvironmentAware接口,讓spring把environment對象注入到要使用它的bean中,調(diào)用getProperty方法獲取配置項的值。
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController implements EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@RequestMapping("/config1")
public String getConfig1(){
log.info("test.config.version :{} " ,environment.getProperty("test.config.version"));
return environment.getProperty("test.config.version");
}
}
結(jié)果:

三、@ConfigurationProperties注解
寫一個配置類,利用@ConfigurationProperties注解來指定該類對應(yīng)的配置項的前綴,成員變量的名字就是配置項的后綴,這個類的成員變量用于承接對應(yīng)的配置項的值。
@Data注解是Lombok提供的,可以自動生成getter和setter。
@Component
@ConfigurationProperties(prefix = "test.config")
@Data
public class TestConf {
// 相當(dāng)于test.config.version的值,就注入到了該成員變量中
private String version;
}
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController implements EnvironmentAware {
@Resource
TestConf testConf;
@RequestMapping("/config3")
public String getConfig3(){
log.info("test.config.version :{} " , testConf.getVersion());
return testConf.getVersion();
}
}
結(jié)果:

到此這篇關(guān)于SpringBoot獲取配置文件中的配置項的常用方式的文章就介紹到這了,更多相關(guān)SpringBoot獲取配置文件配置項內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
金三銀四復(fù)工高頻面試題java算法LeetCode396旋轉(zhuǎn)函數(shù)
這篇文章主要為大家介紹了金三銀四復(fù)工高頻面試題之java算法題解LeetCode396旋轉(zhuǎn)函數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

