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.注意 :号后边和值要有空格 如 version: 2.0 禁止 version:2.0
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)将属性文件中的值 直接赋值给定义的对象
user
username: 111
age: king //将属性赋值给对象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();
}
}