1.bean的生命周期:
![](https://i-blog.csdnimg.cn/blog_migrate/69e425cb690c9545079f820e8df33977.png)
2.Bean的定义
Bean 是 spring 装配的组件模型,一切实体类都可以配置成一个 Bean ,进而就可以在任何其他的 Bean 中使用,一个 Bean 也可以不是指定的实体类,这就是抽象 Bean 。
3.bean生命周期示例
创建一个实体类,里面定义好构造函数、初始化方法和销毁方法。
package com.yanling.bean;
public class Car {
public Car() {
System.out.println("car ..... constructor....");
}
public void init() {
System.out.println("car.....init....");
}
public void destroy() {
System.out.println("car.....destroy....");
}
}
创建一个后置处理器,自定义后置处理器的两个工作方法。
package com.yanling.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
/**
* 后置处理器:在初始化前后工作
* @author 16437
*
*/
@Component
public class MyBeanPostProcessor implements BeanPostProcessor{
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 在初始化前工作
System.out.println("postProcessBeforeInitialization:"+beanName+"=>"+bean);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 在初始化后工作
System.out.println("postProcessAfterInitialization:"+beanName+"=>"+bean);
return bean;
}
}
创建一个Config.java类,用来做配置类。
package com.yanling.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.yanling.bean.Car;
@Configuration//声明该类是配置类
public class Config {
//创建bean(Spring默认是单实例)
//由于多实例的时,容器不管理bean的销毁,所以这里就用单实例来做示例
@Bean(initMethod="init", destroyMethod="destroy")
public Car car () {
return new Car();
}
}
测试
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
System.out.println("容器创建完成。。。。。。。。。。");
applicationContext.close();
}
4.部分源码解析
通过构造器创建bean实例,下面是AbstractBeanFactory类的doGetBean方法部分代码。
AbstractBeanFactory.doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
//校验要初始化的Bean以来的bean是否都初始化完成
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
getBean(dep);
}
}
// 创建实例bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
/**
* 从单例缓存中显式删除可能存在的实例,同时删除任何接收到bean临时引用的bean。
*/
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// 声明一个对象用于接收要创建的实例
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
//创建实例
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
//创建实例
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
初始化bena,下面是AbstractAutowireCapableBeanFactory类的doCreateBean方法部分代码,代码中可以看出在初始化之前会先对创建的bean进行赋值。
AbstractAutowireCapableBeanFactory.doCreateBean (final String beanName, final RootBeanDefinition mbd, final Object[] args)
Object exposedObject = bean;
try {
//在初始化之前先赋值
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 初始化bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
我们就进入到 initializeBean(beanName, exposedObject, mbd)初始化方法中查看初始化方法,在代码中可以看到通过反射调用自定义初始化化方法前后都会调用后置器,从而实现在bean在初始化前后进行一些处理工作。
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//在初始化之前调用bean的处理器
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//初始化bean
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()) {
//在初始化之后调用bean的处理器
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
最后是通调取close()方法来销毁bean。
DefaultSingletonBeanRegistry.destroyBean(String beanName, DisposableBean bean)
// 调用销毁方法
if (bean != null) {
try {
bean.destroy();
}
catch (Throwable ex) {
logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
}
}
public Object invoke(Object obj, Object... args)throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
MethodAccessor ma = methodAccessor;
if (ma == null) {
ma = acquireMethodAccessor();
}
//通过反射调用自定义销毁方法
return ma.invoke(obj, args);
}