spring boot學習(三)之配置檔案的學習
前言
spring-boot有一個優點是:習慣優於配置。說明spring boot有很多的配置,所以今天我們學習它的配置檔案: application.properties
。
正文
Spring Boot有一個全域性的配置檔案: application.properties
,放在 src/main/resources
目錄下,我們一起來學習一下它吧。
一,自定義屬性
在 application.properties
檔案中我們可以自定義屬性:
com.mlin.name="mlin" com.mlin.dream="想吃美食"
在需要讀取的地方通過 @Value(value="${config.name}")
的方式讀取:
@RestController public class UserController { @Value("${com.mlin.name}") privateString name; @Value("${com.mlin.dream}") privateString dream; @RequestMapping("/proper") public String getProper(){ return name+","+dream; } }
執行啟動檔案,瀏覽器輸入: http://localhost:8080/proper
,看到如下畫面:

1.png
這是一種讀取配置檔案屬性的方式,可以看出還是比較麻煩的,因為一旦屬性過多,那一個個的配置真的挺繁瑣。接下來講第二種方式:
Config.java
,添加註解:
@ConfigurationProperties(prefix = "com.dudu")
,指明要引用的屬性
@ConfigurationProperties(prefix = "com.mlin") public class Config { private String name; private String dream; //get and set }
spring Boot入口類: Chapter1Application
加上 @EnableConfigurationProperties({Config.class})
註解,指明要載入的bean檔案:
@SpringBootApplication @EnableConfigurationProperties({Config.class}) public class Chapter1Application { public static void main(String[] args) { SpringApplication.run(Chapter1Application.class, args); } }
最後在要讀取屬性的地方引用bean檔案即可:
@RestController public class UserController { @Autowired Config config; @RequestMapping("/proper1") public String getProper1(){ return config.getName()+config.getDream(); } }
在 application.properties
中的各個引數之間還可以組合,成為新的屬性,如:
com.mlin.name="mlin" com.mlin.dream="想吃美食" com.mlin.mydream=${com.mlin.name}的願望是${com.mlin.dream}
二,自定義配置檔案
有時候我們不想把所有的配置檔案都放在 application.properties
,因此我們可以自己建立配置檔案,這裡建立了 mlin.properties
,同樣放在 src/main/resourses
下面:
com.mlin.name="mlin" com.mlin.dream="想吃美食aaa" com.mlin.mydream=${com.mlin.name}的願望是${com.mlin.dream}
建立bean檔案 ConfigTest.java
,添加註解如下所示:
@Configuration @ConfigurationProperties(prefix = "com.mlin") @PropertySource("classpath:mlin.properties") public class ConfigTest { private String name; private String dream; //set and get }
和讀取 application.properties
配置檔案最大的區別就在於讀取自定義的配置檔案需要 @Configuration
和 @PropertySource("classpath:mlin.properties")
兩個註解指定要讀取的配置檔案,其他的方法一樣。
三,隨機配置
還可以在配置檔案中使用${random} 來生成各種不同型別的隨機值,如:
com.mlin.number=${random.int} com.mlin.secret=${random.value} com.mlin.bignumber=${random.long} com.mlin.uuid=${random.uuid} com.mlin.number.less.than.ten=${random.int(10)} com.mlin.number.in.range=${random.int[1024,65536]}
原創作者:夢凌小樣
作品連結: ofollow,noindex">https://www.jianshu.com/p/70cb387deb05 【原創不易,轉載請註明出處,感謝理解】
一位愛生活,愛創作,愛分享,愛自己的90後女程式員一枚,記錄工作中的點點滴滴,一起學習,共同進步,期待能和優秀的您交上朋友