1 自定义属性值,并取出,相当于以前的properties文件,并从里面取出数据
示例:
在application.yml文件里定义,以取size里的数值为例
server:
port: 8089
size: 6666
然后在类中取出size的数值
@RestController
public class hello {
@Value("${size}")
private String size;
@RequestMapping(value="/add")
public String addUser(){
return size;
}
}
2 在配置文件中取配置文件中的数据
application.yml文件
server:
port: 8089
size: 6666
age: 18
content: "size: ${size} ,age: ${age}"
类中
@RestController
public class hello {
@Value("${size}")
private String size;
@Value("${content}")
private String content;
@RequestMapping(value="/add")
public String addUser(){
return content;
}
}
访问路径:http://localhost:8089/add
3 自己如果一个一个的用value取有时候太麻烦,可以把他们的属性值封装到类中
application.yml文件
server:
port: 8089
girl:
size: 678
name: 雪儿
新建的封装类
关键注解:
@ConfigurationProperties(prefix=”girl”)//前缀对应配置类中的前缀,底下是他的属性
package com.example.demo.controller;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="girl")//前缀对应配置类中的前缀,底下是他的属性
public class girlProperties {
Integer size;
String name;
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
控制层的引用
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class hello {
@Autowired
private girlProperties girlproperties ;
@RequestMapping(value="/add")
public String addUser(){
return girlproperties.getName()+girlproperties.getSize();
}
}
访问路径:http://localhost:8089/add
4 写多个配置文件,然后在application.yml文件中引入,在不同的生产环境可能使用的配置不同
在application.yml中引入的配置
spring:
profiles:
active:
- prod