写一个完整的Spring生命周期例子

一共三个类:

 

@不能被Spring管理,因为需要通过@Bean的方法加上initMethod和destroyMethod
public
class Car implements InitializingBean, DisposableBean { public Car() { System.out.println("构造函数"); } @PreDestroy public void aa() { System.out.println("@PreDestroy"); } @PostConstruct public void bb() { System.out.println("@PostConstruct"); } @Override public void destroy() throws Exception { System.out.println("重写的DisposableBean方法"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("重写的InitializingBean方法"); } public void initMethod() { System.out.println("initMethod"); } public void destroyMethod() { System.out.println("destroyMethod"); } }

 

@Component
public class MainConfigOfLifeCycle {

    @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
    public Car car() {
        return  new Car();
    }
}
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization  " + bean + "  " + beanName);
#这里return bean和return null是有区别的
return bean;
    }

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

 

结果如下:

构造函数
postProcessBeforeInitialization  com.config.Car@3ad847f8  car
@PostConstruct  #@PostConstruct:postProcessBeforeInitializatin中return 了bean则有这个输入,但如果return null则没有这个输出
重写的InitializingBean方法
initMethod
postProcessAfterInitialization  com.config.Car@3ad847f8  car
@PreDestroy
重写的DisposableBean方法
destroyMethod

 

posted on 2020-10-10 07:31  我欲皆真  阅读(185)  评论(0编辑  收藏  举报

导航