javascript
Springboot-读取核心配置文件及自定义配置文件
讀取核心配置文件
核心配置文件是指在resources根目錄下的application.properties或application.yml配置文件,讀取這兩個配置文件的方法有兩種,都比較簡單。
核心配置文件application.properties內(nèi)容如下:
server.port=9090 test.msg=Hello World Springboot!?-
使用@Value方式(常用)
?
注意:在@Value的${}中包含的是核心配置文件中的鍵名。在Controller類上加@RestController表示將此類中的所有視圖都以JSON方式顯示,類似于在視圖方法上加@ResponseBody。
訪問:http://localhost:9090/index?時將得到The Way 1 : Hello World Springboot!
-
使用Environment方式
訪問:http://localhost:9090/index2?時將得到The Way 2 : Hello World Springboot!
讀取自定義配置文件
-
通過@ConfigurationProperties注解,通過getter、setter方法注入及獲取配置
為了不破壞核心文件的原生態(tài),但又需要有自定義的配置信息存在,一般情況下會選擇自定義配置文件來放這些自定義信息,這里在resources/config目錄下創(chuàng)建配置文件my-web.properties
resources/config/my-web.properties內(nèi)容如下:
web.name=isea533web.jdbc.username=root
web.jdbc.password=root?
創(chuàng)建管理配置的實體類:
@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web") @Component public class MyWebConfig{private String name;private Jdbc jdbc;class Jdbc {private String username;private String password;//getter... }public Integer gePort(){return this.port;}public Jdbc getJdbc() {return this.jdbc;} } 注意:在@ConfigurationProperties注釋中有兩個屬性:
- locations:指定配置文件的所在位置
- prefix:指定配置文件中鍵名稱的前綴(我這里配置文件中所有鍵名都是以web.開頭)
使用@Component是讓該類能夠在其他地方被依賴使用,即使用@Autowired注釋來創(chuàng)建實例。
-
通過@PropertySource注解,然后使用@Value逐個注入配置
?
?轉載于:https://www.cnblogs.com/junzi2099/p/7509045.html
總結
以上是生活随笔為你收集整理的Springboot-读取核心配置文件及自定义配置文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java标识符的规则等
- 下一篇: Linux命令2