Spring Boot中配置文件application.properties使用
一、配置文檔配置項的調用
啟動后在瀏覽器直接輸入http://localhost:18080/user/test,就直接打印出配置文件中的配置內容。
二、綁定對象bean調用
有時候屬性太多了,一個個綁定到屬性字段上太累,官方提倡綁定一個對象的bean,這里我們建一個ConfigBean.java類,頂部需要使用注解@ConfigurationProperties(prefix = “com”)來指明使用哪個
@ConfigurationProperties(prefix = "com") public class ConfigBean { private String name; private String id; // 省略getter和setter }
這里配置完還需要在spring Boot入口類加上@EnableConfigurationProperties并指明要加載哪個bean,如果不寫ConfigBean.class,在bean類那邊添加
@SpringBootApplication @EnableConfigurationProperties({ConfigBean.class}) public class Chapter2Application { public static void main(String[] args) { SpringApplication.run(Chapter2Application.class, args); } }
最后在Controller中引入ConfigBean使用即可,如下:
@RestController public class UserController { @Autowired ConfigBean configBean; @RequestMapping("/") public String hexo(){ return configBean.getName()+configBean.getId(); } }
三、參數間引用
在application.properties中的各個參數之間也可以直接引用來使用,就像下面的設置:
com.name="張三" com.id="8" com.psrInfo=${com.name}編號為${com.id}
這樣我們就可以只是用psrInfo這個屬性就好
四、使用自定義新建的配置文件
我們新建一個bean類,如下:
@Configuration @ConfigurationProperties(prefix = "com.md") @PropertySource("classpath:test.properties") public class ConfigTestBean { private String name; private String want; // 省略getter和setter }
主要就是加了一個注解:@PropertySource("classpath:test.properties")
五、配置文件優(yōu)先級
application.properties和application.yml文件可以放在一下四個位置:
- 外置,在相對于應用程序運行目錄的/congfig子目錄里。
- 外置,在應用程序運行的目錄里
- 內置,在config包內
- 內置,在Classpath根目錄
同樣,這個列表按照優(yōu)先級排序,也就是說,src/main/resources/config下application.properties覆蓋src/main/resources下application.properties中相同的屬性,如圖:
此外,如果你在相同優(yōu)先級位置同時有application.properties和application.yml,那么application.yml里面的屬性就會覆蓋application.properties里的屬性。
ps:下面看下SpringBoot讀取application.properties文件
SpringBoot讀取application.properties文件,通常有3種方式
1. @Value 例如:
@Value("${spring.profiles.active}") private String profileActive;------相當于把properties文件中的spring.profiles.active注入到變量profileActive中
2. @ConfigurationProperties 例如:
@Component @ConfigurationProperties(locations = "classpath:application.properties",prefix="test") public class TestProperties { String url; String key; }
其他類中使用時,就可以直接注入該TestProperties 進行訪問相關的值
3. 使用Enviroment 例如:
private Enviroment env; env.getProperty("test.url");
而env方式效率較低
注:@ConfigurationProperties也可用于其他.properties文件,只要locations指定即可
總結
以上所述是小編給大家介紹的Spring Boot中配置文件application.properties使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
bug解決Failed_to_execute_goal_org.springframework
這篇文章主要為大家介紹了bug解決Failed_to_execute_goal_org.springframework,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09