spring通过注解注册bean的方式+spring生命周期
spring容器通过注解注册bean的方式
- @ComponentScan + 组件标注注解 (@Component/@Service...)
@ComponentScan(value = "com.example.demo.annotation")
spring会将
com.example.demo.annotation目录下标注了spring能识别的注解的类注册为bean
@ComponentScan还可以指定排除和包含规则- excludeFilters: 指定排除规则,排除哪些组件
- includeFilters: 指定只需要包含哪些组件,需要设置 useDefaultFilters = false
- FilterType.ANNOTATION 基于注解过滤
- FilterType.ASSIGNABLE_TYPE : 基于给定的类型过滤
- ...
- FilterType.CUSTOM: 自定义规则过滤
@ComponentScan(value = "com.example.demo.annotation",
/*excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
},*/
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Configuration.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {TestController.class}),
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyTypeFilter.class})
},useDefaultFilters = false
)
其中
CUSTOM自定义规则中的MyTypeFilter需要实现TypeFilter接口,举例如下public class MyTypeFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
String className = metadataReader.getClassMetadata().getClassName();
System.out.println("------>"+className);
if (className.contains("er")){
return true;
}
return false;
}
}
- @Bean (可以将第三方包中的类注册为bean)
@Bean
Person person() {
return new Person("zhang");
}
- @Import
@Import({Color.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
- 导入一个普通类,容器会自动注册这个组件,组件的id默认是类的全类名
- 导入
ImportSelector:返回需要注册的组件
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{"com.example.demo.annotation.bean.Red"};
}
}
- 导入
ImportBeanDefinitionRegistrar类
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean b = registry.containsBeanDefinition("com.example.demo.annotation.bean.Color");
boolean b1 = registry.containsBeanDefinition("com.example.demo.annotation.bean.Red");
if (b && b1){
registry.registerBeanDefinition("rainBow",new RootBeanDefinition(RainBow.class));
}
}
}
- 使用spring提供的 FactoryBean
public class ColorFactoryBean implements FactoryBean<Color> {
@Override
public Color getObject() throws Exception {
return new Color();
} @Override
public Class<?> getObjectType() {
return Color.class;
}
} @Bean
ColorFactoryBean colorFactoryBean() {
return new ColorFactoryBean();
}
applicationContext.getBean("colorFactoryBean") 默认获取到的是FactoryBean调用getObject方法返回的对象
要获取FactoryBean本身,需要在id前面加个& (&colorFactoryBean)
当满足某种条件时才注册bean,使用@Conditional
举例:在windows和linux上分别注册不同的bean
@Conditional({WindowsConditional.class})
@Bean("windows")
Person person1() {
return new Person("windows");
}
@Bean("linux")
@Conditional({LinuxConditional.class})
Person person2() {
return new Person("linux");
}
public class WindowsConditional implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Environment environment = conditionContext.getEnvironment();
String property = environment.getProperty("os.name");
return property.toLowerCase().contains("windows");
}
}
public class LinuxConditional implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Environment environment = conditionContext.getEnvironment();
String property = environment.getProperty("os.name");
return property.toLowerCase().contains("linux");
}
}
bean的生命周期
spring容器管理bean的生命周期:创建--》初始化--》销毁
我们可以自定义初始化和销毁方法,容器在bean进行到当前生命周期时来调用我们自定义的初始化和销毁方法
创建对象:
单实例:在容器启动时创建对象
多实例:在每次获取bean的时候创建对象每个BeanPostProcessor的 postProcessBeforeInitialization 方法会在初始化之前执行
初始化: 对象创建好,调用初始化方法
每个BeanPostProcessor的 postProcessAfterInitialization 方法会在初始化之后执行销毁:
单实例:容器关闭时销毁
多实例:容器会帮助创建这个bean,但不会管理这个bean,所以容器不会调用销毁方法,可以手动调用销毁方法
指定初始化和销毁的方法:
- 在 @Bean注解指定(initMethod = "",destroyMethod = "")
- 通过让bean实现 InitializingBean(定义初始化逻辑) 和 DisposableBean(定义销毁时逻辑)
- 使用JSR250: @PostConstruct (定义初始化逻辑) @PreDestroy(在容器销毁bean之前通知进行清理工作)
bean的后置处理器 BeanPostProcessor,其有如下两个方法,在bean的初始化前后做一些处理:
- postProcessBeforeInitialization:在初始化之前工作
- postProcessAfterInitialization:在初始化之后工作
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
private final ApplicationContext applicationContext;
public MyBeanPostProcessor(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization--->"+beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization--->"+beanName);
return bean;
}
}
如果自定义组件想要使用spring容器底层的组件(ApplicationContext,BeanFactory,***),自定义组件可以实现 ***Aware,
在创建bean的时候,相关BeanPostProcessor会调用接口规定的方法注入相关组件
例如:
如果自定义bean 实现了ApplicationContextAware 接口,在ApplicationContextAwareProcessor中会调用ApplicationContextAware的
setApplicationContext方法,注入ApplicationContext组件
spring通过注解注册bean的方式+spring生命周期的更多相关文章
- @Scope注解设置创建bean的方式和生命周期
1.1.1 Scope注解创建bean的方式和生命周期 作用 Scope设置对象在spring容器(IOC容器)中的生命周期,也可以理解为对象在spring容器中的创建方式. 取 ...
- Spring框架系列(三)--Bean的作用域和生命周期
Bean的作用域 Spring应用中,对象实例都是在Container中,负责创建.装配.配置和管理生命周期(new到finalize()) Spring Container分为两种: 1.BeanF ...
- 五 Spring的配置:Bean的配置,生命周期和作用范围
Bean相关的配置: <bean>标签的id和name的配置: id:使用了约束中的唯一约束,里面不能出现特殊字符 name:没有使用唯一约束,理论上可以重复,实际上开发不行,里面可以出现 ...
- 【String注解驱动开发】面试官让我说说:如何使用FactoryBean向Spring容器中注册bean?
写在前面 在前面的文章中,我们知道可以通过多种方式向Spring容器中注册bean.可以使用@Configuration结合@Bean向Spring容器中注册bean:可以按照条件向Spring容器中 ...
- 【String注解驱动开发】如何按照条件向Spring容器中注册bean?这次我懂了!!
写在前面 当bean是单实例,并且没有设置懒加载时,Spring容器启动时,就会实例化bean,并将bean注册到IOC容器中,以后每次从IOC容器中获取bean时,直接返回IOC容器中的bean,不 ...
- spring IOC容器实例化Bean的方式与RequestContextListener应用
spring IOC容器实例化Bean的方式有: singleton 在spring IOC容器中仅存在一个Bean实例,Bean以单实例的方式存在. prototype 每次从容器中调用Bean时, ...
- 在Listener(监听器)定时启动的TimerTask(定时任务)中使用Spring@Service注解的bean
1.有时候在项目中需要定时启动某个任务,对于这个需求,基于JavaEE规范,我们可以使用Listener与TimerTask来实现,代码如下: public class TestTaskListene ...
- Spring中Bean的作用域、生命周期
Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...
- Spring之Bean的作用域与生命周期
在前面博客中提到容器启动获得BeanDefinition对象中有一个scope 属性.该属性控制着bean对象的作用域.本章节介绍Bean的作用域及生命周期,了解bean是怎么来的又怎么没的. 一.B ...
随机推荐
- windows下wchar_t的问题
使用vs新建工程或者编译工程的时候默认在编译设置里面讲wchar_t设置为内置类型,如下图: 但是在编译相互依赖的工程的时候,如果有的工程不将wchar_t设置为内置类型的时候,将会出现链接错误,需要 ...
- shell脚本自学笔记
一. 什么是Shell脚本 shell脚本并不能作为正式的编程语言,因为它是在linux的shell中运行的,所以称为shell脚本.事实上,shell脚本就是一些命令的集合. 假如完成某个需求需要一 ...
- 攻防世界 web4.cookie
题有几种解法,我有点懒,懒的打开burp,所以可以直接在浏览器拿flag, 首先访问ip/cookie.php,提示:See the http response 接着F12查看响应头 给你cyberp ...
- Luogu P1196 [NOI2002]银河英雄传说 | 并查集
题目链接 并查集,具体看注释. #include<iostream> #include<cstdio> #include<cmath> using namespac ...
- 记录自己的踩坑第一天 | CSS:vertical-align 属性
前言 最近老师让大家单独写前后端分离项目,真是大家卷完后端,一起去卷前端了.(我以前都是主要负责后端,处于只大致看的懂的级别,说多了都是泪啊). 真是处于一边学一边写的状态,基本就是每天早上看上两~三 ...
- 面试题系列:用了这么多年的 Java 泛型,我竟然只知道它的皮毛
面试题:说说你对泛型的理解? 面试考察点 考察目的:了解求职者对于Java基础知识的掌握程度. 考察范围:工作1-3年的Java程序员. 背景知识 Java中的泛型,是JDK5引入的一个新特性. 它主 ...
- k8s入坑之路(16)kubernetes中CICD/基于宿主机jenkins
cicd的结合组件 需要代码仓库如gitlab.github.包构建工具Maven等,持续集成工具如jenkins,github/cicd.结合自己脚本实现重复式任务自动化. 传统服务发布流程: 提交 ...
- Mysql基础教程:(七)MySQL基础练习
MySQL基础练习 一.创建student和score表 CREATE TABLE student (id INT(10) NOT NULL PRIMARY KEY ,name VARCHAR(20) ...
- requestAnimationFrame 执行机制探索
1.什么是 requestAnimationFrame window.requestAnimationFrame() 告诉浏览器--你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更 ...
- 微软商店打不开的教程(错误代码0x80131500)
1 打开win+R 输入`inetcpl.cpl` 2 点击高级 3 勾选上`使用TLS 1.2`或者点击还原默认设置就可以啦 4 然后就可以打开啦