原理初探
自动配置:
pom.xml(注:我的pom.xml中没有parent 手动加的)
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.4.5</version>
<relativePath/>
</parent>
- spring-boot-dependencies:核心依赖在父工程。
- 我们在写或者引入一些springboot依赖的时候,不需要指定版本,就是因为有这些版本仓库。
启动器:
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
-
启动器:说白了就是springboot的启动场景。
-
比如:spring-boot-starter-web,它就会帮我们自动导入web环境所有的依赖!
-
springboot会将所有的功能场景,都变成一个个启动器。
-
我们要使用什么功能,就只需要找到对应的启动器就可以了。
官网地址查看启动器:https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
主程序
package com.kuang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication:标注这个类是一个springboot的应用
@SpringBootApplication
public class Springboot01HelloworldApplication {
//将springboot应用启动
//SpringApplication类
//run方法
public static void main(String[] args) {
SpringApplication.run(Springboot01HelloworldApplication.class, args);
}
}
-
注解:
-
@SpringBootConfiguration: springboot的配置 @Configuration :spring配置类 @Component :说明这也是一个spring的组件 @EnableAutoConfiguration:自动配置 @AutoConfigurationPackage:自动配置包 @Import({Registrar.class}) public @interface AutoConfigurationPackage :自动配置包注册 @Import({AutoConfigurationImportSelector.class}):自动导入选择 @ComponentScan:扫描当前主启动类同级下的包 //获取所有的配置 List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
-
获取候选的配置:
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}
META-INF/spring.factories:自动配置的核心文件
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
//所有的资源加载到配置类中
==结论:==springboot所有自动配置都是在启动的时候扫描并加载:spring.factories所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立,只要导入了对应的start,就有对应的启动器了,有了启动器,我们自动装配就会生效,然后就配置成功。
1.springboot在启动的时候,从类路径下/META-INF/spring.factories获取指定的值;
2.将这些自动配置的类导入容器,自动配置就会生效,帮我们进行自动配置!
3.以前我们需要自动配置的东西,现在springboot帮我们做了!
4.整合javaEE,解决方案和自动配置的东西都在spring-boot-autoconfigure-2.4.5.jar这个包
5.它会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器。
6.容器中会存在非常多的xxxAutoConfiguration的文件(@Bean),就是这些类给容器中导入了这个场景需要的所有组件;并自动配置,@Configuration, JavaConfig!
7.有了自动配置类,免去了我们手动编写配置文件的工作。
Run
开启了一个服务:
package com.kuang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication:标注这个类是一个springboot的应用
@SpringBootApplication
public class Springboot01HelloworldApplication {
//将springboot应用启动
//SpringApplication类
//run方法
public static void main(String[] args) {
//该方法返回一个ConfigurableApplicationContext对象
//参数一:应用入口的类 参数类:命令行参数 SpringApplication.run(Springboot01HelloworldApplication.class, args);
}
}
SpringApplication.run分析:
分析该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行。
SpringApplication
这个类主要做了以下四件事:
1.推断应用的类型是普通项目还是web项目。
2.查找并加载所有可用初始化器,设置到initializers属性中
3.找出所有的应用程序监听器,设置到listeners属性中
4.推断并设置main方法的定义类,找到运行的主类。
查看构造器
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = Collections.emptySet();
this.isCustomEnvironment = false;
this.lazyInitialization = false;
this.applicationContextFactory = ApplicationContextFactory.DEFAULT;
this.applicationStartup = ApplicationStartup.DEFAULT;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.bootstrapRegistryInitializers = this.getBootstrapRegistryInitializersFromSpringFactories();
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}
JavaConfig的核心是:@Configuration @Bean
面试:关于SpringBoot,谈谈你的理解
- 自动装配
- run()
SpringBoot配置
实现热部署的操作:
配置文件
pom.xml中没有parent 手动加:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.4.5</version>
</parent>
SpringBoot使用一个全局的配置文件,配置文件名称是固定的
- application.properties
- 语法结构: key = value
- application.yml
- 语法结构:key: 空格 value
配置文件的作用:修改SpringBoot自动配置的默认值,因为SpringBoot在底层都给我们自动配置好了。
YAML
YAML是’YAML Ain’t a Markup Language’(YAML不是一种置标语言)
在开发这种语言时,YAML的意思就是:“Yet Another Markup Language”(仍是一种置标语言)
YAML A Markup Language: 是一个标记语言
YAML isnot Markup Language :不是一个标记语言
标记语言
以前的配置文件,大多数都是使用xml来配置;比如一个简单的端口配置,对比yaml和xml
yaml配置
server:
port: 8080
xml配置
<server>
<port>8081</port>
</server>
YAML 语法
基础语法:
k:(空格) v
以此来表示一对键值对(空格不能省略);以空格的缩进来控制层级关系,只要是左边对齐的一列数据都是同一级的。
注意:属性的值和大小写都是十分敏感的。例如
server:
port: 8080
path: /hello
值的写法
字面量:普通的值[数字, 布尔值, 字符串]
k: v
字面量直接写在后面就可以,字符串默认不加上双引号或者单引号;
“” 双引号,不会转义字符串里面的特殊字符,特殊字符会作为本身想表示的意思;
比如:name: “kuang\n shen” 输出 : kuang 换行 shen
# k=v
# 对空格的要求十分高 不在同一个位置的级别就变了
# 注入到我们的配置类中
# 普通的key-value
name: qinjiang
# 对象
studnt:
name: qinjiang
age: 3
# 行内写法
studnt1: {name: qinjiang, age: 3}
# 数组
pets:
- cat
- dog
- pig
pets1: [cat,dog,pig]
yaml可以直接给实体类赋值
首先举例原来的使用方法:
程序实现
1.如果要使用properties配置文件可能导入时存在乱码问题,需要在IDEA中进行调整,我们这里直接使用yaml文件,将默认的application.properties后缀修改为yaml
properties配置文件在写中文的时候,会有乱码,需要在IDEA中设置编码格式为UTF-8
pojo
Dog.java
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Dog {
@Value("旺财")
private String name;
@Value("3")
private Integer age;
public Dog() {
}
public Dog(String name, Integer age) {
this.name = name;
this.age = 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;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试:
package com.kuang;
import com.kuang.pojo.Dog;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot02ConfigApplicationTests {
@Autowired
private Dog dog;
@Test
void contextLoads() {
System.out.println(dog);
}
}
爆红也不会影响运行 解决这个问题的办法是在pom.xml 进行配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
出现的错误: java.lang.NoClassDefFoundError: org/springframework/test/context/TestContextAnnotationUtils
目前的解决方法:重新建项目 就没事了 网上的办法目前对我这个没有用
Person.java
package com.kuang.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")
/*
@ConfigurationProperties作用:
将配置文件中配置的每一个属性的值,映射到这个组件中;
告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
参数prefix = "person" :将配置文件中的person下面的所有属性一一对应
只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能
*/
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;
//输出结果Person{name='qinjiang', age=3,
// happy=false, birth=Sat Apr 17 00:00:00 GMT+08:00 2021,
// maps={k1=v1, k2=v2}, lists=[code, music, study],
// dog=Dog{name='旺财', age=3}}
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 +
'}';
}
}
resources:
application.yaml
person:
name: qinjiang
age: 3
happy: false
birth: 2021/4/17
maps: {k1: v1, k2: v2}
lists:
- code
- music
- study
dog:
name: 旺财
age: 3
第二种测试application.yaml
person:
name: qinjiang${random.uuid}
age: ${random.int}
happy: false
birth: 2021/4/17
maps: {k1: v1, k2: v2}
lists:
- code
- music
- study
dog:
name: ${person.hello:hello}_旺财
age: 3
输出的 dog=Dog{name=‘hello_旺财’
如果application.yaml是这样写的‘:
person:
name: qinjiang${random.uuid}
age: ${random.int}
happy: false
birth: 2021/4/17
maps: {k1: v1, k2: v2}
hello: haayy
lists:
- code
- music
- study
dog:
name: ${person.hello:hello}_旺财
age: 3
输出的为: dog=Dog{name=‘haayy_旺财’
绑定配置文件的第二种写法:
package com.kuang.pojo;
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.Date;
import java.util.List;
import java.util.Map;
@Component //注册bean
//javaConfig 绑定我们配置文件的值,可以采取这些方式
// 加载指定的配置文件
@PropertySource(value = "classpath:qinjiang.properties")
public class Person {
//SPEL表达式取出配置文件的值
@Value("${name}")
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 +
'}';
}
}
实现结果:
功能图对比
- cp 只需要写一次即可,value则需要每个字段都添加
- 松散绑定: 比如我的yaml中写的last-name, 这个和lastName是一样的, -后面跟着的字母默认是大写的。这就是松散绑定
package com.kuang.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
private String firstName;
private Integer age;
public Dog() {
}
public Dog(String firstName, Integer age) {
this.firstName = firstName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"firstName='" + firstName + '\'' +
", age=" + age +
'}';
}
}
person:
name: qinjiang${random.uuid}
age: ${random.int}
happy: false
birth: 2021/4/17
maps: {k1: v1, k2: v2}
hello: haayy
lists:
- code
- music
- study
dog:
name: ${person.hello:hello}_旺财
age: 3
dog:
first-name: 阿黄
age: 3
结果:
- JSR303数据校验,这个就是我们可以在字段是增加一层过滤器验证,可以保证数据的合法性
- 复杂类型封装,yaml中可以封装对象,使用@value就不支持验证
结论:
- 配置yaml和配置properties都可以获得值,推荐yaml
- 如果我们在某个业务中,只需要获得配置文件中的某个值,可以使用一下@value
- 如果说我们专门编写了一个JavaBean来和配置文件进行映射,就直接使用@configurationProperties
JSR303数据校验
spring-boot 中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。
出现的问题:Cannot resolve symbol 'Email’
原因缺少相关依赖:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
这个JSR-303地址:https://www.jianshu.com/p/554533f88370
@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=) Validates that the annotated string is between min and max included
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证String 对象是否符合正则表达式的规则
JSR303校验文件: