运行原理
给属性赋值的几种方式
1. 通过yml 给对象赋值(推荐)
@ConfigurationProperties(prefix = “xxx”),可以给类直接赋值。
@Data
@Component
@ConfigurationProperties(prefix = "person") //给这个类加一个前缀,在yaml中才能识别
public class Person {
private String name;
private Integer age;
private Date birthday;
private List<Object> lists;
private Dog dog;
private Map<String,Object> maps;
}
@Component
@Data
public class Dog {
@Value("14")
private int age;
private String name;
}
person:
age: 18
name: 夏木
birthday: 2020/05/22
lists:
- one
- two
- three
maps: {hubei: 武汉,zheJiang: 杭州}
dog:
age: 5
name: 大黄
2. 指定properties配置文件
@PropertySource(value = “classpath:person.properties”)
jsr303验证
验证数据的合法性,使用验证的时候需要在类上加上 @Validated注解
多环境配置及配置文件位置
配置文件位置
springboot中配置文件可以存放在四个地方,按优先级排序分别为:
- 根目录/config
- 根目录/
- resources/config
- resources/
其中第4个优先级最低,也是系统默认的位置。
多环境配置
方式一:使用properties配置文件
创建三个配置文件,对应不同的环境:
- application.properties
- application-test.properties
- application-dev.properties
application.properties中指定要使用的环境配置文件:spring.profiles.active=dev
方式二:使用yaml配置文件
创建application.yaml,通过三条横杆区分不同的环境
server:
port: 8080
spring:
profiles:
active: dev
---
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: dev
静态资源
处理静态资源的方式
- 使用webjars,需要导入依赖,localhost:8080/webjars/
- 使用静态资源下的目录,localhost:8080/
resources/public
resources/static
resources/resources
resources/**
优先级:resources>static>public