首页  

spring bean生命周期及扩展点     所属分类 spring 浏览量 1463
bean 实例化 初始化 使用 销毁

实例化 instantiation
初始化 initialization

1 BeanFactoryPostProcessor

void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
加载完bean定义之后, bean实例化之前 ,回调该方法 ,修改bean定义元数据 BeanDefinition

2 Bean实例化 ,反射调用 构造函数

3 Bean属性注入

4 BeanNameAware

5 BeanFactoryAware

6 ApplicationContextAware

7 BeanPostProcessor  postProcessBeforeInitialization

    @Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
	
	default 声明接口默认方法
	
	

8 InitializingBean的afterPropertiesSet()方法

  void afterPropertiesSet() throws Exception;

9 自定义的inti-method方法

10 BeanPostProcessor postProcessAfterInitialization

    @Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
	

11 bean 使用

12 DisposableBean 的 destory()方法

   

13 自定义的destory-method方法

   void destroy() throws Exception;
   
   
BeanFactoryPostProcessor 和  BeanPostProcessor 常见的扩展点


@Configuration
@Component
public class MyBeanFactoryPostProcesser implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 不要调用 getBean 方法 ,会提前实例化  
        //Cat cat = beanFactory.getBean("cat", Cat.class);
        BeanDefinition bd = beanFactory.getBeanDefinition("cat");
        bd.getPropertyValues().add("name", "cat-new");
        bd.setScope(BeanDefinition.SCOPE_SINGLETON);
        bd.setLazyInit(true);
       
    }
}


@Configuration
@Component
public class MyBeanPostProcesser implements BeanPostProcessor {
    @Nullable
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization run,beanName=" + beanName);
        return bean;
    }

    @Nullable
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization run,beanName=" + beanName);
        return bean;
    }
}

上一篇     下一篇
java内存模型

spring和springboot发展历史

spring扩展点

spring xml bean 配置读取

为何要定投指数基金

spring5事件机制