Day15 SpringBoot 2 配置文件 SPEL表达式 松散绑定 JSR303校验 yaml语法
uwupu 啦啦啦啦啦

SpringBoot如何启动

入口

1
2
3
4
5
6
7
8
//标注这个类是一个SpringBoot应用
@SpringBootApplication
public class SpringBootForthProjectApplication {
public static void main(String[] args) {
//将SpringBoot应用启动
SpringApplication.run(SpringBootForthProjectApplication.class, args);
}
}

SpringApplication.run(SpringBootForthProjectApplication.class, args);

  1. 推断应用的类型是普通的项目还是Web项目;
  2. 查找并加载所有可用初始化器,设置到initializers属性中;
  3. 找出所有的应用程序监听器,设置到listeners属性中;
  4. 推断并设置main方法的定义类,找到运行的主类;

SpringBoot全局配置文件

默认文件名

两种方案:

  • application.properties
    • 语法结构:key=value
  • application.yml
    • 语法结构:key:空格value

作用:修改SpringBoot自动配置的默认值。

文件位置

可以在以下几个位置放置配置文件:

  1. file:./config/ 项目目录下config文件夹中
  2. file:./ 项目根目录下
  3. classpath:/config/ 资源目录的config目录下
  4. classpath:/ 资源目录根目录下

优先级顺序也按照上面的顺序来。

不同环境下的配置文件

有三种环境:默认、dev、test。(默认、开发、测试)

多文件方式

  1. 创建三个文件,其中没有后缀表示默认,dev表示开发,test表示测试;

    image

  2. 在application.yaml添加spring.profiles=指定使用的配置环境,

    1
    2
    3
    spring:
    profiles:
    active: dev

    示例中表示使用dev环境。

  3. 配置的环境名可以自定义

    image

单文件方式

  1. 在application.yaml中添加以下内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    server:
    port: 8081
    spring:
    profiles:
    active: dev


    ---
    server:
    port: 8082
    spring:
    config:
    activate:
    on-profile: dev

    ---
    server:
    port: 8083
    spring:
    config:
    activate:
    on-profile: test

    使用”—“分隔开三种配置。在示例中,第一部分为默认的配置,spring.profiles.active指定现在使用的配置。第二部分为dev配置,第三部分为test配置。

    • 在默认配置中使用spring.profiles.active指定要使用的配置环境
    • spring.config.activate.on-profile声明当前位置的配置名
  2. 使用即可。

yaml语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 普通的key-value
name: 张三

# 对象
student:
name: zhangsan
age: 3

# 行内对象
student2: {name: zhangsan ,age: 3}

#数组
pets:
- cat
- dog


# 行内数组
pets2: [cat,dog,pig]

Spring的@Autowired和@Value实现对象自动初始化

  1. 创建一个Dog类,放入无参构造方法、getter和setter,对类使用@Component注解。对需要赋值的变量使用@Value注解,值为要赋的值。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //将类加入Spring底层
    @Component
    public class Dog {
    @Value("张三") //自动装载的默认值
    private String name;
    @Value("12") //这里只能写字符串,整数也要用引号括住
    private Integer age;

    //toString方法、getter方法、setter方法、无参构造方法、有参构造方法这里省略
    }
  2. 在要使用的类中,创建一个引用,使用@Autowired注解,即可实现自动初始化;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @SpringBootTest
    class SpringBootForthProjectApplicationTests {

    @Autowired
    private Dog dog;
    @Test
    void contextLoads() {
    System.out.println(dog);
    }

    }
  3. 写一个测试类,测试结果。

    1
    Dog{name='张三', age=12}

通过yaml实现对象自动初始化

  1. 在application.yaml中添加以下内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
person:
name: zhangsan
age: 3
happy: false
birth: 2022/9/9
maps: {k1: v1,k2: v2}
lists:
- code
- girl
- zhangsan
dog:
name: lisi
age: 3
  1. 创建一个Person类,添加注解@ConfigurationProperties(prefix = "person"),其中prefix前缀的值为application.yaml配置的对应的对象的名,也就是person。
1
2
3
4
5
6
7
8
9
10
11
12
@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;
//构造方法、setter、getter、toString方法
}
  1. 运行测试
1
2
3
4
5
6
7
8
9
@SpringBootTest
class SpringBootForthProjectApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
1
Person{name='zhangsan', age=3, happy=false, birth=Fri Sep 09 00:00:00 CST 2022, maps={k1=v1, k2=v2}, lists=[code, girl, zhangsan], dog=Dog{name='lisi', age=3}}

注意:

image

@configurationProperties使用后会标红,解决办法:

  1. 在pom.xml中添加:

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
    </dependency>
  2. 重启idea。

