1、讀取默認(rèn)配置文件
默認(rèn)配置文件是指在resources目錄下的application.properties或application.yml配置文件霍衫,讀取這兩個(gè)配置文件的方法有三種绞蹦。
application.properties內(nèi)容如下:
#log
logging.level.root=INFO
logging.path=logs
#custom properties
a.age=29
a.msg=hello
b.age=92
b.msg=hi
方法一:
@Value("${a.age}")
private String age;
//其他類似瞭稼,代碼省略
方法二:
@Autowired
private Environment env;
String msg = env.getProperty("a.age");
//其他類似盛垦,代碼省略
方法三:
適合于配置比較多,希望更好的組織蹭秋,定義一個(gè)CustomASettings類:
@ConfigurationProperties(prefix = "a")
public class CustomASettings {
private String age;
private String msg;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
必須添加@EnableConfigurationProperties注解
@SpringBootApplication
@EnableConfigurationProperties({CustomASettings.class})
public class App{
public static void main(String args[]){
SpringApplication.run(App.class);
}
}
2、嵌套屬性
假設(shè)application.properties內(nèi)容如下:
#嵌套屬性
name=test
jdbc.username=root
jdbc.password=root
定義一個(gè)NestedSettings類:
@ConfigurationProperties
public class NestedSettings {
private String name;
@NestedConfigurationProperty
private Jdbc jdbc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Jdbc getJdbc() {
return jdbc;
}
public void setJdbc(Jdbc jdbc) {
this.jdbc = jdbc;
}
public static class Jdbc {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
}
@EnableConfigurationProperties注解添加NestedSettings.class:
@SpringBootApplication
@EnableConfigurationProperties({NestedSettings.class})
public class App{
public static void main(String args[]){
SpringApplication.run(App.class);
}
}
3堤撵、讀取自定義配置文件
假設(shè)有一個(gè)custom.properties文件:
c.age=29
c.msg=hello
SpringBoot 1.5版本之前的做法:
@ConfigurationProperties(locations = "classpath:custom.properties", prefix = "c")
public class CustomCSettings{
private String age;
private String msg;
public String getAge() {
return age;
}
public String getMsg() {
return msg;
}
public void setAge(String age) {
this.age= age;
}
public void setMsg(String msg) {
this.msg= msg;
}
}
但是現(xiàn)在@ConfigurationProperties已經(jīng)沒有l(wèi)ocations這個(gè)屬性仁讨。
SpringBoot 1.5版本之后可以這樣做:
@Configuration
@PropertySource("classpath:custom.properties")
public class CustomCSettings {
@Autowired
Environment environment;
public String getAge() {
return environment.getProperty("c.age");
}
public String getMsg() {
return environment.getProperty("c.msg");
}
}