• 写一个完整的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
  • 相关阅读:
    用扑克牌保存文本信息
    计算机网络7--报文交换
    算法——字符串匹配之BM算法
    Head First Python 学习笔记-Chapter3:文件读取和异常处理
    页面登陆框老是乱乱的?banner跨页图片缩小之后总是在側面不能显示主要部分?哈哈~我来帮你忙~~
    happens-before通俗理解
    Eclipse中Git插件还原文件
    集成 Tomcat 插件到 Eclipse 的过程
    深入理解ClassLoader(五)—类的卸载
    使用eclipse远程调试Tomcat的方法
  • 原文地址:https://www.cnblogs.com/woyujiezhen/p/13789907.html
Copyright © 2020-2023  润新知