spring bean生命周期 后置处理器

User

@ToString
public class User {
    private Integer id;
    private String name;

    public void init() {
        System.out.println("init");
    }

    public void destroy() {
        System.out.println("destroy");
    }

    public User(Integer id, String name) {
        System.out.println("user 有参构造");
        this.id = id;
        this.name = name;
    }

    public User() {
        System.out.println("user 无参构造");
    }
}

后置处理器

bean的后置处理器,MyBeanPostProcessor 实现BeanPostProcessor接口,该接口有两个默认(default)方法分别在生命周期的初始化方法前后调用
bean:创建好的bean对象
beanName:bean对象对应配置文件中的bean id

public class MyBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("before " + bean + ":" + beanName);
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("after " + bean + ":" + beanName);
        return bean;
    }
}

applicationContext.xml

init-method:spring容器创建完对象后调用该类中的方法
destroy-method:spring容器容器关闭的时候执行

<bean id="user3" class="net.wanho.pojo.User" init-method="init" destroy-method="destroy"/>
<!-- 后置处理器 不需要写id -->
<bean class="net.wanho.pojo.MyBeanPostProcessor"/>

测试

@Test
public void beanLife() {
    private ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    User user = ac.getBean("user3", User.class);
    //关闭spring容器
    ((ClassPathXmlApplicationContext)ac).close();
}

结果

user 无参构造
before User(id=null, name=null):user3
init
after User(id=null, name=null):user3
destroy

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。