Springboot (二) 配置文件

一、配置文件

配置文件:修改SpringBoot自动配置的默认值。
全局的配置文件:

application.properties
语法结构 :key=value

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

二、YAML语法

(一)基本写法

k:(空格)v:表示一对键值对

server:
  port: 8888

注意:
①空格不能省略
②以空格的缩进来控制层级关系,只要是左对齐的一列数据,都是同一个层级的。
③属性和值大小写敏感

(二)值的写法:

1、字面量:普通的值

k: v

字面直接来写,字符串默认不用加上双引号或者单引号。
" ":双引号,不会转义字符串里面的特殊字符,特殊字符会作为本身想表示的意思

name: “张三 \n 李四”

输出:

张三
李四

’ ':单引号,会转义特殊字符,特殊字符最终只是一个普通的字符串数据

name: ‘张三 \n 李四’

输出:

张三 \n 李四

2、对象、Map(键值对)
k: v:在下一行来写对象的属性和值的关系

person:
  name: 张三
  age: 20

行内写法:

person: {name: 张三,age: 20}

3、数组
用 - 值表示数组中的一个元素

pets:
 - cat
 - dog
 - pig

行内写法:

pets: [cat,dog,pig]

三、配置文件注入

(一)用@Value方法注入

1、编写实体类

package com.qzy.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component  //注册bean到容器中
public class Dog {
    @Value("阿黄")
    private String name;
    @Value("2")
    private Integer 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 Dog(){

    }
    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

}

2、测试类

@SpringBootTest
class Springboot01HelloworldApplicationTests {

    @Autowired //将狗自动注入进来
    Dog dog;

    @Test
    public void contextLoads() {
        System.out.println(dog); 
    }
}

@Autowired:可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。如果方法有参数,会在IOC容器中自动寻找同类型参数为其传值。

3、运行测试类
在这里插入图片描述

(二)yml配置的方式

1、编写实体类

package com.qzy.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 //注册bean到容器中
@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, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.name = name;
        this.age = age;
        this.happy = happy;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }

    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 +
                '}';
    }
}

其中,@ConfigurationProperties作用:将配置文件中配置的每一个属性的值,映射到这个组件中。
参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应

2、yml

person:
  name: 张三
  age: 20
  happy: true
  birth: 2021/07/01
  maps: {k1: v1,k2: v2}
  lists:
    - code
    - music
    - play
  dog:
    name: 旺财
    age: 1

3、测试类

package com.qzy;

import com.qzy.pojo.Dog;
import com.qzy.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot01HelloworldApplicationTests {

    @Autowired //将person自动注入进来
    Person person;

    @Test
    public void contextLoads() {
        System.out.println(person);
    }
}

4、运行测试类
在这里插入图片描述

四、配置文件占位符

配置文件还可以编写占位符生成随机数

person:
    name: 张三${random.uuid}
    age: ${random.int}
    happy: true
    birth: 2021/07/01
    maps: {k1: v1,k2: v2}
    lists:
      - code
      - music
      - book
    dog:
      name: ${person.hello:other}_狗蛋
      age: 3

五、配置文件加载位置

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件

–file:./config/
–file:./
–classpath:/config/
–classpath:/

优先级由高到底,高优先级的配置会覆盖低优先级的配置

SpringBoot会从这四个位置全部加载主配置文件,互补配置

六、JSR303数据校验

Springboot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。
常见参数


@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       验证 DateCalendar 对象是否在当前时间之前  
@Future     验证 DateCalendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

.......等等
除此以外,我们还可以自定义一些数据校验规则

七、自动配置原理

HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理

@Configuration 
//表示这是一个配置类,和以前编写的配置文件一样,也可以给容器中添加组件;
@EnableConfigurationProperties({HttpProperties.class}) 
//启动指定类的ConfigurationProperties功能
//进入这个HttpProperties查看,将配置文件中对应的值和HttpProperties绑定起来;
//并把HttpProperties加入到ioc容器中
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
//Spring底层@Conditional注解
//根据不同的条件判断,如果满足指定的条件,整个配置类里面的配置就会生效
//这里的意思就是判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnClass({CharacterEncodingFilter.class})
//判断当前项目有没有这个类CharacterEncodingFilter,SpringMVC中进行乱码解决的过滤器;
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
//判断配置文件中是否存在某个配置:spring.http.encoding.enabled;
//如果不存在,判断也是成立的
//即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的

public class HttpEncodingAutoConfiguration {
    //他已经和SpringBoot的配置文件映射了
    private final Encoding properties;
    //只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
    }
    
    //给容器中添加一个组件,这个组件的某些值需要从properties中获取
    @Bean
    @ConditionalOnMissingBean //判断容器没有这个组件
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
    }
    //。。。。。。。
}

根据当前不同的条件判断,决定这个配置类是否生效。

(1)一但这个配置类生效,这个配置类就会给容器中添加各种组件。
(2)这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的。
(3)所有在配置文件中能配置的属性都是在xxxxProperties类中封装着。
(4)配置文件能配置什么就可以参照某个功能对应的这个属性类。

总结:
1、SpringBoot启动会加载大量的自动配置类。

2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中。

3、我们再来看这个自动配置类中到底配置了哪些组件(只要我们要用的组件存在在其中,我们就不需要再手动配置了)。

4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可。

xxxxAutoConfigurartion:自动配置类,给容器中添加组件。

xxxxProperties:封装配置文件中相关属性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值