Springboot2(2)屬性配置講解和自定義屬性配置
[原始碼地址](https://gitee.com/cowboy2016/springboot2-open)
在使用spring boot過程中,可以發現專案中只需要極少的配置就能完成相應的功能,這歸功於spring boot中的模組化配置,在pom.xml中依賴的每個Starter都有預設配置,而這些預設配置足以滿足正常的功能開發。
重點
多環境的配置方法
@value支援的7種內容注入,還List,Map型別的注入,設定預設值的方法
@ConfigurationProperties,@Profile的使用
屬性配置詳解
引數引用與random隨機數方法的使用
在application.yml內可以直接通過${}引用其他屬性的值,如下:
myframe:
name: tom
desc: ${myframe.name} is boy
獲取隨機數,可以通過${random}
#獲取隨機字串 myframe.randomValue: ${random.value} #獲取隨機字串:${random.value} #獲取隨機int:${random.int} #獲取10以內的隨機數:${random.int(10)} #獲取10-20的隨機數:${random.int[10,20]} #獲取隨機long:${random.long} #獲取隨機uuid:${random.uuid}
多環境配置
實際開發中可能會有不同的環境,有開發環境、測試環境、生成環境。對於每個環境相關配置都可能有所不同,如:資料庫資訊、埠配置、本地路徑配置等。
方法一
在application.yml同目錄下新建一下三個檔案:
application-dev.yml //開發環境的配置檔案
在application.yml新增:
spring.profiles.active: dev
用命令執行jar包啟動應用的時候,也可以指定相應的配置
java -jar myframe-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
方法二
在application.yml通過---
server.port: 8001
spring.profiles: node1
---
spring.profiles: node2
server.port: 8002
激動環境
用命令執行jar包啟動應用的時候,可以指定相應的配置
java -jar myframe-0.0.1-SNAPSHOT.jar --spring.profiles.active=node1
或者在application.yml
中
spring.profiles.active: test
配置方式和優先順序
這些方式優先順序如下:
a. 命令列引數
b. 來自java:comp/env的JNDI屬性
c. Java系統屬性(System.getProperties())
d. 作業系統環境變數
e. RandomValuePropertySource配置的random.*屬性值
f. jar外部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
g. jar內部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
h. jar外部的application.properties或application.yml(不帶spring.profile)配置檔案
i. jar內部的application.properties或application.yml(不帶spring.profile)配置檔案
j. @Configuration註解類上的@PropertySource
k. 通過SpringApplication.setDefaultProperties指定的預設屬性
注:命令列引數這種jar包指定引數啟動應用的方式,可能是不安全的,我們可以設定禁止這種方式啟動應用,如下:
springApplication.setAddCommandLineProperties(false);
自定義屬性配置
在application.yml中新增自定義屬性配置
myframe:
user:
name: tom
age: 29
address: 廣東廣州天河
uuid: ${random.uuid}
desc: ${myframe.user.name} is ${myframe.user.age} years old
date: 2018/09/20
hobby[0]: 打球
hobby[1]: 寫程式碼
@Value()載入
@Component
@Data
class User{
@Value("${myframe.user.name}")
private String name;
@Value("${myframe.user.age}")
private int age;
@Value("${myframe.user.address}")
private String address;
@Value("${myframe.user.phone:13422337766}")
private String phone;
@Value("${myframe.user.desc}")
private String desc;
}
SpringBoot如果我們使用了@Value來從配置檔案讀取值的話 ,就會報錯
@Value(${myframe.user.phone:13422337766}) 配置項指定了13422337766預設值
@value支援注入內容
-
(1)注入普通字元;
-
(2)注入作業系統屬性;
-
(3)注入表示式運算結果;
-
(4)注入其他Bean的屬性;
-
(5)注入檔案內容;
-
(6)注入網址內容;
-
(7)注入屬性檔案;
import org.springframework.core.io.Resource;
@Data
@Component
@PropertySource("classpath:application.yml")
public class ValueModel {
@Value("I LOVE YOU!") //注入普通字串
private String normal;
@Value("#{systemProperties['os.name']}") //注入作業系統屬性
private String osName;
@Value("#{T(java.lang.Math).random() * 100.0}") //注入表示式結果
private String randomNumber;
@Value("#{user.address}") //注入其他Bean屬性
private String address;
@Value("classpath:/test.txt") //注入檔案資源
private Resource testFile;
@Value("http://www.baidu.com") //注入網址資源
private Resource testUrl;
@Value("${myframe.user.name}") // 注入配置檔案
private String userName;
@Autowired // 注入配置檔案
private Environment environment;
@Bean // 注入配置檔案
public static PropertySourcesPlaceholderConfigurer propertyConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
public void outputResource(){
try {
System.out.println(normal);
System.out.println(osName);
System.out.println(randomNumber);
System.out.println(address);
System.out.println(IOUtils.toString(testFile.getInputStream()));
System.out.println(IOUtils.toString(testUrl.getInputStream()));
System.out.println(userName);
System.out.println(environment.getProperty("myframe.user.name"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@ConfigurationProperties(prefix="")
@Component
@ConfigurationProperties(prefix = "myframe.user")
@Data
class PreUser{
private String name;
private int age;
private String address;
private String phone;
private String desc;
private Date date;
private List<String> hobby;
}
@ConfigurationProperties可以對基本資料型別實現自動封裝,可以封裝格式為yyyy/MM/dd的日期
@Profile("")
public interface Person {
void say();
}
@Component
@Profile("test")
@Slf4j
public class Student implements Person{
@Override
public void say() {
log.info("我是學生");
}
}
@Component
@Slf4j
@Profile("dev")
public class Teacher implements Person {
@Override
public void say() {
log.info("我是老師");
}
}
使用方法
@Autowired
private Person person;
@RequestMapping("/user")
public String user(){
person.say();
return "";
}
當spring.profiles.active: test
時,列印"我是學生"
當spring.profiles.active: dev
時,列印"我是老師"