Spring Boot 框架学习笔记(二)
六、appliaction.properties配置与数据注入6.1 `@Value`注解测试注入数据读取输入流6.2 读取配置文件数据注入单文件`@ConfigurationProperties`批量注入七. yaml配置注入yaml基础语法yaml语法特点:松散绑定八. JSR303数据校验及多环境切换数据验证其它注解多环境切换配置文件的多个位置优先级:1>2>3>4(我们默认配置等级为4)多环境切换properties 版本yaml版本(优势:支持多文档块)六、appliaction.properties配置与数据注入
关于数据的注入,Spring框架提供了两种方式
构造方法注入Setter方法注入
我们可以使用XML配置文件数据注入,但是我们要学习的是注解方式注入
@Value
或者@Autowried
6.1@Value
注解
新建项目,引入Lomnok和Spring Web
注入普通简单的数据(字符串、基本数据类型)(常用)注入操作系统属性(标出来的默认建立的这五项暂时没啥用 可以直接删除
Syswdem类
)注入表达式运行结果(#{}
)注入其他Bean的属性,关联对象注入文件资源注入URL资源测试注入数据
DataValue类:
package com.yue.bean;import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.springframework.core.io.Resource;import org.ponent;@Data/*引用lombok 省略get set方法*/@Componentpublic class DataValue {/*基本数据类型*/@Value("诛仙")private String bookName;@Value("66.6")private Double bookSprice;/*对系统属性进行操作*/@Value("#{systemProperties['os.name']}")private String osName;//操作系统的名字@Value("#{systemProperties['java.version]']}")private String javaVersion;//jdk版本/*支持表达式和类型*/@Value("#{666.6*999.9}")private Double result;@Value("#{T(Math).random()}")private Double random;/*引入外部属性文件路径和网址*/@Value("classpath:jdbc.properties")private Resource resourceFile;@Value("")private Resource resourceUrl;/*引入其他类的属性*/@Value("#{student.studentName}")private String userName;}
外部Student类:
package com.yue.bean;import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.ponent;@Data@Componentpublic class Student {@Value("夜雨")private String studentName;}
测试类:
package com.yue;import com.yue.bean.DataValue;import lombok.Data;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestclass Boot02ApplicationTests {@Autowiredprivate DataValue dataValue;@Testpublic void test01() {System.out.println(dataValue);}}
结果:
读取输入流
package com.yue;import com.yue.bean.DataValue;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.core.io.Resource;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;@SpringBootTestclass Boot02ApplicationTests {@Autowiredprivate DataValue dataValue;@Testpublic void test01() throws IOException {System.out.println(dataValue);Resource r1 = dataValue.getResourceUrl();InputStream in;BufferedReader reader = new BufferedReader(new InputStreamReader(r1.getInputStream()));String str = null;while ((reader.readLine())!=null){System.out.println(reader.readLine());}}}
读取网址的时候,可以将整个网页读取出来
6.2 读取配置文件数据注入
单文件
通过@Value
注解将外部配置文件中的值注入到Bean中,配置文件分为两类:
核心配置文件application.properties
,在Spring Boot启动时就进行加载自定义配置文件(*.properties
或者*.yaml
):需要通过@PropertySource
加载文件,@PropertySource
可以同时加载多个文件,如果多个文件中存在相同KEY值,只会使用最后加载文件中的KEY对应的值。 加载文件的路径可以是可以配置成变量
@Component@Datapublic class DataBean {@Value("${app.name}")private String appName;@Value("${jdbc.driverName}")private String driverName;@Value("${jdbc.url}")private String url;}
@SpringBootApplication@PropertySource(value = {"classpath:jdbc.properties", "classpath:yeyu.properties"})public class Demo02Application {public static void main(String[] args) {SpringApplication.run(Demo02Application.class, args);}}
@SpringBootApplication
可以注入外部配置文件,重要属性value(支持数组)注意上面的代码
@PropertySource
中有两个配置路径,按先后顺序加载。若key值相同,后者覆盖前者。不同则不影响,一起输出
@ConfigurationProperties
批量注入
配置文件:
person.name=wukongperson.age=10person.sex=man
类:
@Component@Data@ConfigurationProperties(prefix = "person")public class Person02 {private String name;private String sex;private Integer age;}
七. yaml配置注入
SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的
application.properties(上文数据注入已涉及)
语法结构 :key=value
application.yml
语法结构 :key:空格 value
配置文件作用 :修改SpringBoot自动配置的默认值,(SpringBoot在底层都给我们自动配置好了)
yaml基础语法
字面量:普通的值 [ 数字,布尔值,字符串 ]说明:语法要求严格!
空格不能省略以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。属性和值的大小写都是十分敏感的。
字面量直接写在后面就可以 , 字符串默认不用加上双引号或者单引号;
对象、Map(键值对)注意:
“ ”
双引号,不会转义字符串里面的特殊字符 , 特殊字符会作为本身想表示的意思;
''
单引号,会转义特殊字符 , 特殊字符最终会变成和普通字符一样输出
#对象、Map格式k: v1:v2:#或者行内写法行内写法K: {V1: XXX,V2: XXX}
数组( List、set )
用 - 值表示数组中的一个元素:
pets:- cat- dog- pig#行内写法pets: [cat,dog,pig]
数据注入和上文第六部分差不多,@Value
,@ConfigurationPropertiesn
批量注入
yaml语法特点:松散绑定
比如说在配置文件中给last-name赋值
用
@ConfigurationPropertiesn
绑定的时候将其给name绑定也可以成功
八. JSR303数据校验及多环境切换
数据验证
Springboot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。可以用@Email
注解被注解属性只支持Email格式
@Component@Data@ConfigurationProperties(prefix = "person")@Validated//数据验证public class Person {@Emailprivate String name;private int age;private String sex;}
配置文件:
person:name: 夜雨age: 18sex: 男
此时注入的数据
夜雨
不是邮件格式 所以会报错:
查看@Email
源码:
public @interface Email {String message() default "{javax.validation.constraints.Email.message}";}
改变默认错误提示信息:
@Email(message = "大佬,您的邮箱错啦!")
其它注解
常见参数:
核心:
@Pattera(value)
:正则表达式空检查
@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 对象是否符合正则表达式的规则
多环境切换
配置文件的多个位置
file:./configfile:./classpath:/config/classpath:/优先级:1>2>3>4(我们默认配置等级为4)
多环境切换
profile是Spring对不同环境提供不同配置功能的支持,可以通过激活不同的环境版本,实现快速切换环境;
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml , 用来指定多个环境版本:
properties 版本
application-test.properties 代表测试环境配置
application-dev.properties 代表开发环境配置
但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件; 我们需要通过一个配置来选择需要激活的环境:
yaml版本(优势:支持多文档块)
和properties配置文件中一样,但是使用yml去实现不需要创建多个配置文件,更加方便
server:port: 8080spring:profiles:active: test # 选择激活哪个版本---server:port: 8081spring:config:activate:on-profile: dev # 环境名称---server:port: 8082spring:config:activate:on-profile: test # 环境名称
注意:如果yml和properties同时都配置了端口,并且没有激活其他环境 ,默认会使用properties配置文件
Spring Boot 框架学习笔记(二)(配置文件与数据注入 yaml基本语法 JSR303数据验证 多环境切换 )