spring源码阅读之BeanPostProcessor

BeanPostProcessor 简介

该接口我们也叫后置处理器,作用是在Bean对象在实例化和依赖注入完毕后,在初始化方法的前后添加我们自己的逻辑。注意是Bean实例化完毕后及依赖注入完成后触发的。接口的源码如下
在这里插入图片描述
在这里插入图片描述

/**
 * BeanPostProcessor 是spring框架的通用的一个扩展点(不止一个)
 * 通过实现BeanPostProcessor接口,程序员就可以查收bean实例化过程,从而减轻beanFactory的负担
 * 值得说的是: 这个接口可以设置多个,会形成一个列表,然后依次执行,
 * (我们自己定义的类上面使用@Component,spring提供的都没有添加,所以spring使用的是set方式)
 * 比如aop就是在bean实例后期间将切面逻辑植入bean实例中的
 * aop也正是通过beanpostprocessor和ioc容器建立起了联系
 * (由spring提供的默认的PostPorcessor,spring提供了很多默认的PostProcessor,下面我们会一一介绍这些类的功能)
 * 可以来演示下BeanPosterProcessor的使用方式(把动态代理和ioc,aop结合起来使用)
 * 在演示之前先熟悉一下这个接口,其实这个接口非常简单
 * 但是他的实现类特别复杂
 * 可以看看spring提供哪些默认的实现
 */
public interface BeanPostProcessor {
	//初始化之前调用
	Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
	//初始化之后调用
	Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}

自定义BeanPostProcessor

