Spring - bean的生命周期与后置处理器

1.设置初始化之前与对象销毁之前执行的方法

public class UserService {
    /*对象初始化之前执行*/
    public void initMethod(){

    }

    /*对象初始化之后执行*/
    public void destroyMethod(){

    }
}
    <bean id="userService" class="com.levi.dao.UserService" 
          init-method="initMethod" destroy-method="destroyMethod"/>

2.后置处理器

/*
* ioc容器中的所有对象初始化时都会执行以下这两个方法
* */
public class BeanPost implements BeanPostProcessor {
    /*对象初始化之前执行*/
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    /*对象初始化之后执行*/
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
    <!--注册后置处理器-->
    <bean name="beanPost "class="com.levi.BeanPost"/>

 

posted on 2021-12-08 15:26  每天积极向上  阅读(33)  评论(0编辑  收藏  举报

导航