項目中用到了 afterPropertiesSet: 於是具體的查了一下到底afterPropertiesSet到底是什么時候執行的。為什么一定要實現 InitializingBean;
**/ @Component public class CityRepositoryImpl implements CityRepository, InitializingBean { private static final Logger LOGGER = LoggerFactory.getLogger(CityRepositoryImpl.class); @Override public void afterPropertiesSet() { synchronized (CityRepositoryImpl.class) { if (TEMPLATE_METHOD_MAP.size() == 0) { loadTemplateMethod(); } } } }}
Spring 容器中的 Bean 是有生命周期的,Spring 允許在 Bean 在初始化完成后以及 Bean 銷毀前執行特定的操作,常用的設定方式有以下三種:
(1) 通過實現 InitializingBean/DisposableBean 接口來定制初始化之后/銷毀之前的操作方法;
(2) 通過 <bean> 元素的 init-method/destroy-method屬性指定初始化之后 /銷毀之前調用的操作方法;
(3) 在指定方法上加上@PostConstruct 或@PreDestroy注解來制定該方法是在初始化之后還是銷毀之前調用。
這是我們就有個疑問,這三種方式是完全等同的嗎,孰先孰后?
下面我們將帶着這個疑問,試圖通過測試代碼以及分析Spring源碼找到答案。
首先,我們還是編寫一個簡單的測試代碼:
public class InitSequenceBean implements InitializingBean { public InitSequenceBean() { System.out.println("InitSequenceBean: constructor"); } @PostConstruct public void postConstruct() { System.out.println("InitSequenceBean: postConstruct"); } public void initMethod() { System.out.println("InitSequenceBean: init-method"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("InitSequenceBean: afterPropertiesSet"); } }
並且在配置文件中添加如下Bean定義:
<bean class="InitSequenceBean" init-method="initMethod"></bean>
好了,我們啟動Spring容器,觀察輸出結果,就可知道三者的先后順序了:
InitSequenceBean: constructor
InitSequenceBean: postConstruct
InitSequenceBean: afterPropertiesSet
InitSequenceBean: init-method
通過上述輸出結果,三者的先后順序也就一目了然了:
Constructor > @PostConstruct > InitializingBean > init-method
先大致分析下為什么會出現這些的結果:構造器(Constructor)被率先調用毋庸置疑,InitializingBean先於init-method我們也可以理解(在也談Spring容器的生命周期中已經討論過),但是PostConstruct為何率先於InitializingBean執行呢?
我們再次帶着這個疑問去查看Spring源代碼來一探究竟。
通過Debug並查看調用棧,我們發現了這個類org.springframework.context.annotation.CommonAnnotationBeanPostProcessor,從命名上,我們就可以得到某些信息——這是一個BeanPostProcessor。想到了什么?在也談Spring容器的生命周期中,我們提到過BeanPostProcessor的postProcessBeforeInitialization是在Bean生命周期中afterPropertiesSet和init-method之前執被調用的。
再次觀察CommonAnnotationBeanPostProcessor這個類,它繼承自InitDestroyAnnotationBeanPostProcessor。InitDestroyAnnotationBeanPostProcessor顧名思義,就是在Bean初始化和銷毀的時候所作的一個前置/后置處理器。
通過查看InitDestroyAnnotationBeanPostProcessor類下的postProcessBeforeInitialization方法:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); try { metadata.invokeInitMethods(bean, beanName); } catch (InvocationTargetException ex) { throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Couldn't invoke init method", ex); } return bean; }
查看findLifecycleMetadata方法,繼而我們跟蹤到buildLifecycleMetadata這個方法體中,看下buildLifecycleMetadata這個方法體的內容:
private LifecycleMetadata buildLifecycleMetadata(final Class clazz) { final LifecycleMetadata newMetadata = new LifecycleMetadata(); final boolean debug = logger.isDebugEnabled(); ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { if (initAnnotationType != null) { if (method.getAnnotation(initAnnotationType) != null) { newMetadata.addInitMethod(method); if (debug) { logger.debug("Found init method on class [" + clazz.getName() + "]: " + method); } } } if (destroyAnnotationType != null) { if (method.getAnnotation(destroyAnnotationType) != null) { newMetadata.addDestroyMethod(method); if (debug) { logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method); } } } } }); return newMetadata; }
分析這段代碼發現,在這里會去判斷某方法有沒有被initAnnotationType/destroyAnnotationType注釋,如果有,則添加到init/destroy隊列中,后續一一執行。
initAnnotationType/destroyAnnotationType注釋是什么呢,我們在CommonAnnotationBeanPostProcessor的構造函數中看到下面這段代碼:
/**
* Create a new CommonAnnotationBeanPostProcessor,
* with the init and destroy annotation types set to
* {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy},
* respectively.
*/
public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);
setInitAnnotationType(PostConstruct.class);
setDestroyAnnotationType(PreDestroy.class);
ignoreResourceType("javax.xml.ws.WebServiceContext");
}
一切都清晰了吧。一言以蔽之,@PostConstruct注解后的方法在BeanPostProcessor前置處理器中就被執行了,所以當然要先於InitializingBean和init-method執行了。
最后,給出本文的結論,Bean在實例化的過程中:
Constructor > @PostConstruct > InitializingBean > init-method
spring怎么使用注解在初始化bean的時候init-method指定的方法
用的三種指定特定操作的方法:
通過實現InitializingBean/DisposableBean 接口來定制初始化之后/銷毀之前的操作方法;
通過<bean> 元素的 init-method/destroy-method屬性指定初始化之后 /銷毀之前調用的操作方法;
在指定方法上加上@PostConstruct或@PreDestroy注解來制定該方法是在初始化之后還是銷毀之前調用。