一、配置文檔配置項的調用
啟動后在瀏覽器直接輸入http://localhost:18080/user/test,就直接打印出配置文件中的配置內容。
二、綁定對象bean調用
有時候屬性太多了,一個個綁定到屬性字段上太累,官方提倡綁定一個對象的bean,這里我們建一個configbean.java類,頂部需要使用注解@configurationproperties(prefix = “com”)來指明使用哪個
1
2
3
4
5
6
7
|
@configurationproperties (prefix = "com" ) public class configbean { private string name; private string id; // 省略getter和setter } |
這里配置完還需要在spring boot入口類加上@enableconfigurationproperties并指明要加載哪個bean,如果不寫configbean.class,在bean類那邊添加
1
2
3
4
5
6
7
|
@springbootapplication @enableconfigurationproperties ({configbean. class }) public class chapter2application { public static void main(string[] args) { springapplication.run(chapter2application. class , args); } } |
最后在controller中引入configbean使用即可,如下:
1
2
3
4
5
6
7
8
9
10
|
@restcontroller public class usercontroller { @autowired configbean configbean; @requestmapping ( "/" ) public string hexo(){ return configbean.getname()+configbean.getid(); } } |
三、參數間引用
在application.properties中的各個參數之間也可以直接引用來使用,就像下面的設置:
1
2
3
|
com.name= "張三" com.id= "8" com.psrinfo=${com.name}編號為${com.id} |
這樣我們就可以只是用psrinfo這個屬性就好
四、使用自定義新建的配置文件
我們新建一個bean類,如下:
1
2
3
4
5
6
7
8
|
@configuration @configurationproperties (prefix = "com.md" ) @propertysource ( "classpath:test.properties" ) public class configtestbean { private string name; private string want; // 省略getter和setter } |
主要就是加了一個注解:@propertysource("classpath:test.properties")
五、配置文件優先級
application.properties和application.yml文件可以放在一下四個位置:
- 外置,在相對于應用程序運行目錄的/congfig子目錄里。
- 外置,在應用程序運行的目錄里
- 內置,在config包內
- 內置,在classpath根目錄
同樣,這個列表按照優先級排序,也就是說,src/main/resources/config下application.properties覆蓋src/main/resources下application.properties中相同的屬性,如圖:
此外,如果你在相同優先級位置同時有application.properties和application.yml,那么application.yml里面的屬性就會覆蓋application.properties里的屬性。
ps:下面看下springboot讀取application.properties文件
springboot讀取application.properties文件,通常有3種方式
1. @value 例如:
1
2
|
@value ( "${spring.profiles.active}" ) private string profileactive;------相當于把properties文件中的spring.profiles.active注入到變量profileactive中 |
2. @configurationproperties 例如:
1
2
3
4
5
6
|
@component @configurationproperties (locations = "classpath:application.properties" ,prefix= "test" ) public class testproperties { string url; string key; } |
其他類中使用時,就可以直接注入該testproperties 進行訪問相關的值
3. 使用enviroment 例如:
1
2
|
private enviroment env; env.getproperty( "test.url" ); |
而env方式效率較低
注:@configurationproperties也可用于其他.properties文件,只要locations指定即可
總結
以上所述是小編給大家介紹的spring boot中配置文件application.properties使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/gczr/p/6692054.html