Spring注解系列十四:生命周期-BeanPostProcessor

转:https://blog.csdn.net/lizhiqiang1217/article/details/89950527

1、MainConfigOfLifeCycle

/**
 * 4)、BeanPostProcessor【interface】:bean的后置处理器;
 *      在bean初始化前后进行一些处理工作;
 *      postProcessBeforeInitialization:在初始化之前工作
 *      postProcessAfterInitialization:在初始化之后工作
 */
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {

}

2、创建类MyBeanPostProcessor 。实现BeanPostProcessor 接口

/**
 * 后置处理器:初始化前后进行处理工作
 * 将后置处理器加入到容器中
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
        return bean;
    }
}

3、测试

@Test
public void test01(){
    //1、创建ioc容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
    System.out.println("容器创建完成...");
    
    //关闭容器
    applicationContext.close();
}
图片.png

你可能感兴趣的:(Spring注解系列十四:生命周期-BeanPostProcessor)