@Component
public class TestBeanPostProcessor01 implements BeanPostProcessor, PriorityOrdered {
	/**
	 * 初始化之前调用
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println(beanName+this.getClass().getSimpleName());
		//这个bean必须返回,bean是从ioc中拿的,使用完必须返还,不然后面使用bean会包空指针
		return bean;
	}

	/**
	 * 初始化之后调用
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println(beanName+this.getClass().getSimpleName());
		//这个bean必须返回,bean是从ioc中拿的,使用完必须返还,不然后面使用bean会包空指针
		return bean;
	}

	@Override
	public int getOrder() {
		return 1;
	}
}

注意:接口中两个方法不能返回null,如果返回null那么在后续初始化方法将报空指针异常或者通过getBean()方法获取不到bena实例对象,因为后置处理器从Spring IoC容器中取出bean实例对象没有再次放回IoC容器中

我代码里面有多个类,我们就以UserDaoImpl为例

@Repository
public class UserDaoImpl implements UserDao {
	public UserDaoImpl() {
		System.out.println(this.getClass()+"构造方法");
	}

	@PostConstruct
	public void init(){
		System.out.println(this.getClass()+"初始化");
	}


	@Override
	public String query() {
		System.out.println("User Dao");
		return "userDao";
	}
}
public class TestUserDao {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext configApplicationContext =
				new AnnotationConfigApplicationContext(AppConfig.class);
		//configApplicationContext.register(UserDaoImpl.class);
		//configApplicationContext.refresh();
		UserDao bean = configApplicationContext.getBean(UserDaoImpl.class);
		bean.query();
	}
}

打印效果:
在这里插入图片描述
通过结果我们可以看出是UserDaoImpl实例化完成后,在进行初始化前后进行的

配置多个BeanPostProcessor如何保证顺序

我们可以添加多个BeanPostProcessor(后置处理器)接口实现类,在默认情况下Spring容器会根据后置处理器的定义顺序来依次调用。
比如我又添加了一个.如果保证他们的顺序,是需要继承PriorityOrdered这个接口来实现,根据getOrder返回值的大小来决定执行顺序,该方法返回一整数,默认值为 0,优先级最高,值越大优先级越低

@Component
public class TestBeanPostProcessor02 implements BeanPostProcessor, PriorityOrdered {
	/**
	 * 初始化之前调用
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println(beanName+this.getClass().getSimpleName());
		return bean;
	}

	/**
	 * 初始化之后调用
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println(beanName+this.getClass().getSimpleName());
		return bean;
	}

	@Override
	public int getOrder() {
		return 0;
	}
}

spring 内部是如何使用的

回到我们发现这个使用的地方再,我是按照下面的路线找到这个地方
在这里插入图片描述
ApplicationContextAwareProcessor是spring提供的BeanPostProcessor接口的实现类之一
我们从此至少可以有两个想法:
1.spring是使用beanFactory添加的这个后置处理器,我们是否可以使用此方法,而不适用@Component?
2.ApplicationContextAwareProcessor这个后置处理器是干什么的?

问题1:

BeanFactory和ApplicationContext两个容器对待bean的后置处理器稍微有些不同。ApplicationContext容器会自动检测Spring配置文件中那些bean所对应的Java类实现了BeanPostProcessor接口,并自动把它们注册为后置处理器。在创建bean过程中调用它们,所以部署一个后置处理器跟普通的bean没有什么太大区别。
BeanFactory容器注册bean后置处理器时必须通过代码显示的注册,在IoC容器继承体系中的ConfigurableBeanFactory接口中定义了注册方法

spring提供了哪些默认的BeanPostProcessor

这个地方我们不可能全部都写了,太多了,在看代码的时候遇到哪个写哪个吧

ApplicationContextAwareProcessor

主要是处理Aware类的信息
//添加一个后置管理器ApplicationContextAwareProcessor
//能够在bean中活动各种
Aware(*Aware都有其作用)

源码出处org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.EmbeddedValueResolver;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;

/**
 * {@link org.springframework.beans.factory.config.BeanPostProcessor}
 * implementation that passes the ApplicationContext to beans that
 * implement the {@link EnvironmentAware}, {@link EmbeddedValueResolverAware},
 * {@link ResourceLoaderAware}, {@link ApplicationEventPublisherAware},
 * {@link MessageSourceAware} and/or {@link ApplicationContextAware} interfaces.
 *
 * <p>Implemented interfaces are satisfied in order of their mention above.
 *
 * <p>Application contexts will automatically register this with their
 * underlying bean factory. Applications do not use this directly.
 *
 * @author Juergen Hoeller
 * @author Costin Leau
 * @author Chris Beams
 * @since 10.10.2003
 * @see org.springframework.context.EnvironmentAware
 * @see org.springframework.context.EmbeddedValueResolverAware
 * @see org.springframework.context.ResourceLoaderAware
 * @see org.springframework.context.ApplicationEventPublisherAware
 * @see org.springframework.context.MessageSourceAware
 * @see org.springframework.context.ApplicationContextAware
 * @see org.springframework.context.support.AbstractApplicationContext#refresh()
 */
//这个类没有使用public修饰,说明spring没有打算让外部使用
class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 * 使用给定的应用上下文创建一个ApplicationContextAwareProcessor实例,通常该方法
	 * 	 * 由应用上下文对象自己调用,比如在类AbstractApplicationContext中 :
	 * 	 * new ApplicationContextAwareProcessor(this)
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}

	/**
	 *继承BeanPostProcessor 在bean的初始化前调用
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return
	 * @throws BeansException
	 */

	@Override
	@Nullable
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		AccessControlContext acc = null;

		if (System.getSecurityManager() != null &&
				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
			// 检查bean上是否实现了某个Aware接口,有的话做相应调用
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

	/**
	 * 这个方法主要是是 对Bean 实现或者继承*Aware的类进行设置application相关信息
	 * 检查bean上是否实现了某个Aware接口,有的话做相应调用
	 * @param bean
	 */
	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EnvironmentAware) {
				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
			}
			if (bean instanceof EmbeddedValueResolverAware) {
				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
			}
			if (bean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
			}
			if (bean instanceof ApplicationEventPublisherAware) {
				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
			}
			if (bean instanceof MessageSourceAware) {
				((MessageSourceAware) bean).setMessageSource(this.applicationContext);
			}
			if (bean instanceof ApplicationContextAware) {
				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
			}
		}
	}

	/**
	 * 继承BeanPostProcessor 在bean的初始化后调用,这个地方没有做任何处理
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		return bean;
	}

}

ApplicationContextAwareProcessor是一个Spring内部工具,它实现了接口BeanPostProcessor,用于向实现了如下某种Aware接口的bean设置ApplicationContext中相应的属性:

  • EnvironmentAware
  • EmbeddedValueResolverAware
  • ResourceLoaderAware
  • ApplicationEventPublisherAware
  • MessageSourceAware
  • ApplicationContextAware
    如果bean实现了以上接口中的某几个,那么这些接口方法调用的先后顺序就是上面接口排列的先后顺序。

注意,ApplicationContextAwareProcessor自己会被应用程序上下文自动注册到bean容器,不需要应用开发人员操心

ApplicationListenerDetector

事件监听相关的后置处理器,将来再写一个专题吧

LoadTimeWeaverAwareProcessor

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值