Spring 生命周期 各种初始化方法 执行顺序

BeanConfigAndLifeCycle
package com.study.spring.config;

import com.study.spring.bean.Cat;
import com.study.spring.bean.Dog;
import com.study.spring.bean.Pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfigAndLifeCycle {

    /**
     *  执行顺序: Construct(构造器) > @postConstruct > InitializingBean接口 > @Bean(initMethod) > BeanPostProcessor.postProcessBeforeInitialization
     *  执行顺序: @preDestroy >DisposableBean接口 > @Bean(destroyMethod)
     * 1)、指定初始化和销毁方法;
     * 		通过@Bean指定init-method和destroy-method;
     * 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
     * 				DisposableBean(定义销毁逻辑);
     * 3)、可以使用JSR250;
     * 		通过@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
     * 		通过@PreDestroy:在容器销毁bean之前通知我们进行清理工作
     * 4)、BeanPostProcessor【interface】:bean的后置处理器;
     * 		在bean初始化前后进行一些处理工作;
     * 		postProcessBeforeInitialization:在初始化之前工作
     * 		postProcessAfterInitialization:在初始化之后工作
     *
     * 	 * Spring底层对 BeanPostProcessor 的使用;
     *  * 		bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;
     * @return
     */
    //@Bean(initMethod = "running", destroyMethod = "back")
    @Bean(initMethod = "running", destroyMethod = "back")
    public Dog dog() {
        return new Dog();
    }


    //@Bean
    public Cat cat() {
        return new Cat();
    }
}

Dog

package com.study.spring.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Dog implements Pet,BeanPostProcessor, InitializingBean, DisposableBean {

    public Dog() {
        System.out.println("dog is Construct ing...");
    }

    @Override
    public void running() {
        System.out.println("dog is running...");
    }

    @Override
    public void back() {
        System.out.println("dog is back...");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("dog is destroy()");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("dog is afterPropertiesSet()...");
    }

    @PostConstruct
    public void postConstruct() throws Exception {
        System.out.println("dog is postConstruct()");
    }
    @PreDestroy
    public void preDestroy() throws Exception {
        System.out.println("dog is preDestroy()");
    }

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("dog is postProcessBeforeInitialization()" + o);
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("dog is postProcessAfterInitialization()" + o);
        return o;
    }

}

初始化执行顺序:

Construct(构造器) > @postConstruct > InitializingBean接口 > @Bean(initMethod) > BeanPostProcessor.postProcessBeforeInitialization > BeanPostProcessor.postProcessAfterInitialization

销毁方法执行顺序:

@preDestroy >DisposableBean接口 > @Bean(destroyMethod)

 

InitializingBean接口 > @Bean(initMethod)执行顺序原因:

AbstractAutowireCapableBeanFactory

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
			throws Throwable {

		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isDebugEnabled()) {
				logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			if (System.getSecurityManager() != null) {
				try {
					AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
						@Override
						public Object run() throws Exception {
							((InitializingBean) bean).afterPropertiesSet();
							return null;
						}
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
				((InitializingBean) bean).afterPropertiesSet();
			}
		}

		if (mbd != null) {
			String initMethodName = mbd.getInitMethodName();
			if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值