SpringBoot使用yml配置
阿新 • • 發佈:2018-12-20
1.yml的標準結構
version: 2.0
server:
port: 8081
spring:
application:
name: ztest-spb
profiles:
active: dev
2.系統中呼叫格式
env.getProperty("version"),
env.getProperty("spring.application.name"),
env.getProperty("spring.profiles.active"),
env.getProperty("server.port")
3.注意 :
Caused by: org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token found character '\t(TAB)' that cannot start any token. (Do not use \t(TAB) for indentation)
in 'reader', line 3, column 2:
.yml文字中禁止使用tab 做間隔 否則報以上錯誤
4.yml的賦值使用
(1)使用特定的 @value*yml註解 給類中的屬性注入值 (類似從屬性檔案獲取資料然後賦值)
@RestController
public class TestController {
@Value(value="${spring.application.name}")
private String projectname;
@RequestMapping("/hello")
public String hello(){
return "hello "+projectname;
}
}
(2)將屬性檔案中的值 直接賦值給定義的物件
version: 2.0 server: port: 8081 spring: application: name: ztest-spb profiles: active: dev #使用物件獲取值 user: username: 小明
將屬性賦值給物件
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {
private String username;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username= username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
在類中直接自動裝配就可以使用了
@RestController
public class Test2Controller {
@Autowired
UserProperties properties;
@RequestMapping("/hello")
public String hello(){
return "hello "+properties.getUsername();
}
}
OK 完成!