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
    评论
### 回答1: BeanPostProcessorSpring框架中的一个接口,它允许开发人员在bean实例化和依赖注入之后对bean进行自定义处理。BeanPostProcessor接口有两个方法:postProcessBeforeInitialization和postProcessAfterInitialization。这两个方法分别在bean实例化之后和依赖注入之后被调用。 BeanPostProcessor源码解析可以从以下几个方面入手: 1. BeanPostProcessor的实现类 Spring框架中有很多实现了BeanPostProcessor接口的类,比如AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor等。这些类都是用来处理bean的,可以通过查看它们的源码来了解BeanPostProcessor的具体实现。 2. postProcessBeforeInitialization方法 postProcessBeforeInitialization方法在bean实例化之后、依赖注入之前被调用。这个方法可以用来修改bean的属性或者执行一些初始化操作。在源码中可以看到,postProcessBeforeInitialization方法的实现类似于以下代码: public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // 执行一些初始化操作 return bean; } 3. postProcessAfterInitialization方法 postProcessAfterInitialization方法在bean实例化和依赖注入之后被调用。这个方法可以用来对bean进行一些后处理操作。在源码中可以看到,postProcessAfterInitialization方法的实现类似于以下代码: public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // 对bean进行一些后处理操作 return bean; } 4. BeanPostProcessor的执行顺序 在Spring框架中,BeanPostProcessor的执行顺序是固定的。首先会执行所有实现了PriorityOrdered接口的BeanPostProcessorpostProcessBeforeInitialization方法,然后执行所有实现了Ordered接口的BeanPostProcessorpostProcessBeforeInitialization方法,最后执行所有其他的BeanPostProcessorpostProcessBeforeInitialization方法。在执行postProcessAfterInitialization方法时,执行顺序与执行postProcessBeforeInitialization方法时相同。 总之,BeanPostProcessorSpring框架中非常重要的一个接口,它允许开发人员对bean进行自定义处理。通过对BeanPostProcessor源码的分析,我们可以更好地理解它的实现原理和使用方法。 ### 回答2: BeanPostProcessorSpring框架的一个非常重要的组件。它可以在Bean的创建周期中对Bean进行一些处理,它提供了在初始化Bean之前和之后执行自定义逻辑的机会。本文将深入剖析BeanPostProcessor源码实现及其作用。 1. BeanPostProcessor的接口: BeanPostProcessor是一个接口,定义了两个方法: (1)postProcessBeforeInitialization(Object bean, String beanName): 在初始化之前对Bean做一些操作。 (2)postProcessAfterInitialization(Object bean, String beanName): 在初始化之后对Bean做一些操作。 2. BeanPostProcessor源码实现: 它是一个接口,BeanPostProcessor是一个在SpringBean加载过程中非常重要的组件,它主要负责Bean的实例化、属性赋值和初始化过程中提供额外的自定义处理逻辑。 BeanPostProcessor接口的定义如下: public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; } 在Spring IoC容器中,BeanPostProcessor的主要作用是在Bean实例化、属性赋值和初始化过程中提供额外的自定义处理逻辑。在创建Bean实例之后,Spring容器会遍历所有注册的BeanPostProcessor,调用它们的postProcessBeforeInitialization和postProcessAfterInitialization方法。 3. BeanPostProcessor的应用: (1)扩展Bean生命周期: 可以通过实现BeanPostProcessor接口来自定义对一个或者所有的Bean的初始化过程,可以在初始化之前或之后执行额外的逻辑。 (2)实现依赖注入: 可以通过实现BeanPostProcessor接口,来实现依赖注入。例如可以通过注解的方式,来实现自动为所有Bean中标注了特定注解的属性注入值。 (3)实现AOP: 可以通过Spring的AOP机制来实现AOP,而BeanPostProcessor是实现AOP的重要底层组件之一。 总之,BeanPostProcessorSpring框架中非常重要的一个组件,它提供了对Bean创建周期中的两个关键事件——初始化之前和初始化之后进行处理的机会。使用BeanPostProcessor可以实现很多功能,如扩展Bean的生命周期、实现依赖注入、实现AOP等,对于自定义框架和组件开发来说,非常有用。 ### 回答3: BeanPostProcessorSpring 框架中的一个扩展点,它允许我们在一个 bean 被实例化时或者在 bean 的初始化过程中修改 bean 的一些属性或者执行一些操作。本文将在源码层面上对 BeanPostProcessor 进行详细解析。 首先,我们需要了解 BeanPostProcessor 接口的定义: ```java public interface BeanPostProcessor { /** * 在 bean 的初始化之前执行,返回一个代理对象用来替换原始的 bean 对象。 * 在 Spring 内部,Spring 会在这个方法被调用时对当前 bean 对象进行代理, * 然后交给后续的 bean 处理流程处理。 * * @param bean 待初始化的 bean 对象 * @param beanName 当前 bean 对象的名称 * @return 可以替代原始 bean 对象的代理对象 * @throws BeansException 如果出现任何异常,将导致 bean 的初始化过程被中断。 */ @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * 在 bean 的初始化之后执行。这个方法在最终返回 bean 对象之前调用, * 因此在这里面进行的任何操作都可以生效,包括修改 bean 对象的属性值等等。 * * @param bean 待初始化的 bean 对象 * @param beanName 当前 bean 对象的名称 * @return 可以替代原始 bean 对象的代理对象 * @throws BeansException 如果出现任何异常,将导致 bean 的初始化过程被中断。 */ @Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } } ``` 可以看到,BeanPostProcessor 接口中只定义了两个方法,分别在 bean 实例化前后执行。这两个方法都有一个相同的传参,即需要处理的 bean 和这个 bean 的名称。 然后我们看看 Spring 框架是如何调用 BeanPostProcessor 的实现类的。在 AbstractAutowireCapableBeanFactory 类中,有一个名为 applyBeanPostProcessorsAfterInitialization 的方法: ```java protected Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; // 遍历所有的 BeanPostProcessor 实现类,依次执行 postProcessAfterInitialization 方法 for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; } ``` 在这个方法中,Spring 会遍历所有的 BeanPostProcessor 实现类,依次调用 postProcessAfterInitialization 方法,返回代理对象。如果最终的代理对象返回 null,那么就会返回原始 bean 对象。这样保证了 BeanPostProcessor 的后续执行不会受到任何异常的干扰。 在 AbstractAutowireCapableBeanFactory 中还有一个方法 applyBeanPostProcessorsBeforeInitialization,其代码结构与 applyBeanPostProcessorsAfterInitialization 类似,不再赘述。 除了上述方法,AbstractAutowireCapableBeanFactory 类还有一个名为 getBeanPostProcessors 的方法。这个方法返回 Spring 容器内所有的 BeanPostProcessor 实现类,它们会依次被调用。 ```java protected List<BeanPostProcessor> getBeanPostProcessors() { List<BeanPostProcessor> processors = new ArrayList<>(); // 往集合里添加 BeanPostProcessor 实现类 processors.addAll(beanFactory.getBeansOfType(BeanPostProcessor.class, true, false).values()); // 往集合里添加 SmartInstantiationAwareBeanPostProcessor 实现类 processors.addAll(beanFactory.getBeansOfType(SmartInstantiationAwareBeanPostProcessor.class, true, false).values()); return processors; } ``` 可以看到,getBeanPostProcessors 方法主要作用是将 Spring 容器内所有的 BeanPostProcessor 实现类添加到一个 List 集合里,并返回这个集合。 至此,我们从源码层面上对 BeanPostProcessor 接口进行了详细的解析。相信完这篇文档,你对 BeanPostProcessor 接口的作用以及 Spring 框架是如何使用它进行初始化 bean 过程中的各种扩展操作有了更深层次的理解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值