springboot的配置文件必须命名为application
端口
- 多环境配置
server:
port: 8080
spring:
profiles: DEV
---
server:
port: 8081
spring:
profiles: TEST
---
server:
port: 8082
spring:
profiles: PROD
---
server:
port: 8083
spring:
profiles: SIT
---
spring:
profiles:
active: PROD
- 多个application.yaml的执行顺序:
1.项目路径下的config包下的application.yaml文件
2.项目根路径下的application.yaml文件
3.src/resources路径下的config文件内的application.yaml文件
4.src/resources路径下的application.yaml文件
属性值的注入
- 推荐使用yaml文件
spring:
application:
name: yaml-demo01
server:
port: 8081
studnet:
id: ${
random.uuid}
age: ${
random.int}
hobby:
- code
- music
- eat
phone: [p,as,s]
parent: [mother: t,father: g]
dog:
name: 旺财
age: 1
package cn.itcast.yamldemo01.pojo;
import lombok.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component//spring添加组件注解,其他的有@Component、@Repository @Service、@Controller
@Data//get和set方法
@NoArgsConstructor//无参构造
@AllArgsConstructor//有参构造
@ToString//打印对象
@ConfigurationProperties(prefix = "studnet")//yaml文件配置属性
@PropertySource(value = "classpath:student.properties")//加载属性配置文件
public class Studnet {
private String id;
@Value("${name}")//student.properties文件中设置了name的值
private String name;
private String age;
private List<String> hobby;
private List<String> phone;
private Map<String, Object> parent;
private Dog dog;//dog类中必须添加@Component注解
}
数据校验
@Component //注册bean
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
public class Person {
@Email(message="邮箱格式错误") //name必须是邮箱格式
private String name;
}
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
.......等等
除此以外,我们还可以自定义一些数据校验规则