1,由於項目需要,學習了新的框架--springboot,順便練習一下在.yml中配置自定義屬性並在controller里面獲取。(以下的Springboot框架我已經搭建好,就不在陳述)
2,springboot支持很多外部配置,這里就不多介紹了。說說.properties和.yml文件在springboot中的區別:
優先級:如果在項目中同時配置了.yml和.properties文件,那么會優先加載.properties文件。
作用:在properties中以.進行分割,.yml中以“:”進行分割:,並且它以key-value和“:”進行賦值。
注意的地方:
縮進只能用空格鍵!!!!只能!!!
每個key的冒號后面一定要加空格!!!
3,以下是.yml文件中的代碼:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
server:
port: 8080
servlet:
context-path: /testspringboot
#訪問地址:http://localhost:8081/testspringboot/
yybx: #自定義的屬性和值
name: yuxi
age : 26
yybx是我簡單自定義的兩個屬性,接下來建立一個bean類:
@Component
public class Testbean
{
@Value("${yybx.name}")
private String name;
@Value("${yybx.age}")
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
@Component:將實體類注入到spring中方便以后取出
@Value("${yybx.name}")
private String name;
@Value("${yybx.age}")
private Integer age;
上面四行是將yybx中的屬性取出來對應的賦值給bean中的屬性
編寫測試類:

控制台:
取值成功!
還有一種使用@ConfigurationProperties
方式取值,感覺沒有這種方式簡單,這里先不陳述,以后會繼續添加!