springboot 项目创建完成后,在 resources目录下会生成一个 application.properties 文件,用于编写springboot 项目的配置。
但官方不推荐使用.properties 的配置文件,所以我们这里把原来的 application.properties 修改为yaml 配置文件,即重命名为 application.yaml
注意:yaml对空格的要求十分严格
对象形式
student:
name: b5ck
age: 18
# 行内写法
student2: {name: b5ck,age: 3}数组形式
pets:
- cat
- dog
- pig
# 行内写法
pets2: [cat,dog,pig]修改 springboot 默认的监听端口
application.yaml
server:
port: 8888重启 springboot 项目,监听端口修改为 8888
先在pom.xml中导入spring的配置处理器
<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>创建两个实体类 Person 和 Dog
Dog实体类
@Component // 将实体类添加到spring组件内
public class Dog {
private String name;
private Integer age;
// 使用Alt+ Inster快速构建有参、无参构造函数以及setter和getter、toString方法
}Person 实体类
@Component
@ConfigurationProperties(prefix = "person") //与配置文件中的对象所关联
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
// 创建Dog类对象
private Dog dog;
// 使用Alt+ Inster快速构建有参、无参构造函数以及setter和getter、toString方法
}从以上两个实体类中我们用到了两个注解:
@Component 注解表示将这个实体类添加到spring组件中@ConfigurationProperties(prefix = "person") 注解用于与配置文件的对象进行绑定,perfix对应的值为绑定的对象名称,目前该注解使实体类绑定配置文件中的person对象。接下来我们在配置文件 application.yaml中设置我们实体类的属性值
person:
name: b5ck
age: 18
happy: false
birth: 2020/01/17
maps: {k1: v1,k2: v2}
lists:
- code
- music
- girl
dog:
name: 123
age: 3基本配置已完成,接下来我们在 srpingboot 单元测试中输出我们的实体类,看下属性的值是否设置成功
单元测试类
@SpringBootTest
class ApplicationTests {
@Autowired //自动装配实体类
private Person person;
@Test
void contextLoads() {
System.out.println(person); //输出对象信息
}
}构建并运行单元测试, 得到输出的实体类信息
person:
name: b5ck.${random.uuid} # 随机uuid
age: ${random.int} # 随机数
happy: false
birth: 2020/01/17
maps: {k1: v1,k2: v2}
lists:
- code
- music
- girl
dog:
name: 旺财
age: 3spring-boot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。我们这里来写个注解让我们的name只能支持Email格式
@Component //注册bean
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
public class Person {
//@Value("${person.name}")
@Email //name必须是邮箱格式
private String name;
}还有很多内置校验规则,也可以自定义正则表达式进行校验,这里我们不进行详细的举例
更多校验案例参考: (https://blog.csdn.net/qq_28867949/article/details/78922520)