#spring注解
理解spring bean 生命周期
- 实例化:spring对bean进行实例化
- 填充属性:spring将值和Bean的引用注入到Bean对应属性
- 调用BeanNameAware的setBeanName():如果Bean实现了该接口,Spring将Bean的ID传递给setBeanName()
- 调用BeanFactoryAware的setBeanFactory():如果Bean实现了该接口,Spring将BeanFactory容器实例传入
- 调用ApplicationContextAware的setApplicationContext():如果Bean实现了该接口,Spring将bean所在的上下文引用传入
- 调用BeanPostProcessor的预初始化方法:Spring调用他们的 postProcessBeforeInitialization()
- 调用InitializingBean的afterPropertiesSet():Spring调用他们的afterPropertiesSet().类似的bean使用init-method,该方法被调用
- 调用自定义的初始化方法
- 调用BeanPostProcessor的初始化方法 :Spring调用他们的 postProcessAfterInitialization()
- bean使用
- 容器关闭
- 调用DisposableBean的destroy()
- 调用自定义的销毁方法
自定义注解接口
spring 通过此类扫描:org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider。
默认并将带@Component扫描,通过方法registerDefaultFilters(),并注入到spring容器中。
示例:
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface MyComponent {
String value() default "";
}
@Configuration
@ComponentScan(includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = ComponentAnnotationTest.MyComponent.class)})
注解处理类
@Component
public class BoyAnnotationBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
return o;
}
}
添加BeanScannerConfigurer
- 继承ApplicationContextAware接口,Spring会读取ApplicationContextAware类型的的JavaBean,并调用setApplicationContext(ApplicationContext applicationContext)传入Spring的applicationContext。
- 继承BeanFactoryPostProcessor接口,Spring会在BeanFactory的相关处理完成后调用postProcessBeanFactory方法,进行定制的功能
package com.nbd.ocp.study.springboot.annotation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanScannerConfigurer implements BeanFactoryPostProcessor, ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
}