BeanFactoryPostProcessor
BeanFactoryPostProcessor
接口允许在 Spring 容器初始化完所有的 bean 定义之后,但还未实例化任何 bean 时,修改应用上下文的内部 bean 工厂。通过实现 postProcessBeanFactory
方法,你可以覆盖或添加属性,甚至是对急切初始化的 beans 进行修改。
// AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer, CustomEditorConfigurer, CustomScopeConfigurer, DeprecatedBeanWarner, EventListenerMethodProcessor, PlaceholderConfigurerSupport, PreferencesPlaceholderConfigurer, PropertyOverrideConfigurer, PropertyPlaceholderConfigurer, PropertyResourceConfigurer, PropertySourcesPlaceholderConfigurer
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor
接口继承自 BeanFactoryPostProcessor
,允许在应用上下文的内部 bean 定义注册表初始化之后(但还未实例化任何 bean)修改 bean 定义。通过实现 postProcessBeanDefinitionRegistry
方法,可以在下一个后处理阶段之前,向容器中添加额外的 bean 定义。postProcessBeanFactory
方法默认是空实现,因为该接口主要关注 postProcessBeanDefinitionRegistry
方法。
// ConfigurationClassPostProcessor
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean definition registry after its
* standard initialization. All regular bean definitions will have been loaded,
* but no beans will have been instantiated yet. This allows for adding further
* bean definitions before the next post-processing phase kicks in.
* @param registry the bean definition registry used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
/**
* Empty implementation of {@link BeanFactoryPostProcessor#postProcessBeanFactory}
* since custom {@code BeanDefinitionRegistryPostProcessor} implementations will
* typically only provide a {@link #postProcessBeanDefinitionRegistry} method.
* @since 6.1
*/
@Override
default void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
实现类 | 用途 |
---|---|
AspectJWeavingEnabler | 启用 AspectJ 编织支持,通常与 Spring AOP 集成使用,用于支持 AspectJ 注解的织入。 |
ConfigurationClassPostProcessor | 处理 Spring 配置类(使用 @Configuration 注解的类),执行配置类的 Bean 定义处理。 |
CustomAutowireConfigurer | 允许注册自定义的自动注入限定符类型(如自定义注解),以扩展 Spring 的自动注入功能。 |
CustomEditorConfigurer | 为 Spring Bean 的属性类型注册自定义编辑器,以便在属性赋值时进行类型转换。 |
CustomScopeConfigurer | 配置 Spring 自定义作用域(例如,创建一个新的作用域或改变现有作用域的行为)。 |
DeprecatedBeanWarner | 提供警告,在 Spring Bean 配置中发现已弃用的 Bean 时发出警告。 |
EventListenerMethodProcessor | 处理使用 @EventListener 注解的方法,自动注册为 Spring 应用上下文中的事件监听器。 |
PlaceholderConfigurerSupport | 支持配置属性的占位符替换,通常用于加载属性文件并注入属性值到 Bean 中。 |
PreferencesPlaceholderConfigurer | 允许从 java.util.prefs.Preferences 中加载占位符属性,适用于 Java 的偏好设置。 |
PropertyOverrideConfigurer | 允许通过 XML 配置文件覆盖现有的 Bean 属性值,通常用于根据不同环境加载不同的配置。 |
PropertyPlaceholderConfigurer | 用于解析 properties 文件中的占位符并注入到 Spring 配置中的 Bean 属性。 |
PropertyResourceConfigurer | 处理并加载资源文件(如 .properties 文件)中的占位符替换,常用于外部配置文件的支持。 |
PropertySourcesPlaceholderConfigurer | 替代 PropertyPlaceholderConfigurer ,支持在 Spring 4 中对 PropertySources API 的扩展。 |
BeanFactoryInitializer
BeanFactoryInitializer
接口用于初始化给定的 beanFactory
。它定义了一个方法 initialize
,接收一个类型为 F extends ListableBeanFactory
的 beanFactory
参数,允许实现类对该 beanFactory
进行启动或初始化设置。
public interface BeanFactoryInitializer<F extends ListableBeanFactory> {
/**
* Initialize the given bean factory.
* @param beanFactory the bean factory to bootstrap
*/
void initialize(F beanFactory);
}
BeanPostProcessor
BeanPostProcessor
接口允许在 Spring 容器初始化 bean 之前和之后对其进行自定义处理。通过实现这两个方法:postProcessBeforeInitialization
和 postProcessAfterInitialization
,你可以在 bean 初始化的各个阶段修改 bean 实例或返回一个包装的版本。
// AbstractAdvisingBeanPostProcessor, AbstractAdvisorAutoProxyCreator, AbstractAutoProxyCreator, AbstractBeanFactoryAwareAdvisingPostProcessor, AdvisorAdapterRegistrationManager, AnnotationAwareAspectJAutoProxyCreator, AspectJAwareAdvisorAutoProxyCreator, AsyncAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor, BeanNameAutoProxyCreator, BeanValidationPostProcessor, CommonAnnotationBeanPostProcessor, DefaultAdvisorAutoProxyCreator, ImportAwareAotBeanPostProcessor, InfrastructureAdvisorAutoProxyCreator, InitDestroyAnnotationBeanPostProcessor, JmsListenerAnnotationBeanPostProcessor, LoadTimeWeaverAwareProcessor, MethodValidationPostProcessor, PersistenceAnnotationBeanPostProcessor, PersistenceExceptionTranslationPostProcessor, ScheduledAnnotationBeanPostProcessor, ScriptFactoryPostProcessor, ServletContextAwareProcessor, SimpleServletPostProcessor
public interface BeanPostProcessor {
/**
* Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>The default implementation returns the given {@code bean} as-is.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other {@code BeanPostProcessor} callbacks.
* <p>The default implementation returns the given {@code bean} as-is.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
DestructionAwareBeanPostProcessor
DestructionAwareBeanPostProcessor
是一个扩展自 BeanPostProcessor
的接口,用于在 Spring 容器销毁 bean 前执行自定义的销毁操作,并可以判断是否需要销毁该 bean。
// CommonAnnotationBeanPostProcessor, InitDestroyAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, ScheduledAnnotationBeanPostProcessor, SimpleServletPostProcessor
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given bean instance before its
* destruction, for example, invoking custom destruction callbacks.
* <p>Like DisposableBean's {@code destroy} and a custom destroy method, this
* callback will only apply to beans which the container fully manages the
* lifecycle for. This is usually the case for singletons and scoped beans.
* @param bean the bean instance to be destroyed
* @param beanName the name of the bean
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.DisposableBean#destroy()
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#setDestroyMethodName(String)
*/
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;
/**
* Determine whether the given bean instance requires destruction by this
* post-processor.
* <p>The default implementation returns {@code true}. If a pre-5 implementation
* of {@code DestructionAwareBeanPostProcessor} does not provide a concrete
* implementation of this method, Spring silently assumes {@code true} as well.
* @param bean the bean instance to check
* @return {@code true} if {@link #postProcessBeforeDestruction} is supposed to
* be called for this bean instance eventually, or {@code false} if not needed
* @since 4.3
*/
default boolean requiresDestruction(Object bean) {
return true;
}
}
InstantiationAwareBeanPostProcessor
InstantiationAwareBeanPostProcessor
是一个扩展自 BeanPostProcessor
的接口,用于在 Spring 容器实例化 bean 之前和之后进行自定义处理,允许修改 bean 实例化过程及其属性设置。
// AbstractAdvisingBeanPostProcessor, AbstractAdvisorAutoProxyCreator, AbstractAutoProxyCreator, AbstractBeanFactoryAwareAdvisingPostProcessor, AnnotationAwareAspectJAutoProxyCreator, AspectJAwareAdvisorAutoProxyCreator, AsyncAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor, BeanNameAutoProxyCreator, CommonAnnotationBeanPostProcessor, DefaultAdvisorAutoProxyCreator, InfrastructureAdvisorAutoProxyCreator, MethodValidationPostProcessor, PersistenceAnnotationBeanPostProcessor, PersistenceExceptionTranslationPostProcessor, ScriptFactoryPostProcessor
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
/**
* Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>.
* The returned bean object may be a proxy to use instead of the target bean,
* effectively suppressing default instantiation of the target bean.
* <p>If a non-null object is returned by this method, the bean creation process
* will be short-circuited. The only further processing applied is the
* {@link #postProcessAfterInitialization} callback from the configured
* {@link BeanPostProcessor BeanPostProcessors}.
* <p>This callback will be applied to bean definitions with their bean class,
* as well as to factory-method definitions in which case the returned bean type
* will be passed in here.
* <p>Post-processors may implement the extended
* {@link SmartInstantiationAwareBeanPostProcessor} interface in order
* to predict the type of the bean object that they are going to return here.
* <p>The default implementation returns {@code null}.
* @param beanClass the class of the bean to be instantiated
* @param beanName the name of the bean
* @return the bean object to expose instead of a default instance of the target bean,
* or {@code null} to proceed with default instantiation
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessAfterInstantiation
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getBeanClass()
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName()
*/
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
/**
* Perform operations after the bean has been instantiated, via a constructor or factory method,
* but before Spring property population (from explicit properties or autowiring) occurs.
* <p>This is the ideal callback for performing custom field injection on the given bean
* instance, right before Spring's autowiring kicks in.
* <p>The default implementation returns {@code true}.
* @param bean the bean instance created, with properties not having been set yet
* @param beanName the name of the bean
* @return {@code true} if properties should be set on the bean; {@code false}
* if property population should be skipped. Normal implementations should return {@code true}.
* Returning {@code false} will also prevent any subsequent InstantiationAwareBeanPostProcessor
* instances being invoked on this bean instance.
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessBeforeInstantiation
*/
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
/**
* Post-process the given property values before the factory applies them
* to the given bean.
* <p>The default implementation returns the given {@code pvs} as-is.
* @param pvs the property values that the factory is about to apply (never {@code null})
* @param bean the bean instance created, but whose properties have not yet been set
* @param beanName the name of the bean
* @return the actual property values to apply to the given bean (can be the passed-in
* PropertyValues instance), or {@code null} to skip property population
* @throws org.springframework.beans.BeansException in case of errors
* @since 5.1
*/
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
return pvs;
}
}
MergedBeanDefinitionPostProcessor
MergedBeanDefinitionPostProcessor
是一个扩展自 BeanPostProcessor
的接口,用于在合并后的 bean 定义过程中进行自定义处理,并允许在 bean 定义重置时清理相关元数据。
// AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, InitDestroyAnnotationBeanPostProcessor, JmsListenerAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, ScheduledAnnotationBeanPostProcessor
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
/**
* Post-process the given merged bean definition for the specified bean.
* @param beanDefinition the merged bean definition for the bean
* @param beanType the actual type of the managed bean instance
* @param beanName the name of the bean
* @see AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
*/
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
/**
* A notification that the bean definition for the specified name has been reset,
* and that this post-processor should clear any metadata for the affected bean.
* <p>The default implementation is empty.
* @param beanName the name of the bean
* @since 5.1
* @see DefaultListableBeanFactory#resetBeanDefinition
*/
default void resetBeanDefinition(String beanName) {
}
}
SmartInstantiationAwareBeanPostProcessor
SmartInstantiationAwareBeanPostProcessor
扩展了 InstantiationAwareBeanPostProcessor
,提供了一些额外的回调方法,用于预测、确定和操作 bean 类型、构造函数以及早期访问的引用,支持更细粒度的 bean 创建和初始化控制。
// AbstractAdvisingBeanPostProcessor, AbstractAdvisorAutoProxyCreator, AbstractAutoProxyCreator, AbstractBeanFactoryAwareAdvisingPostProcessor, AnnotationAwareAspectJAutoProxyCreator, AspectJAwareAdvisorAutoProxyCreator, AsyncAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor, BeanNameAutoProxyCreator, DefaultAdvisorAutoProxyCreator, InfrastructureAdvisorAutoProxyCreator, MethodValidationPostProcessor, PersistenceExceptionTranslationPostProcessor, ScriptFactoryPostProcessor
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
/**
* Predict the type of the bean to be eventually returned from this
* processor's {@link #postProcessBeforeInstantiation} callback.
* <p>The default implementation returns {@code null}.
* Specific implementations should try to predict the bean type as
* far as known/cached already, without extra processing steps.
* @param beanClass the raw class of the bean
* @param beanName the name of the bean
* @return the type of the bean, or {@code null} if not predictable
* @throws org.springframework.beans.BeansException in case of errors
*/
@Nullable
default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
/**
* Determine the type of the bean to be eventually returned from this
* processor's {@link #postProcessBeforeInstantiation} callback.
* <p>The default implementation returns the given bean class as-is.
* Specific implementations should fully evaluate their processing steps
* in order to create/initialize a potential proxy class upfront.
* @param beanClass the raw class of the bean
* @param beanName the name of the bean
* @return the type of the bean (never {@code null})
* @throws org.springframework.beans.BeansException in case of errors
* @since 6.0
*/
default Class<?> determineBeanType(Class<?> beanClass, String beanName) throws BeansException {
return beanClass;
}
/**
* Determine the candidate constructors to use for the given bean.
* <p>The default implementation returns {@code null}.
* @param beanClass the raw class of the bean (never {@code null})
* @param beanName the name of the bean
* @return the candidate constructors, or {@code null} if none specified
* @throws org.springframework.beans.BeansException in case of errors
*/
@Nullable
default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
* <p>This callback gives post-processors a chance to expose a wrapper
* early - that is, before the target bean instance is fully initialized.
* The exposed object should be equivalent to what
* {@link #postProcessBeforeInitialization} / {@link #postProcessAfterInitialization}
* would expose otherwise. Note that the object returned by this method will
* be used as the bean reference unless the post-processor returns a different
* wrapper from said post-process callbacks. In other words, those post-process
* callbacks may either eventually expose the same reference or alternatively
* return the raw bean instance from those subsequent callbacks (if the wrapper
* for the affected bean has been built for a call to this method already,
* it will be exposed as the final bean reference by default).
* <p>The default implementation returns the given {@code bean} as-is.
* @param bean the raw bean instance
* @param beanName the name of the bean
* @return the object to expose as the bean reference
* (typically the passed-in bean instance as default)
* @throws org.springframework.beans.BeansException in case of errors
*/
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return bean;
}
}
实现类 | 用途 |
---|---|
AbstractAdvisingBeanPostProcessor |
用于 Spring AOP,提供通用的 Bean 后处理逻辑,支持自动代理和通知增强。 |
AbstractAdvisorAutoProxyCreator |
创建代理 Bean,并为其应用切面通知,用于自动代理。 |
AbstractAutoProxyCreator |
用于创建自动代理,增强 Bean。 |
AbstractBeanFactoryAwareAdvisingPostProcessor |
支持增强 Bean 的功能,并能在 Bean Factory 中获得访问。 |
AdvisorAdapterRegistrationManager |
用于注册和管理 Spring AOP 中的 Advisor。 |
AnnotationAwareAspectJAutoProxyCreator |
结合 AspectJ 注解为 Bean 自动创建代理。 |
AspectJAwareAdvisorAutoProxyCreator |
专门为 Spring AOP 创建基于 AspectJ 的代理。 |
AsyncAnnotationBeanPostProcessor |
用于处理 @Async 注解,将异步任务执行功能应用到 Bean 中。 |
AutowiredAnnotationBeanPostProcessor |
处理 @Autowired 注解,自动注入依赖的 Bean。 |
BeanNameAutoProxyCreator |
通过 Bean 名称创建代理 Bean,适用于特定名称的 Bean。 |
BeanValidationPostProcessor |
自动触发 Bean 的验证,适用于 @Valid 注解的验证。 |
CommonAnnotationBeanPostProcessor |
处理 Java EE 注解(如 @PostConstruct , @PreDestroy )的后处理。 |
DefaultAdvisorAutoProxyCreator |
默认的自动代理创建器,处理 AOP 中的 Advisor。 |
ImportAwareAotBeanPostProcessor |
用于处理 AOT(Ahead-of-Time)期间的导入依赖。 |
InfrastructureAdvisorAutoProxyCreator |
创建基础设施相关的 Advisor 自动代理,通常用于系统级的 AOP 配置。 |
InitDestroyAnnotationBeanPostProcessor |
处理 @PostConstruct 和 @PreDestroy 注解的 Bean 后处理器。 |
JmsListenerAnnotationBeanPostProcessor |
处理 @JmsListener 注解,将方法绑定为 JMS 消息监听器。 |
LoadTimeWeaverAwareProcessor |
处理类加载时间增强,通常与字节码增强技术(如 AspectJ)配合使用。 |
MethodValidationPostProcessor |
用于处理方法级验证的 Bean 后处理器。 |
PersistenceAnnotationBeanPostProcessor |
处理持久化相关注解(如 @Transactional ),自动配置事务管理。 |
PersistenceExceptionTranslationPostProcessor |
处理持久化异常的翻译,将数据库异常转换为 Spring 的数据访问异常。 |
ScheduledAnnotationBeanPostProcessor |
处理 @Scheduled 注解,自动配置定时任务。 |
ScriptFactoryPostProcessor |
处理脚本相关的配置,通常用于与脚本引擎相关的 Bean 配置。 |
ServletContextAwareProcessor |
使 Bean 能访问 ServletContext,用于 Web 环境的上下文访问。 |
SimpleServletPostProcessor |
简单的 Servlet 后处理器,用于处理 Servlet 配置。 |
SmartInitializingSingleton
SmartInitializingSingleton
接口提供了一个 afterSingletonsInstantiated
方法,该方法在所有普通单例 bean 实例化完成后被调用,适用于在容器启动过程中需要确保所有单例已创建的场景。
public interface SmartInitializingSingleton {
/**
* Invoked right at the end of the singleton pre-instantiation phase,
* with a guarantee that all regular singleton beans have been created
* already. {@link ListableBeanFactory#getBeansOfType} calls within
* this method won't trigger accidental side effects during bootstrap.
* <p><b>NOTE:</b> This callback won't be triggered for singleton beans
* lazily initialized on demand after {@link BeanFactory} bootstrap,
* and not for any other bean scope either. Carefully use it for beans
* with the intended bootstrap semantics only.
*/
void afterSingletonsInstantiated();
}
InitializingBean
InitializingBean
接口提供了一个 afterPropertiesSet
方法,在所有 bean 属性设置完成后由容器调用,允许 bean 进行验证和最终初始化。
public interface InitializingBean {
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
* <p>This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set.
* @throws Exception in the event of misconfiguration (such as failure to set an
* essential property) or if initialization fails for any other reason
*/
void afterPropertiesSet() throws Exception;
}
DisposableBean
DisposableBean
接口提供了一个 destroy
方法,在容器销毁 bean 时调用,允许 bean 释放资源并进行清理。
public interface DisposableBean {
/**
* Invoked by the containing {@code BeanFactory} on destruction of a bean.
* @throws Exception in case of shutdown errors. Exceptions will get logged
* but not rethrown to allow other beans to release their resources as well.
*/
void destroy() throws Exception;
}