Spring中讀取配置文件的五種方式
Spring中讀取配置文件的五種方式
- @Value:只能讀取單個配置項
- @ConfigurationProperties:可以一次性讀取多個配置項,將多個配置項轉(zhuǎn)換為Bean對象。需要配合prefix使用。
- @PropertySource+@Value:獲取自定義配置文件的單個配置項。
- @PropertySource+@ConfigurationProperties:獲取自定義配置文件的多個配置項。
- Environment的getProperty方法獲取,很少使用。
舉例說明:
第一種:@Value注解方式獲取
application.yml
server: port: 9201
取值方式:
@Value("${server.port}")
private String port;
第二種:@ConfigurationProperties注解方式獲取
application.yml
student: name: 張三 age: 18
取值方式:
@Configuration
@ConfigurationProperties(prefix = "student")
public class CaptchaProperties{
private String name;
private Integer age;
...
}
注:需要配和@Component使用,本文中使用的@Configuration,我們查看Configuration注解會發(fā)現(xiàn)它使用了@Component注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
...
}
第三種:@PropertyResource + @Value注解方式獲取,可讀取自定義配置文件。只支持讀取.properties類型的配置文件,yml類型的配置文件需要自定義。
student.properties
student.name = 張三 student.age = 18
取值方式:
@Component
@PropertyResouce(value = "classpath:student.properties")
public class Student implements Serializable{
@Value("${student.name}")
private String name;
@Value("${student.age}")
private Integer age;
...
}
第四種:@PropertyResource + @ConfigurationProperties注解方式獲取,可讀取自定義配置文件。只支持讀取.properties類型的配置文件,yml類型的配置文件需要自定義。
student.properties
student.name = 張三 student.age = 18
取值方式:
/**
* @Component標識為是Spring的一個組件,只有容器組件,容器才會為ConfigurationProperties提供此注入共
* 功能
*/
@Component
@PropertyResouce(value = "classpath:student.properties")
@ConfigurationProperties(prefix = "student")
public class Student implements Serializable{
private String name;
private Integer age;
...
}
第五種:Environment方式讀取,基本很少使用
application.yml
student: name: 張三 age: 18
取值方式:
...
@Autowired
private Environment env;
public String getUserName(){
return env.getProperty("student.name");
}
...
以上就是Spring中讀取配置文件的五種方式的詳細內(nèi)容,更多關于Spring讀取配置文件的資料請關注腳本之家其它相關文章!
相關文章
SpringBoot和VUE源碼直接整合打包成jar的踩坑記錄
這篇文章主要介紹了SpringBoot和VUE源碼直接整合打包成jar的踩坑記錄,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
IDEA新建springboot項目時未生成pom.xml文件的解決操作
這篇文章主要給大家介紹了關于IDEA新建springboot項目時未生成pom.xml文件的解決操作方法,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2023-02-02
Java實現(xiàn)獲取指定個數(shù)的不同隨機數(shù)
今天小編就為大家分享一篇關于Java實現(xiàn)獲取指定個數(shù)的不同隨機數(shù),小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Spring Security跳轉(zhuǎn)頁面失敗問題解決
這篇文章主要介紹了Spring Security跳轉(zhuǎn)頁面失敗問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-01-01
使用Spring?Batch實現(xiàn)大數(shù)據(jù)處理的操作方法
通過使用Spring?Batch,我們可以高效地處理大規(guī)模數(shù)據(jù),本文介紹了如何配置和實現(xiàn)一個基本的Spring?Batch作業(yè),包括讀取數(shù)據(jù)、處理數(shù)據(jù)和寫入數(shù)據(jù)的全過程,感興趣的朋友跟隨小編一起看看吧2024-07-07

