Spring中的InitializingBean接口的使用
转自: https://www.cnblogs.com/weiqihome/p/8922937.html
Tip:
1、Spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法。
或者在配置文件中通过init-method指定,两种方式可以同时使用。
所以会发现当配置文件当一个bean没有通过init-method指定初始化方法时,会发现,各个bean中都实现了InitializingBean接口。
比如:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
等等。
2、如果同时使用,会先调用afterPropertieSet()方法,然后再调用init-method中指定的方法。
3、实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率要高一点,但是init-method方式消除了对spring的依赖。
4、如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。
测试如下:
package com.muna.InitializingBean; import org.springframework.beans.factory.InitializingBean; /** * @ClassName TestInitializingBean * @Description TODO * @Author * @Date 2018/12/4 15:39 * @Version 1.0 **/ public class TestInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("ceshi InitializingBean"); } public void testInit(){ System.out.println("ceshi init-method"); } }
xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--<bean id="testInitializingBean" class="com.muna.InitializingBean.TestInitializingBean"/>--> <bean id="testInitializingBean" class="com.muna.InitializingBean.TestInitializingBean" init-method="testInit"/> </beans>
Main方法
package com.muna.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* @ClassName Main
* @Description 测试InitializingBean接口
* @Author
* @Date 2018/12/4 15:41
* @Version 1.0
**/
public class Main {
public static void main(String[] args){
ApplicationContext context = new FileSystemXmlApplicationContext("/src/test/java/com/muna/InitializingBean/beans.xml");
}
}
当:
<bean id="testInitializingBean" class="com.muna.InitializingBean.TestInitializingBean"/>
结果为:
16:05:40.499 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'testInitializingBean'
ceshi InitializingBean
当:
<bean id="testInitializingBean" class="com.muna.InitializingBean.TestInitializingBean" init-method="testInit"/>
结果为:
16:05:11.153 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'testInitializingBean'
ceshi InitializingBean
16:05:11.154 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking init method 'testInit' on bean with name 'testInitializingBean'
ceshi init-method
从结果可以看出,在Spring初始化bean的时候,如果该bean实现了InitializingBean接口,并且同时在配置文件中指定了init-method,系统则是先调用afterPropertieSet()方法,然后再调用init-method中指定的方法。
源码:AbstractAutowiredCapableBeanFactory类中的invokeInitMethods
protected void invokeInitMethods(String beanName, final Object bean, @Nullable 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((PrivilegedExceptionAction<Object>) () -> { ((InitializingBean) bean).afterPropertiesSet(); return null; }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.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)) {
invokeCustomInitMethod(beanName, bean, mbd); } } }