InitializingBean上篇
Posted xiaozhuanfeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了InitializingBean上篇相关的知识,希望对你有一定的参考价值。
参考: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); } } }
说明:
以上是关于InitializingBean上篇的主要内容,如果未能解决你的问题,请参考以下文章
spring的InitializingBean的 afterPropertiesSet 方法 和 init-method配置的区别联系
httpservlert 的init 方法与initializingbean的afterpropertiesset有啥显微的区
Spring中Bean初始化及销毁方法(InitializingBean接口DisposableBean接口@PostConstruct注解@PreDestroy注解以及init-method(代码片
Spring InitializingBean和init-method
Spring原理篇--BeanPostProcessor or BeanDefinition or Aware or InitializingBean