前言
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}")
private String name;
@Value("${com.mlin.dream}")
private String dream;
@RequestMapping("/proper")
public String getProper(){
return name+","+dream;
}
}
運行啓動文件,瀏覽器輸入:http://localhost:8080/proper
,看到如下畫面:
這是一種讀取配置文件屬性的方式,可以看出還是比較麻煩的,因爲一旦屬性過多,那一個個的配置真的挺繁瑣。接下來講第二種方式:
新建實體文件:
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]}
原創作者:夢凌小樣
作品鏈接:https://www.jianshu.com/p/70cb387deb05【原創不易,轉載請註明出處,感謝理解】
一位愛生活,愛創作,愛分享,愛自己的90後女程序員一枚,記錄工作中的點點滴滴,一起學習,共同進步,期待能和優秀的您交上朋友