SpringBoot配置
yaml语法
Yet Another Markup Language以key-value形式存储,类似于 python对空格的要求尤为严格。强调以数据为中心,而不是以标记语言 为中心。
student:
name: cyl
age: 22
student: {name: cyl,age: 22}
books:
- A
- B
- C
books: [A,B,C]
给属性赋值
yaml可以直接给实体类赋值
package com.cyl.back.Pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
@Value("17391041378")
private String id;
@Value("cyl")
private String username;
@Value("123456")
private String password;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean money;
private Date birth;
private Map<String, Object> map;
private List<Object> list;
private User user;
}
person:
name: cyl
age: 22
money: false
birth: 2020/07/21
map: {k1: v1,k2: v2}
list:
- code
- music
- girl
user:
id: 17391041378
username: cyl
password: 123456
@SpringBootTest
class BackApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
@ConfigurationProperties
- 将配置文件中每一个属性的值,映射到这个组件中,即进行参数绑定。
JSR303校验
我们给实体类使用此注解,类似于前端
这儿的前端传入值必须为邮箱格式,不然就会报错
<input type="email">
我们给实体类中的属性名使用注解即可实现数据校验
@Validated
public class Person {
@Email()
private String email;
@NotNull()
private Integer age;
@AssertFalse
private Boolean money;
}
|