zoukankan      html  css  js  c++  java
  • 写一个完整的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
  • 相关阅读:
    NOIp 图论算法专题总结 (3):网络流 & 二分图 简明讲义
    zkw 线段树
    NOIp 图论算法专题总结 (2)
    NOIp 数据结构专题总结 (2):分块、树状数组、线段树
    单调栈、单调队列 思路及例题
    java自动装箱和拆箱
    HashMap和HashTable的异同点
    HttpServletRequest. getParameter获取的参数格式
    关于交换函数(1)
    std::vector::iterator重载了下面哪些运算符
  • 原文地址:https://www.cnblogs.com/woyujiezhen/p/13789907.html
Copyright © 2011-2022 走看看