Spring Boot配置--yml
配置文件
- Spring Boot使用一个全局的配置文件,配置文件名称是固定的application.yml
key:空格value
YAML
yaml可以直接给实体类赋值
person类
package org.god.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@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;
private Dog dog;
public Person() {
}
public Person(String name, Dog dog, List<Object> lists, Map<String, Object> maps, Date birth, Boolean happy, Integer age) {
this.name = name;
this.dog = dog;
this.lists = lists;
this.maps = maps;
this.birth = birth;
this.happy = happy;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getHappy() {
return happy;
}
public void setHappy(Boolean happy) {
this.happy = happy;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", happy=" + happy +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
}
application配置文件
person:
name: zlatan${random.uuid}
age: 28
happy: false
birth: 1987/08/25
maps: {k1: v1,k2: v2}
hello: good
lists:
- code
- soccer
dog:
name: ${person.hello:bady}-lulu
age: 18
测试类
@SpringBootTest
class Springboot01HelloworldApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
松散绑定:在YML中写last-name和lastName是一样的,-后边跟着的字母默认是大写。这就是松散绑定
JSR303校验
JSR303规范内置了一系列的约束注解,用于对数据进行校验,例如:
- @NotNull:确保字段不为null
- @Min和@Max:确保数字值在一定的范围内
- @Size:确保字符串的长度在指定的范围内
- @Email:确保字段是一个电子邮件地址
- @Pattern:确保字符串符合正则表达式
浙公网安备 33010602011771号