标签:one tor bst pack with instance cee catch context
参考:https://blog.csdn.net/zl834205311/article/details/78802584
记住一点:InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的子类,在初始化bean的时候会执行该方法。
下面看下简单的例子:(环境是用Spring Boot搭建,直接用SpringtestApplication启动即可)
<bean id="myInitializingBean" class="com.paic.phssp.springtest.init.MyInitializingBean" init-method="testInit"></bean>
package com.paic.phssp.springtest.init; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * 继承InitializingBean接口的类,在初始化bean的时候会执行该方法 */ //@Component public class MyInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("ceshi MyInitializingBean>>>>>>>>>>>>>>>>>>>"); } @PostConstruct //功能上近似init-method,但加载时机不同 public void test(){ System.out.println("PostConstruct >>>>>>>>>>>>"); } public void testInit(){ System.out.println("ceshi init-method"); } }
结果:
PostConstruct >>>>>>>>>>>>
ceshi MyInitializingBean>>>>>>>>>>>>>>>>>>>
ceshi init-method
说明:
通过上述输出结果,三者的先后顺序也就一目了然了:
Constructor > @PostConstruct > InitializingBean > init-method
(1)通过查看spring的加载bean的源码类(AbstractAutowireCapableBeanFactory)可看出其中奥妙:
AbstractAutowireCapableBeanFactory.invokeInitMethods
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = bean instanceof InitializingBean; if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (this.logger.isTraceEnabled()) { this.logger.trace("Invoking afterPropertiesSet() on bean with name ‘" + beanName + "‘"); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(() -> { ((InitializingBean)bean).afterPropertiesSet(); return null; }, this.getAccessControlContext()); } catch (PrivilegedActionException var6) { throw var6.getException(); } } else { ((InitializingBean)bean).afterPropertiesSet(); } } if (mbd != null && bean.getClass() != NullBean.class) { String initMethodName = mbd.getInitMethodName(); if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { this.invokeCustomInitMethod(beanName, bean, mbd); } } }
说明:
标签:one tor bst pack with instance cee catch context
原文地址:https://www.cnblogs.com/xiaozhuanfeng/p/10415794.html