spring初始化bean时执行某些方法完成特定的初始化操作
在項目中經(jīng)常會在容器啟動時,完成特定的初始化操作,如資源文件的加載等。
一 實現(xiàn)的方式有三種:
1.使用@PostConstruct注解,該注解作用于void方法上
2.在配置文件中配置init-method方法
<bean id="student" class="com.demo.spring.entity.Student" init-method="init2"><property name="name" value="景甜"></property><property name="age" value="28"></property><property name="school" ref="school"></property> </bean>3.將類實現(xiàn)InitializingBean接口
package com.demo.spring.entity;import javax.annotation.PostConstruct;import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component;/*** @author chenyk* @date 2018年5月8日*/ @Component("student") public class Student implements InitializingBean{private String name;private int age;private School school;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public School getSchool() {return school;}public void setSchool(School school) {this.school = school;}//1.使用postconstrtct注解 @PostConstructpublic void init(){System.out.println("執(zhí)行 init方法");}//2.在xml配置文件中配置init-method方法public void init2(){System.out.println("執(zhí)行init2方法 ");}//3.實現(xiàn)InitializingBean接口public void afterPropertiesSet() throws Exception {System.out.println("執(zhí)行init3方法");}}執(zhí)行結(jié)果:
執(zhí)行 init方法
2018-06-11 10:09:16,195 DEBUG [AbstractAutowireCapableBeanFactory.java:1671] : Invoking afterPropertiesSet() on bean with name 'student'
執(zhí)行init3方法
2018-06-11 10:09:36,459 DEBUG [AbstractAutowireCapableBeanFactory.java:1731] : Invoking init method 'init2' on bean with name 'student'
執(zhí)行init2 方法
二 實現(xiàn)原理:
由以上執(zhí)行結(jié)果可知:先執(zhí)行@PostConstruct注解的方法,然后是實現(xiàn)了InitializingBean接口的afterPropertiesSet方法,最后執(zhí)行在配置文件中配置的init-method方法。至于為什么是這個順序,可以看源碼:
在?AbstractAutowireCapableBeanFactory 類中
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {if (System.getSecurityManager() != null) {AccessController.doPrivileged(new PrivilegedAction<Object>() {@Overridepublic Object run() {invokeAwareMethods(beanName, bean);return null;}}, getAccessControlContext());}else {invokeAwareMethods(beanName, bean);}Object wrappedBean = bean;if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);}try {//調(diào)用初始化方法invokeInitMethods(beanName, wrappedBean, mbd);}catch (Throwable ex) {throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),beanName, "Invocation of init method failed", ex);}if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;}
然后進(jìn)入到?invokeInitMethods 方法中?
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>() {@Overridepublic Object run() throws Exception {((InitializingBean) bean).afterPropertiesSet();return null;}}, getAccessControlContext());}catch (PrivilegedActionException pae) {throw pae.getException();}}else {//直接調(diào)用 InitializingBean 接口中的 afterPropertiesSet 方法((InitializingBean) bean).afterPropertiesSet();}}if (mbd != null) {String initMethodName = mbd.getInitMethodName();if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&!mbd.isExternallyManagedInitMethod(initMethodName)) {
//進(jìn)入該方法可知通過反射的方式調(diào)用init-method方法invokeCustomInitMethod(beanName, bean, mbd);}}}
所以,初始化方法的執(zhí)行順序?afterPropertiesSet() > init-method()
博客園的第一篇文章。感覺博客園很干凈,文章排版特別是插入代碼格式看起來很舒服。就不吐槽csdn了。
轉(zhuǎn)載于:https://www.cnblogs.com/51life/p/9166009.html
總結(jié)
以上是生活随笔為你收集整理的spring初始化bean时执行某些方法完成特定的初始化操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UserWarning: Matplot
- 下一篇: pyinstaller打包执行exe出现