当前栏目
SpringBoot2----容器功能
容器功能
本篇笔记是在尚硅谷SpringBoot2核心技术与响应式编程这篇笔记的基础上,增加一些个人注解
2.1、组件添加
1、@Configuration
基本使用
Full模式与Lite模式
- 示例
- 最佳实战
- 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
这里有无依赖多指是否在一个类中使用到另一个类,例如在People类里面,Cat类是People里的一个属性,这样People和cat类之间就产生了依赖关系
1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的 2、配置类本身也是组件,即配置类本身也被注册在了IOC容器中 3、proxyBeanMethods:代理bean的方法 Full(proxyBeanMethods = true)【保证每个@Bean方法被调用多少次返回的组件都是单实例的】 Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的,多实例,调用时创建】 组件依赖必须使用Full模式默认。其他默认是否Lite模式
#############################Configuration使用示例######################################################
/**
* 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
* 2、配置类本身也是组件
* 3、proxyBeanMethods:代理bean的方法
* Full(proxyBeanMethods = true)【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
* Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
* 组件依赖必须使用Full模式默认。其他默认是否Lite模式
*/
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
/**
* Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
* @return
*/
@Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public User user01(){
User zhangsan = new User("zhangsan", 18);
//user组件依赖了Pet组件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom")//当然也可以选择给组件起名,作为在容器中的唯一标识id
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
################################@Configuration测试代码如下########################################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
//3、从容器中获取组件
Pet tom01 = run.getBean("tom", Pet.class);
Pet tom02 = run.getBean("tom", Pet.class);
System.out.println("组件:"+(tom01 == tom02));
//4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
MyConfig bean = run.getBean(MyConfig.class);
System.out.println(bean);
//如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
//保持组件单实例
User user = bean.user01();
User user1 = bean.user01();
System.out.println(user == user1);
User user01 = run.getBean("user01", User.class);
Pet tom = run.getBean("tom", Pet.class);
System.out.println("用户的宠物:"+(user01.getPet() == tom));
}
}
Full模式与Lite模式注意点如下
Full模式和Lite模式是针对spring配置而言的,和xml配置无关。
何时为Lite模式:
- 1.类上有@Component注解
- 2.类上有@ComponentScan注解
- 3.类上有@Import注解
- 4.类上有@ImportResource注解
- 5.类上没有任何注解,但是类中存在@Bean方法
- 6.类上有@Configuration(proxyBeanMethods = false)注解
Lite总结:运行时不用生成CGLIB子类,提高运行性能,降低启动时间,可以作为普通类使用。但是不能声明 @Bean之间的依赖
何时为Full模式:
- 1.标注有@Configuration或者@Configuration(proxyBeanMethods = true)的类被称为Full模式的配置类。
- Full模式总结:单例模式能有效避免Lite模式下的错误。性能没有Lite模式好
关于SpringBoot的Full模式与Lite模式上面案例的总结
- proxyBeanMethods注意到这个属性了吧,我们知道,在上图中,@Bean是用来注册组件到容器之中的,如下图,我们从容器中连续取俩次Pet,取到的是否相等呢,我们知道,当是单例模式时取到的必然相等。
- 那我们回到proxyBeanMethods这个属性,当他为true时,表示注册到容器中的Myconfig这个类是一个代理类,而Myconfig这个类可以调用tomcatPet()这个方法,容器每次获取Pet对象都会调用tomcatPet()这个方法
- 当容器中的myconfig是一个代理类时,每次调用方法之前都会检查springboot容器中是否有Pet对象,如果有就会直接从容器中取出,没有才调用方法创建对象。
- 而当proxyBeanMethods这个属性为false时,表示注册到容器中的Myconfig这个类不是一个代理类,那么每次调用tomcatPet()方法之前不会检查springboot容器中是否有Pet对象,而是直接调用方法创建一个对象,那么两个Pet对象便不会相同。
2、@Bean、@Component、@Controller、@Service、@Repository这些注解都可以用来注册组件到容器中,当然注册组件到容器中的方法不止这些
3、@ComponentScan、@Import
4、@Import({User.class, DBHelper.class})
给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}
@Import 高级用法:https://www.bilibili.com/video/BV1gW411W7wy?p=8
4、@Conditional
条件装配:满足Conditional指定的条件,则进行组件注入
放在配置类上表示,当容器中满足条件时,配置类中的组件才生效; 放在配置方法上的时候,表示的意思是当满足条件的时候配置方法才生效;
=====================测试条件装配==========================
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
/**
* Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
* @return
*/
@Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public User user01(){
User zhangsan = new User("zhangsan", 18);
//user组件依赖了Pet组件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom22")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
boolean tom = run.containsBean("tom");
System.out.println("容器中Tom组件:"+tom);
boolean user01 = run.containsBean("user01");
System.out.println("容器中user01组件:"+user01);
boolean tom22 = run.containsBean("tom22");
System.out.println("容器中tom22组件:"+tom22);
}
2.2、原生配置文件引入
1、@ImportResource
将原生的Spring.xml的配置文件,通过@ImportResource导入后SpringBoot进行解析,完成对应的组件注册 位置:在某个配置类的上方
======================beans.xml=========================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="haha" class="com.atguigu.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.atguigu.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
@Configuration
@ImportResource("classpath:beans.xml")
public class MyConfig {}
======================测试=================
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true
2.3、配置绑定
如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;
方式一:@Component + @ConfigurationProperties
对应要绑定的类:
/**
* 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
*/
@Component
@ConfigurationProperties(prefix = "mycar")//指定要与配置文件中以某前缀开始的值进行属性匹配
public class Car {
private String brand;
private Integer price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + ''' +
", price=" + price +
'}';
}
}
对应的配置文件:
mycar.brand="宝马"
mycar.price=100000
配置类:
@SpringBootApplication
public class SpringBoot2Demo1Application {
public static void main(String[] args)
{
ConfigurableApplicationContext app = SpringApplication.run(SpringBoot2Demo1Application.class, args);
Car car = app.getBean(Car.class);
System.out.println(car);
}
}
方式二: @EnableConfigurationProperties + @ConfigurationProperties
对应要绑定的类:
@ConfigurationProperties(prefix = "mycar")//指定要与配置文件中以某前缀开始的值进行属性匹配
public class Car {
private String brand;
private Integer price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + ''' +
", price=" + price +
'}';
}
}
对应的配置文件:
mycar.brand="宝马"
mycar.price=100000
配置类:
@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
@SpringBootApplication
public class SpringBoot2Demo1Application {
public static void main(String[] args)
{
ConfigurableApplicationContext app = SpringApplication.run(SpringBoot2Demo1Application.class, args);
Car car = app.getBean(Car.class);
System.out.println(car);
}
}
小总结
一般使用这种方式
@EnableConfigurationProperties(Car.class) // 开启 Car 的属性配置并自动注入到容器中
public class MyConfiguration {
@ConfigurationProperties(prefix = "mycar")//指定要与配置文件中以某前缀开始的值进行属性匹配
public class Car {
3、自动配置原理入门
3.1、引导加载自动配置类===@SpringBootApplication的组合注解如下:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{}
1、@SpringBootConfiguration
@Configuration。代表当前是一个配置类
@ SpringBootConfiguration只是Spring标准@Configuration批注的替代方法。 两者之间的唯一区别是@SpringBootConfiguration允许自动找到配置。
2、@ComponentScan
指定扫描哪些,Spring注解;
3、@EnableAutoConfiguration的组合注解如下
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}
1、@AutoConfigurationPackage
自动配置包?指定了默认的包规则
@Import(AutoConfigurationPackages.Registrar.class) //给容器中导入一个组件
public @interface AutoConfigurationPackage {}
利用Registrar给容器中导入一系列组件
将指定的一个包下的所有组件导入进来?MainApplication 所在包下。
默认包扫描原理就在这里体现
使用@import将AutoConfigurationPackages包下的Registrar类作为组件导入到容器中,然后使用Registrar中的方法批量完成组件的注册。
2、@Import(AutoConfigurationImportSelector.class)
1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4、从META-INF/spring.factories位置来加载一个文件。
默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories
文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,
........
调用关系及总结
3.2、按需开启自动配置项
虽然我们127个场景的所有自动配置启动的时候默认全部加载。xxxxAutoConfiguration
按照条件装配规则(@Conditional),最终会按需配置。
3.3、修改默认配置
springmvc文件上传功能,下面是springboot默认配置的文件上传功能:
@Bean
@ConditionalOnBean(MultipartResolver.class) //容器中有这个类型组件
@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
public MultipartResolver multipartResolver(MultipartResolver resolver) {
//给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
//SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
// Detect if the user has created a MultipartResolver but named it incorrectly
return resolver;
}
给容器中加入了文件上传解析器;
下面展示springmvc原生的springmvc.xml中对文件上传功能的.xml配置:
<!--文件上传解析器: id必须是multipartFile-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置文件上传最大量为5m-->
<property name="maxUploadSize" value="5242880"></property><!--spel运算符,计算最大可上传文件体积-->
<!--设置默认的编码-->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先====约定大于配置
@Bean
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
}
总结
- SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
- 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
- 生效的配置类就会给容器中装配很多组件
- 只要容器中有这些组件,相当于这些功能就有了
定制化配置
- 用户直接自己@Bean替换底层的组件
- 用户去看这个组件是获取的配置文件什么值就去修改。
xxxxxAutoConfiguration —> 组件 —> xxxxProperties里面拿值 ----> application.properties
3.4、最佳实践
- 引入场景依赖—下面的链接是SprigBoot提供的所有启动器
- 查看自动配置了哪些,即哪些自动配置生效了,哪些没生效
自己分析,引入场景对应的自动配置一般都生效了
配置文件中debug=true开启自动配置报告。Negative(不生效)Positive(生效)
- 是否需要修改相关配置
参照文档修改配置项,springboot官网文档,展示可修改的配置属性
自己分析。xxxxProperties绑定了配置文件的哪些。
自定义加入或者替换组件,用户配置的组件优先===》@Bean、@Component…
自定义器 XXXXXCustomizer
4、开发小技巧
4.1 开发小技巧
简化JavaBean开发
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
idea中搜索安装lombok插件
===============================简化JavaBean开发===================================
@NoArgsConstructor
//@AllArgsConstructor
@Data
@ToString
@EqualsAndHashCode
public class User {
private String name;
private Integer age;
private Pet pet;
public User(String name,Integer age){
this.name = name;
this.age = age;
}
}
================================简化日志开发===================================
@Slf4j
@RestController
public class HelloController {
@RequestMapping("/hello")
public String handle01(@RequestParam("name") String name){
log.info("请求进来了....");
return "Hello, Spring Boot 2!"+"你好:"+name;
}
}
lombok提供的注解如下
- @ToString—帮助生成ToString方法
- @AllArgsConstructor—生成全参构造器
- @NoArgsConstructor—生成无参构造方法
- @EqualsAndHashCode—生成HashCode方法
- @Data:该注解相当于同时加上以下注解@Setter @Getter,@ToString,@EqualsAndHashCode
- @Getter:生成getter方法
- @Setter:生成setter方法
4.2、dev-tools
spring-boot-devtools是一个为开发者服务的一个模块,其中最重要的功能就是自动应用代码更改到最新的App上面去。原理是在发现代码有更改之后,重新启动应用,但是速度比手动停止后再启动还要更快,更快指的不是节省出来的手工操作的时间。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
项目或者页面修改以后:Ctrl+F9 ===>项目重新编译
4.3、Spring Initailizr(项目初始化向导)
0、选择我们需要的开发场景
1、自动依赖引入
2、自动创建项目结构
3、自动编写好主配置类
相关文章
- 鲜为人知但很有用的 HTML 属性
- 翻转再翻转!有意思的水平横向溢出滚动
- 自定义计数器小技巧!CSS 实现长按点赞累加动画
- 过五关!React高频面试题指南
- 软件开发中的十个认知偏差
- 不需要 JS!仅用 CSS 也能达到监听页面滚动的效果!
- 一文读懂TypeScript类型兼容性
- Vue 的响应式原则与双向数据绑定
- 快速掌握 TypeScript 新语法:Infer Extends
- JWT教你如何证明你是我的人!
- 一篇带给你 V8 GC 的实现
- 面试官:请使用JS完成一个LRU缓存?
- 通过可视化来学习JavaScript事件循环
- 新的跨域策略:使用 COOP、COEP 为浏览器创建更安全的环境
- 为什么有人说 vite 快,有人却说 vite 慢?
- 种草 Vue3 中几个好玩的插件和配置
- 超全面的前端工程化配置指南
- Vue 状态管理未来样子
- Volatile关键字能保证原子性么?
- 面试突击:SpringBoot 有几种读取配置文件的方法?