这个依赖的作用是:添加依赖后,可以用@ConfigurationProperties注释的项轻松生成自己的配置元数据文件,在编写application.yml文件可以有相关提示。

部分SPEL表达式

${random.uuid}

随机

random.uuid:获得一个随机的UUID

random.int:获得一个整数

示例1:${person.hello:Lisi}张三

在对象person中寻找hello,若有hello则用hello的值,没有则用“Lisi”代替,然后拼接“张三”。

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
person:
name: zhangsan${random.uuid}
age: ${random.int}
happy: false
birth: 2022/9/9
maps: {k1: v1,k2: v2}
lists:
- code
- girl
- zhangsan
dog:
name: ${person.hello:张三}_LiSi
age: 3

运行结果:

1
2
Person{name='zhangsand4c877dd-b714-468f-b6f9-c4a4b899a8d0', age=-161320060, happy=false, birth=Fri Sep 09 00:00:00 CST 2022, maps={k1=v1, k2=v2}, lists=[code, girl, zhangsan], dog=Dog{name='张三_LiSi', age=3}}

松散绑定

在使用yaml实现对象自动赋值过程中,yaml中对象名和实际对象名中,驼峰命名和带“-”的命名可以对应起来。如:firstName和first-name。(properties不支持)

示例

dog类:

1
2
3
4
5
6
7
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
private String firstName;
private Integer age;
// Constructor,getter,setter,toString
}

yaml中的dog:

1
2
3
dog:
first-name: Qwert
age: 6

运行结果:

1
Dog{firstName='Qwert', age=6}

JSR303校验

@Validated

JSR303校验指,Spring提供注解可以直接校验变量的值。

在变量前添加指定注解,可以实现注解对应的功能。

依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

使用

  1. 在类前添加@Validated注解;
  2. 在需要检查的对象前添加相应的校验注解。

位于jakarta.validation下的javax.validation.constraint里。

image

代码示例

在yml文件中

1
2
3
4
student:
id: 3
name: Obsidian
email: [email protected]

一个student类

1
2
3
4
5
6
7
8
9
10
@Component
@ConfigurationProperties(prefix = "student")
@Validated
public class Student {
private int id;
private String name;
@Email(message="邮件格式错误")
private String email;
//Constructor、getter、setter、toString
}

运行测试

1
2
3
4
5
6
7
8
9
@SpringBootTest
class SpringBootForthProjectApplicationTests {
@Autowired
private Student student;
@Test
void contextLoads() {
System.out.println(student);
}
}
1
Student{id=3, name='Obsidian', email='[email protected]'}

可以使用的注解

空检查

注解名 介绍
@Null 验证对象是否为空。
@NotNull 验证对象不为空。不检查长度为0的字符串。
@NotBlank 验证约束字符串不是null,且字符串trim后长度大于0。(trim:去掉字符串前后空格)
@NotEmpty 验证约束元素是否为空或null。

Boolean检查

注解名 介绍
@AssertTrue 验证Boolean对象是否为true
@AssertFalse 验证Boolean对象是否为false

长度检查

注解名 介绍
@Size(min=,max=) 验证对象(Array、Collection、Map、String)长度是否在给定范围内
@Length(min=,max=) 验证被注解的字符串的长度是否在给定范围内

日期检查

注解名 介绍
@Past 验证Date和Calendar对象是否在当前时间之前
@Future 验证Date和Calendar对象是否在当前时间之后

字符串检查

注解名 介绍
@Pattern 验证String对象是否符合正则表达式的规则

其他

使用properties配置文件

  1. 类前用@PropertySource注解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Component
    @PropertySource("classpath:application.properties")
    public class Person_properties {
    @Value("${person2.name}")
    private String name;
    @Value("${person2.age}")
    private Integer age;
    @Value("${person2.happy}")
    private Boolean happy;
    @Value("${person2.birth}")
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
    //Contsructor、getter、setter、toString
    }
  2. 在application.yaml文件中

    1
    2
    3
    4
    person2.name=zhangsan
    person2.birth=2020/2/2
    person2.age=123
    person2.happy=false
  3. 运行测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @SpringBootTest
    class SpringBootForthProjectApplicationTests {

    @Autowired
    private Person_properties person;
    @Test
    void contextLoads() {
    System.out.println(person);
    }

    }
    1
    Person2{name='zhangsan', age=123, happy=false, birth=Sun Feb 02 00:00:00 CST 2020, maps=null, lists=null, dog=null}

修改的内容

单文件方式配置SpringBoot多环境

旧版本中

使用spring.profiles声明当前使用的配置名。

新版本中

使用spring.config.activate.on-profile声明当前使用的配置名。

 评论