Spring BeanPostProcessor源码详解(详细注释版)
1. BeanPostProcessor接口源码
/*
* BeanPostProcessor接口是Spring框架中最重要的扩展点之一
* 允许在Bean实例化后、初始化前后对Bean进行自定义处理
* 是Spring AOP、@Autowired、@Value等注解实现的基础
*
* BeanPostProcessor的作用:
* 1. 在Bean初始化前后执行自定义逻辑
* 2. 修改Bean实例或替换Bean实例
* 3. 实现各种注解的处理(如@Autowired、@Value等)
* 4. 实现AOP代理
* 5. 实现Bean的包装和增强
*
* 注意事项:
* - BeanPostProcessor会影响所有Bean的创建过程
* - 实现类应该声明为@Component或通过配置注册
* - 避免在BeanPostProcessor中进行复杂的业务逻辑处理
*/
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
/**
* 工厂钩子,允许自定义修改新的Bean实例
*
* BeanPostProcessor的执行时机:
* 1. Bean实例化完成
* 2. 属性注入完成
* 3. Aware接口方法调用完成
* 4. postProcessBeforeInitialization调用
* 5. InitializingBean.afterPropertiesSet()调用
* 6. 自定义init-method调用
* 7. postProcessAfterInitialization调用
* 8. Bean可以正常使用
*
* 两种回调方法:
* - postProcessBeforeInitialization: 在初始化之前调用
* - postProcessAfterInitialization: 在初始化之后调用
*
* 返回值说明:
* - 可以返回原始Bean实例
* - 可以返回包装后的Bean实例(代理模式)
* - 如果返回null会导致NullPointerException
*/
public interface BeanPostProcessor {
/**
* 在任何Bean初始化回调(如InitializingBean的afterPropertiesSet或自定义init-method)
* 之前应用此BeanPostProcessor到给定的新Bean实例
*
* 此回调将在以下方法之后、任何其他初始化回调之前调用:
* - Bean实例化
* - 属性注入
* - Aware接口方法调用
*
* @param bean 新的Bean实例
* @param beanName Bean的名称
* @return 要使用的Bean实例,可能是原始实例或包装后的实例
* @throws BeansException 如果处理过程中发生错误
*
* 使用场景:
* - 检查Bean的类型并进行特殊处理
* - 包装Bean实例(如AOP代理)
* - 修改Bean的属性值
* - 记录Bean初始化日志
*/
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* 在Bean初始化回调(如InitializingBean的afterPropertiesSet或自定义init-method)
* 之后应用此BeanPostProcessor到给定的新Bean实例
*
* 此回调将在以下方法之后调用:
* - InitializingBean.afterPropertiesSet()
* - 自定义init-method
*
* @param bean 新的Bean实例
* @param beanName Bean的名称
* @return 要使用的Bean实例,可能是原始实例或包装后的实例
* @throws BeansException 如果处理过程中发生错误
*
* 使用场景:
* - 创建Bean的代理对象(AOP)
* - 对Bean进行最终的配置和验证
* - 注册Bean到其他系统
* - 缓存Bean实例
*/
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
2. DestructionAwareBeanPostProcessor接口
/*
* DestructionAwareBeanPostProcessor接口扩展了BeanPostProcessor
* 提供了Bean销毁时的回调方法
* 主要用于需要在Bean销毁时执行特殊处理的场景
*/
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
/**
* 在BeanFactory销毁给定Bean实例之前应用此BeanPostProcessor
*
* 此方法在以下情况下调用:
* - Bean实现DisposableBean接口时
* - Bean有自定义destroy-method时
* - Web应用关闭时
*
* @param bean 要销毁的Bean实例
* @param beanName Bean的名称
* @throws BeansException 如果处理过程中发生错误
*
* 使用场景:
* - 清理BeanPostProcessor创建的资源
* - 取消Bean的注册
* - 记录Bean销毁日志
* - 执行特殊的清理逻辑
*/
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;
/**
* 确定给定的Bean实例是否需要由此BeanPostProcessor进行销毁回调处理
*
* @param bean Bean实例
* @return 如果需要销毁处理返回true
*/
default boolean requiresDestruction(Object bean) {
return true;
}
}
3. InstantiationAwareBeanPostProcessor接口
/*
* InstantiationAwareBeanPostProcessor接口扩展了BeanPostProcessor
* 提供了Bean实例化过程中的回调方法
* 允许在Bean实例化前后进行干预
*/
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
/**
* 在目标Bean被实例化之前应用此BeanPostProcessor
*
* 此方法在以下情况下调用:
* - Bean实例化之前
* - 可以返回一个代理对象来替代实际的Bean实例化
*
* @param beanClass 要实例化的Bean的类
* @param beanName Bean的名称
* @return 要使用的Bean实例,如果返回null则继续正常的实例化过程
* @throws BeansException 如果处理过程中发生错误
*
* 使用场景:
* - 返回代理对象(如AOP代理)
* - 阻止Bean的实例化
* - 提供特殊的Bean实例
*/
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
/**
* 在目标Bean被实例化之后应用此BeanPostProcessor
*
* 此方法在以下情况下调用:
* - Bean实例化之后
* - 属性注入之前
*
* @param bean 已经实例化的Bean实例
* @param beanName Bean的名称
* @return 如果应该继续使用属性填充和后续的初始化过程返回true,否则返回false
* @throws BeansException 如果处理过程中发生错误
*
* 使用场景:
* - 跳过属性填充过程
* - 对实例化后的Bean进行特殊处理
*/
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
/**
* 在工厂将给定的属性值应用到给定的Bean之前,对它们进行后处理
*
* 此方法在以下情况下调用:
* - 属性注入之前
* - 可以修改属性值
*
* @param pvs 要应用到Bean的属性值
* @param bw 包装Bean的BeanWrapper
* @param beanClass 目标Bean的类
* @param beanName Bean的名称
* @return 要应用到Bean的属性值(永远不要为null)
* @throws BeansException 如果处理过程中发生错误
*
* 使用场景:
* - 修改属性值
* - 添加额外的属性
* - 过滤属性值
*/
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return pvs;
}
/**
* 已废弃的方法,使用postProcessProperties替代
*/
@Deprecated
@Nullable
default PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return pvs;
}
}
4. SmartInstantiationAwareBeanPostProcessor接口
/*
* SmartInstantiationAwareBeanPostProcessor接口扩展了InstantiationAwareBeanPostProcessor
* 提供了更智能的实例化感知能力
*/
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
/**
* 预测Bean的类型
*
* @param beanClass 原始Bean类
* @param beanName Bean的名称
* @return 预测的Bean类型
* @throws BeansException 如果处理过程中发生错误
*/
@Nullable
default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
/**
* 确定用于给定Bean的候选构造函数
*
* @param beanClass Bean的类
* @param beanName Bean的名称
* @return 候选构造函数数组
* @throws BeansException 如果处理过程中发生错误
*/
@Nullable
default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
throws BeansException {
return null;
}
/**
* 获取对指定Bean的早期访问的引用,通常是为了解决循环引用
*
* @param bean 原始Bean实例
* @param beanName Bean的名称
* @return 要暴露给其他Bean的Bean实例
* @throws BeansException 如果处理过程中发生错误
*/
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return bean;
}
}
5. AbstractAutowireCapableBeanFactory中BeanPostProcessor的处理
/*
* AbstractAutowireCapableBeanFactory中BeanPostProcessor的核心处理逻辑
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
/**
* 初始化Bean的核心方法
* 包含BeanPostProcessor的调用
*
* @param beanName Bean名称
* @param bean Bean实例
* @param mbd 合并的Bean定义
* @return 初始化完成的Bean实例
* @throws BeansException 如果初始化过程中发生错误
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 调用Aware接口相关方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 应用BeanPostProcessor的前置处理方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 调用初始化方法
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()) {
// 应用BeanPostProcessor的后置处理方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
/**
* 应用BeanPostProcessor的前置处理方法
* 在Bean初始化之前调用
*
* @param existingBean 现有的Bean实例
* @param beanName Bean名称
* @return 处理后的Bean实例
* @throws BeansException 如果处理过程中发生错误
*/
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 遍历所有注册的BeanPostProcessor
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
/**
* 应用BeanPostProcessor的后置处理方法
* 在Bean初始化之后调用
*
* @param existingBean 现有的Bean实例
* @param beanName Bean名称
* @return 处理后的Bean实例
* @throws BeansException 如果处理过程中发生错误
*/
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 遍历所有注册的BeanPostProcessor
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
/**
* 解析构造函数参数并创建Bean实例
* 包含InstantiationAwareBeanPostProcessor的处理
*
* @param mbd Bean定义
* @param beanName Bean名称
* @param typesToMatch 要匹配的类型
* @return 解析后的构造函数参数
*/
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
// 遍历InstantiationAwareBeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 确定候选构造函数
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
/**
* 实例化Bean之前调用InstantiationAwareBeanPostProcessor
*
* @param bd Bean定义
* @param beanName Bean名称
* @param beanClass Bean类
* @return 如果返回非null则使用返回的实例,否则继续正常实例化
*/
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition bd) {
Object bean = null;
if (!Boolean.FALSE.equals(bd.beforeInstantiationResolved)) {
// 确保Bean类型已经解析
if (!bd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, bd);
if (targetType != null) {
// 应用前置实例化处理
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 应用后置初始化处理
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
bd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
/**
* 应用BeanPostProcessor的前置实例化处理
*
* @param beanClass Bean类
* @param beanName Bean名称
* @return 处理后的Bean实例或null
*/
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
// 遍历InstantiationAwareBeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 调用前置实例化方法
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
/**
* 应用BeanPostProcessor的属性处理
*
* @param pvs 属性值
* @param bw BeanWrapper
* @param beanClass Bean类
* @param beanName Bean名称
* @return 处理后的属性值
*/
@Nullable
protected PropertyValues applyBeanPostProcessorsAfterInstantiation(Object bean, String beanName) {
PropertyValues pvs = null;
// 遍历InstantiationAwareBeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 调用后置实例化方法
if (!ibp.postProcessAfterInstantiation(bean, beanName)) {
return null;
}
}
}
return pvs;
}
/**
* 应用BeanPostProcessor的属性值处理
*
* @param pvs 属性值
* @param bean Bean实例
* @param beanName Bean名称
* @return 处理后的属性值
*/
protected PropertyValues applyBeanPostProcessorsBeforeInitialization(
PropertyValues pvs, Object bean, String beanName) {
// 遍历InstantiationAwareBeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 调用属性处理方法
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bean, beanName);
if (pvsToUse == null) {
return null;
}
pvs = pvsToUse;
}
}
return pvs;
}
}
6. 常见的BeanPostProcessor实现
/*
* Spring框架中常见的BeanPostProcessor实现
*/
/**
* AutowiredAnnotationBeanPostProcessor
* 处理@Autowired和@Value注解
*/
public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
// 要处理的注解类型
private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet<>();
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
/**
* 在Bean初始化后处理@Autowired注解
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 注入@Autowired和@Value注解的字段和方法
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), null);
try {
metadata.inject(bean, beanName, null);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return bean;
}
/**
* 查找自动装配元数据
*/
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// 省略具体实现...
return new InjectionMetadata(clazz, new ArrayList<>());
}
}
/**
* CommonAnnotationBeanPostProcessor
* 处理JSR-250注解(如@PostConstruct、@PreDestroy、@Resource等)
*/
public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);
}
/**
* 处理@Resource注解
*/
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// 处理@Resource注解的字段和方法
InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
}
return pvs;
}
}
/**
* ApplicationContextAwareProcessor
* 处理各种Aware接口
*/
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* 在Bean初始化前处理Aware接口
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}
AccessControlContext acc = null;
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
/**
* 调用各种Aware接口方法
*/
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.applicationContext.getBeanFactory());
}
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);
}
}
}
/**
* ApplicationListenerDetector
* 检测并注册ApplicationListener
*/
class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor {
private final AbstractApplicationContext applicationContext;
public ApplicationListenerDetector(AbstractApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* 在Bean初始化后检测ApplicationListener
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
// 将ApplicationListener注册到ApplicationContext
Boolean flag = this.applicationContext.getSingleton(beanName);
if (Boolean.TRUE.equals(flag)) {
// singleton bean
this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
}
else if (flag == null) {
// prototype bean
this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
}
}
return bean;
}
/**
* 在Bean销毁前移除ApplicationListener
*/
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
try {
ApplicationEventMulticaster multicaster = this.applicationContext.getApplicationEventMulticaster();
multicaster.removeApplicationListener((ApplicationListener<?>) bean);
}
catch (IllegalStateException ex) {
// ApplicationEventMulticaster not initialized yet - no need to remove
}
}
}
@Override
public boolean requiresDestruction(Object bean) {
return (bean instanceof ApplicationListener);
}
}
7. 自定义BeanPostProcessor示例
/*
* 自定义BeanPostProcessor实现示例
*/
/**
* 性能监控BeanPostProcessor
* 为Bean添加性能监控功能
*/
@Component
public class PerformanceMonitorBeanPostProcessor implements BeanPostProcessor {
private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorBeanPostProcessor.class);
/**
* 在Bean初始化前创建代理
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 可以在这里进行一些预处理
return bean;
}
/**
* 在Bean初始化后创建性能监控代理
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 为特定类型的Bean创建性能监控代理
if (shouldMonitor(bean)) {
return createPerformanceProxy(bean, beanName);
}
return bean;
}
/**
* 判断是否需要监控
*/
private boolean shouldMonitor(Object bean) {
// 监控所有Service层的Bean
return bean.getClass().getName().contains("service") ||
bean.getClass().isAnnotationPresent(Service.class);
}
/**
* 创建性能监控代理
*/
private Object createPerformanceProxy(Object target, String beanName) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new PerformanceInvocationHandler(target, beanName)
);
}
/**
* 性能监控调用处理器
*/
private static class PerformanceInvocationHandler implements InvocationHandler {
private final Object target;
private final String beanName;
public PerformanceInvocationHandler(Object target, String beanName) {
this.target = target;
this.beanName = beanName;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long startTime = System.currentTimeMillis();
try {
// 执行目标方法
Object result = method.invoke(target, args);
return result;
} finally {
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
// 记录性能日志
logger.info("Bean '{}' method '{}' executed in {} ms",
beanName, method.getName(), executionTime);
}
}
}
}
/**
* 配置验证BeanPostProcessor
* 验证Bean的配置是否正确
*/
@Component
public class ConfigurationValidationBeanPostProcessor implements BeanPostProcessor {
private static final Logger logger = LoggerFactory.getLogger(ConfigurationValidationBeanPostProcessor.class);
/**
* 在Bean初始化前进行配置验证
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
validateBeanConfiguration(bean, beanName);
return bean;
}
/**
* 验证Bean配置
*/
private void validateBeanConfiguration(Object bean, String beanName) {
// 获取Bean的所有字段
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
// 检查@NotNull注解
if (field.isAnnotationPresent(NotNull.class)) {
field.setAccessible(true);
try {
Object value = field.get(bean);
if (value == null) {
throw new IllegalStateException(
String.format("Bean '%s' field '%s' cannot be null",
beanName, field.getName()));
}
} catch (IllegalAccessException e) {
logger.warn("Cannot access field {} of bean {}", field.getName(), beanName);
}
}
// 检查@Min注解
if (field.isAnnotationPresent(Min.class)) {
Min minAnnotation = field.getAnnotation(Min.class);
long minValue = minAnnotation.value();
field.setAccessible(true);
try {
Object value = field.get(bean);
if (value instanceof Number) {
long actualValue = ((Number) value).longValue();
if (actualValue < minValue) {
throw new IllegalStateException(
String.format("Bean '%s' field '%s' value %d is less than minimum %d",
beanName, field.getName(), actualValue, minValue));
}
}
} catch (IllegalAccessException e) {
logger.warn("Cannot access field {} of bean {}", field.getName(), beanName);
}
}
}
}
}
/**
* 日志增强BeanPostProcessor
* 为Bean添加日志功能
*/
@Component
public class LoggingBeanPostProcessor implements BeanPostProcessor {
private static final Logger logger = LoggerFactory.getLogger(LoggingBeanPostProcessor.class);
/**
* 在Bean初始化后添加日志功能
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 为带有@Logged注解的Bean创建日志代理
if (bean.getClass().isAnnotationPresent(Logged.class)) {
return createLoggingProxy(bean, beanName);
}
return bean;
}
/**
* 创建日志代理
*/
private Object createLoggingProxy(Object target, String beanName) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new LoggingInvocationHandler(target, beanName)
);
}
/**
* 日志调用处理器
*/
private static class LoggingInvocationHandler implements InvocationHandler {
private final Object target;
private final String beanName;
public LoggingInvocationHandler(Object target, String beanName) {
this.target = target;
this.beanName = beanName;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 检查方法是否有@Logged注解
Logged methodLogged = method.getAnnotation(Logged.class);
if (methodLogged != null) {
logger.info("Calling method {} of bean {} with args: {}",
method.getName(), beanName, Arrays.toString(args));
}
try {
Object result = method.invoke(target, args);
if (methodLogged != null) {
logger.info("Method {} of bean {} returned: {}",
method.getName(), beanName, result);
}
return result;
} catch (Exception e) {
if (methodLogged != null) {
logger.error("Method {} of bean {} threw exception: {}",
method.getName(), beanName, e.getMessage(), e);
}
throw e;
}
}
}
/**
* 自定义注解,标记需要日志记录的类或方法
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Logged {
}
}
/**
* 缓存增强BeanPostProcessor
* 为Bean添加缓存功能
*/
@Component
public class CacheBeanPostProcessor implements BeanPostProcessor {
private final Map<String, Object> cache = new ConcurrentHashMap<>();
/**
* 在Bean初始化后添加缓存功能
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 为带有@Cacheable注解的Bean创建缓存代理
if (hasCacheableMethods(bean)) {
return createCacheProxy(bean, beanName);
}
return bean;
}
/**
* 检查Bean是否有可缓存的方法
*/
private boolean hasCacheableMethods(Object bean) {
Method[] methods = bean.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Cacheable.class)) {
return true;
}
}
return false;
}
/**
* 创建缓存代理
*/
private Object createCacheProxy(Object target, String beanName) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new CacheInvocationHandler(target, beanName, cache)
);
}
/**
* 缓存调用处理器
*/
private static class CacheInvocationHandler implements InvocationHandler {
private final Object target;
private final String beanName;
private final Map<String, Object> cache;
public CacheInvocationHandler(Object target, String beanName, Map<String, Object> cache) {
this.target = target;
this.beanName = beanName;
this.cache = cache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Cacheable cacheable = method.getAnnotation(Cacheable.class);
if (cacheable != null) {
// 生成缓存键
String cacheKey = generateCacheKey(method, args);
// 检查缓存
Object cachedResult = cache.get(cacheKey);
if (cachedResult != null) {
return cachedResult;
}
// 执行方法并缓存结果
Object result = method.invoke(target, args);
cache.put(cacheKey, result);
return result;
}
// 非缓存方法直接执行
return method.invoke(target, args);
}
/**
* 生成缓存键
*/
private String generateCacheKey(Method method, Object[] args) {
StringBuilder keyBuilder = new StringBuilder();
keyBuilder.append(beanName).append(":").append(method.getName());
if (args != null) {
for (Object arg : args) {
keyBuilder.append(":").append(arg);
}
}
return keyBuilder.toString();
}
}
/**
* 自定义注解,标记可缓存的方法
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cacheable {
}
}
8. BeanPostProcessor的注册和管理
/*
* BeanPostProcessor的注册和管理机制
*/
/**
* BeanPostProcessor注册器
*/
public class BeanPostProcessorRegistration {
/**
* 手动注册BeanPostProcessor
*/
@Configuration
public static class BeanPostProcessorConfig {
@Bean
public BeanPostProcessor customBeanPostProcessor() {
return new CustomBeanPostProcessor();
}
@Bean
public BeanPostProcessor anotherBeanPostProcessor() {
return new AnotherBeanPostProcessor();
}
}
/**
* 通过ApplicationContextAware注册BeanPostProcessor
*/
@Component
public static class DynamicBeanPostProcessorRegistrar implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
// 动态注册BeanPostProcessor
if (applicationContext instanceof ConfigurableApplicationContext) {
ConfigurableApplicationContext configurableContext =
(ConfigurableApplicationContext) applicationContext;
configurableContext.getBeanFactory().addBeanPostProcessor(
new DynamicBeanPostProcessor());
}
}
}
/**
* 条件化BeanPostProcessor注册
*/
@Component
@ConditionalOnProperty(name = "feature.monitoring.enabled", havingValue = "true")
public static class ConditionalBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 只在启用监控功能时执行
return bean;
}
}
/**
* Ordered BeanPostProcessor示例
*/
@Component
public static class FirstBeanPostProcessor implements BeanPostProcessor, Ordered {
@Override
public int getOrder() {
return 1; // 优先级高
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("FirstBeanPostProcessor - Before: " + beanName);
return bean;
}
}
@Component
public static class SecondBeanPostProcessor implements BeanPostProcessor, Ordered {
@Override
public int getOrder() {
return 2; // 优先级低
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("SecondBeanPostProcessor - Before: " + beanName);
return bean;
}
}
}
/**
* BeanPostProcessor优先级管理
*/
public class BeanPostProcessorOrdering {
/**
* 使用@Order注解指定优先级
*/
@Component
@Order(1)
public static class HighPriorityBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("High priority processor");
return bean;
}
}
/**
* 实现Ordered接口指定优先级
*/
@Component
public static class LowPriorityBeanPostProcessor implements BeanPostProcessor, Ordered {
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Low priority processor");
return bean;
}
}
/**
* PriorityOrdered实现示例
*/
@Component
public static class PriorityOrderedBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Priority ordered processor");
return bean;
}
}
}
9. 核心设计要点总结
9.1 执行顺序
- PriorityOrdered BeanPostProcessor
- Ordered BeanPostProcessor
- 普通 BeanPostProcessor
9.2 调用时机
- postProcessBeforeInstantiation: Bean实例化前
- postProcessAfterInstantiation: Bean实例化后,属性注入前
- postProcessProperties: 属性注入时
- postProcessBeforeInitialization: 初始化前(Aware接口后)
- postProcessAfterInitialization: 初始化后(DisposableBean前)
9.3 返回值处理
- 可以返回原始Bean实例
- 可以返回包装后的Bean实例(代理模式)
- 返回null会导致NullPointerException
9.4 常见应用场景
- AOP代理创建: AnnotationAwareAspectJAutoProxyCreator
- 依赖注入: AutowiredAnnotationBeanPostProcessor
- 注解处理: CommonAnnotationBeanPostProcessor
- Aware接口: ApplicationContextAwareProcessor
- 事件监听: ApplicationListenerDetector
9.5 最佳实践
- 性能考虑: 避免在BeanPostProcessor中执行耗时操作
- 异常处理: 适当处理异常,避免影响整个应用
- 优先级设置: 合理设置BeanPostProcessor的执行顺序
- 资源管理: 在DestructionAwareBeanPostProcessor中清理资源
- 幂等性: 确保BeanPostProcessor可以安全地多次调用
9.6 注意事项
- BeanPostProcessor会影响所有Bean的创建过程
- 避免在BeanPostProcessor中创建其他Bean(可能导致循环依赖)
- 实现类应该声明为@Component或通过配置注册
- 注意BeanPostProcessor本身的生命周期管理
BeanPostProcessor作为Spring框架最重要的扩展点之一,为开发者提供了强大的定制能力,是理解Spring IOC容器工作原理的关键。

1万+

被折叠的 条评论
为什么被折叠?



