前言:在springboot中.properties與.yml是兩種不同格式的配置文件,
.properties是xxx.xxx.xxx=xxx的格式,
.yml則展示出了層次感。
一:application.properties
1.自定義配置
在application.properties中自定義參數和值並獲取:
a.自定義參數:
#用戶名
account=robert
#密碼
password=123456
b.寫個配置類
package com.robert.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 配置類
* @author L
*/
@Component
public class Properties {
/**
* 用戶名
*/
@Value("${account}")
private String account;
/**
* 密碼
*/
@Value("${password}")
private String password;
//get、set省略
}
c.寫個controller用來測試獲取到的配置:
@Controller
public class testController {
@Autowired
Properties properties;
@RequestMapping("/getUser")
public String test(ModelMap model) {
String name = properties.getAccount();
String password = properties.getPassword();
return name+","+password;
}
}
d.在瀏覽器地址欄輸入:localhost:8080/getUser
結果是:用戶名:robert 密碼:123456
注意:配置文件中還有很多默認的參數,比如說這裏的用戶名,如果你用username,出來的是你電腦用戶賬號,所以在選擇自定義名稱時需要注意。
2.在正式的項目中,我們可能會有測試環境、生產環境,這時候我們需要把這些環境的配置分開。這時候,只需要配置多個配置文件即可。格式:application-{profile}.properties
例如:application-dev.properties、application-produce.properties
激活哪個配置文件:
spring.profiles.active=dev(或者produce)
二、application.yml
.yml格式如下,.properties中server.port=xxxx,到了.yml中就變成了
server:
port:(空格)9090
注意空格,這是.yml的格式,不可缺少。