一、InitializingBean接口说明
InitializingBean接口为bean提供了属性初始化后的处理方法,它只包括afterPropertiesSet方法,凡是继承该接口的类,在bean的属性初始化后都会执行该方法。
package org.springframework.beans.factory;
/**
* Interface to be implemented by beans that need to react once all their
* properties have been set by a BeanFactory: for example, to perform custom
* initialization, or merely to check that all mandatory properties have been set.
*
* <p>An alternative to implementing InitializingBean is specifying a custom
* init-method, for example in an XML bean definition.
* For a list of all bean lifecycle methods, see the BeanFactory javadocs.
*
* @author Rod Johnson
* @see BeanNameAware
* @see BeanFactoryAware
* @see BeanFactory
* @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
* @see org.springframework.context.ApplicationContextAware
*/
public interface InitializingBean {
/**
* Invoked by a BeanFactory after it has set all bean properties supplied
* (and satisfied BeanFactoryAware and ApplicationContextAware).
* <p>This method allows the bean instance to perform initialization only
* possible when all bean properties have been set and to throw an
* exception in the event of misconfiguration.
* @throws Exception in the event of misconfiguration (such
* as failure to set an essential property) or if initialization fails.
*/
void afterPropertiesSet() throws Exception;
}
二、源码分析接口应用
通过查看spring的加载bean的源码类(AbstractAutowireCapableBeanFactory)可以看到
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//判断该bean是否实现了实现了InitializingBean接口,如果实现了InitializingBean接口,则调用bean的afterPropertiesSet方法
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>() {
public Object run() throws Exception {
//调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
//判断是否指定了init-method方法,如果指定了init-method方法,则再调用制定的init-method
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//反射调用init-method方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
单实例bean案例
创建一个Animal的类实现InitializingBean和DisposableBean接口,代码如下:
package io.mykit.spring.plugins.register.bean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
/**
* @version 1.0.0
* @description 测试InitializingBean接口和DisposableBean接口
*/
public class Animal implements InitializingBean, DisposableBean {
public Animal(){
System.out.println("执行了Animal类的无参数构造方法");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行了Animal类的初始化方法。。。。。");
}
@Override
public void destroy() throws Exception {
System.out.println("执行了Animal类的销毁方法。。。。。");
}
}
接下来,我们新建一个AnimalConfig类,并将Animal通过@Bean注解的方式注册到Spring容器中,如下所示。
package io.mykit.spring.plugins.register.config;
import io.mykit.spring.plugins.register.bean.Animal;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @version 1.0.0
* @description AnimalConfig
*/
@Configuration
@ComponentScan("io.mykit.spring.plugins.register.bean")
public class AnimalConfig {
@Bean
public Animal animal(){
return new Animal();
}
}
接下来,我们在BeanLifeCircleTest类中新增testBeanLifeCircle02()方法来进行测试,如下所示。
@Test
public void testBeanLifeCircle02(){
//创建IOC容器
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
System.out.println("IOC容器创建完成...");
//关闭IOC容器
context.close();
}
运行BeanLifeCircleTest类中的testBeanLifeCircle02()方法,输出的结果信息如下所示。
执行了Animal类的无参数构造方法
执行了Animal类的初始化方法。。。。。
IOC容器创建完成...
执行了Animal类的销毁方法。。。。。
从输出的结果信息可以看出:单实例bean下,IOC容器创建完成后,会自动调用bean的初始化方法;而在容器销毁前,会自动调用bean的销毁方法。
多实例bean案例
多实例bean的案例代码基本与单实例bean的案例代码相同,只不过在AnimalConfig类中,我们在animal()方法上添加了@Scope(“prototype”)注解,如下所示。
package io.mykit.spring.plugins.register.config;
import io.mykit.spring.plugins.register.bean.Animal;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
/**
* @version 1.0.0
* @description AnimalConfig
*/
@Configuration
@ComponentScan("io.mykit.spring.plugins.register.bean")
public class AnimalConfig {
@Bean
@Scope("prototype")
public Animal animal(){
return new Animal();
}
}
接下来,我们在BeanLifeCircleTest类中新增testBeanLifeCircle03()方法来进行测试,如下所示。
@Test
public void testBeanLifeCircle03(){
//创建IOC容器
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AnimalConfig.class);
System.out.println("IOC容器创建完成...");
System.out.println("-------");
//调用时创建对象
Object bean = ctx.getBean("animal");
System.out.println("-------");
//调用时创建对象
Object bean1 = ctx.getBean("animal");
System.out.println("-------");
//关闭IOC容器
ctx.close();
}
运行BeanLifeCircleTest类中的testBeanLifeCircle03()方法,输出的结果信息如下所示。
IOC容器创建完成...
-------
执行了Animal类的无参数构造方法
执行了Animal类的初始化方法。。。。。
-------
执行了Animal类的无参数构造方法
执行了Animal类的初始化方法。。。。。
-------
分析代码可以了解:
1:spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用
2:实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖
3:如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法
三、扩展
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:
- 通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
- 通过 元素的 init-method/destroy-method 属性指定初始化之后 /销毁之前调用的操作方法;
- 在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。
spring bean的初始化执行顺序:构造方法 --> @PostConstruct注解的方法 --> afterPropertiesSet方法 --> init-method指定的方法。具体可以参考例子
afterPropertiesSet通过接口实现方式调用(效率上高一点),@PostConstruct和init-method都是通过反射机制调用
四、特别感谢:
https://www.cnblogs.com/binghe001/p/13174687.html
https://segmentfault.com/a/1190000014105687
https://segmentfault.com/a/1190000012461362