spring扩展点整理
本文转载自spring扩展点整理
背景
Spring的强大和灵活性不用再强调了。而灵活性就是通过一系列的扩展点来实现的,这些扩展点给应用程序提供了参与Spring容器创建的过程,好多定制化的东西都需要扩展点的支持。尤其在使用SpringBoot的过程中。
BeanFactoryPostProcessor
这个扩展点是以一个接口定义的:
/**
* Allows for custom modification of an application context's bean definitions,
* adapting the bean property values of the context's underlying bean factory.
*
* <p>Application contexts can auto-detect BeanFactoryPostProcessor beans in
* their bean definitions and apply them before any other beans get created.
*
* <p>Useful for custom config files targeted at system administrators that
* override bean properties configured in the application context.
*
* <p>See PropertyResourceConfigurer and its concrete implementations
* for out-of-the-box solutions that address such configuration needs.
*
* <p>A BeanFactoryPostProcessor may interact with and modify bean
* definitions, but never bean instances. Doing so may cause premature bean
* instantiation, violating the container and causing unintended side-effects.
* If bean instance interaction is required, consider implementing
* {@link BeanPostProcessor} instead.
*
* @author Juergen Hoeller
* @since 06.07.2003
* @see BeanPostProcessor
* @see PropertyResourceConfigurer
*/
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;
}
BeanFactoryPostProcessor 这个扩展点的功能是:让应用程序在Spring创建Bean对象前修改BeanDefinition。其中一个例子就是Bean属性配置的类型转换,占位符替换。
BeanDefinitionRegistryPostProcessor
该扩展点的定义如下:
/**
* Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for
* the registration of further bean definitions <i>before</i> regular
* BeanFactoryPostProcessor detection kicks in. In particular,
* BeanDefinitionRegistryPostProcessor may register further bean definitions
* which in turn define BeanFactoryPostProcessor instances.
*
* @author Juergen Hoeller
* @since 3.0.1
* @see org.springframework.context.annotation.ConfigurationClassPostProcessor
*/
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
true/**
* 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
*/
truevoid postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
如上面的注释说明:该扩展点可以让应用程序注册自定义的BeanDefinition,并且该扩展点在 BeanFactoryPostProcessor 前执行。
Aware
/**
* Marker superinterface indicating that a bean is eligible to be
* notified by the Spring container of a particular framework object
* through a callback-style method. Actual method signature is
* determined by individual subinterfaces, but should typically
* consist of just one void-returning method that accepts a single
* argument.
*
* <p>Note that merely implementing {@link Aware} provides no default
* functionality. Rather, processing must be done explicitly, for example
* in a {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessor}.
* Refer to {@link org.springframework.context.support.ApplicationContextAwareProcessor}
* and {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory}
* for examples of processing {@code *Aware} interface callbacks.
*
* @author Chris Beams
* @since 3.1
*/
public interface Aware {
}
Aware 接口是一个标记接口,表示所有实现该接口的类是会被Spring容器选中,并得到某种通知。所有该接口的子接口提供固定的接收通知的方法。这样的接口有很多,最常用的如下:
public interface ApplicationContextAware extends Aware {
true/**
* Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see org.springframework.beans.factory.BeanInitializationException
*/
truevoid setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
ApplicationContextAware
的回调方法是在一般的属性注入后,但没有执行Bean的初始化方法前被执行的。初始化方法包括init-method
和InitializingBean
的afterPropertiesSet
方法。
/**
* Interface to be implemented by any bean that wishes to be notified
* of the {@link Environment} that it runs in.
*
* @author Chris Beams
* @since 3.1
*/
public interface EnvironmentAware extends Aware {
true/**
* Set the {@code Environment} that this object runs in.
*/
truevoid setEnvironment(Environment environment);
}
该接口用来接收应用程序的运行环境对象。
ApplicationListener
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
true/**
* Handle an application event.
* @param event the event to respond to
*/
truevoid onApplicationEvent(E event);
}
ApplicationListener 接口主要用来监听应用程序上下文的事件,不同的实现子类注册自己感兴趣的事件。
InitializingBean
public interface InitializingBean {
true/**
* Invoked by a BeanFactory after it has set all bean properties supplied
* (and satisfied BeanFactoryAware and ApplicationContextAware).
* <p>This method allows the bean instance to perform initialization only
* possible when all bean properties have been set and to throw an
* exception in the event of misconfiguration.
* @throws Exception in the event of misconfiguration (such
* as failure to set an essential property) or if initialization fails.
*/
truevoid afterPropertiesSet() throws Exception;
}
InitializingBean 主要用来实现自定义的Bean初始化逻辑。 InitializingBean接口的方法会被BeanFactory在BeanFactoryAware或ApplicationContextAware接口方法调用后进行调用。
InitializingBean 接口的功能还有一个替代方式,就是在xml配置bean结点属性的init-method
属性,指定初始化方法。需要注意的时候如同同时实现了InitializingBean接口并且配置了init-method
属性,则InitializingBean接口的方法会被先执行。
BeanPostProcessor
public interface BeanPostProcessor {
true/**
* Apply this 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.
* @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
*/
trueObject postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
true/**
* Apply this 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 BeanPostProcessor callbacks.
* @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
*/
trueObject postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
BeanPostProcessor 接口定义了在bean初始化前和初始化后执行的方法。应用程序自己可以实现该接口定义自己特殊的逻辑。
参考:http://jinnianshilongnian.iteye.com/blog/1489787 和 http://jinnianshilongnian.iteye.com/blog/1492424
FactoryBean
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}
通过实现接口FactoryBean
来自定义Bean的创建逻辑。Spring容器对待实现了接口FactoryBean
的类是特殊处理的。当你需要向容器请求一个真实的FactoryBean
实例,而不是它生产的bean,例如调用ApplicationContext
的getBean()
方法时,在bean
的id
之前要有连字符(&)。对于一个给定 id
为myBean
的FactoryBean
,调用容器的getBean("myBean")
方法返回的FactoryBean
产品。
spring扩展点整理的更多相关文章
- Spring JdbcTemplate用法整理
Spring JdbcTemplate用法整理: xml: <?xml version="1.0" encoding="UTF-8"?> <b ...
- spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情
<spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...
- spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入
<spring扩展点之二:spring中关于bean初始化.销毁等使用汇总,ApplicationContextAware将ApplicationContext注入> <spring ...
- 2019年Spring核心知识点整理,看看你掌握了多少?
前言 如今做Java尤其是web几乎是避免不了和Spring打交道了,但是Spring是这样的大而全,新鲜名词不断产生,学起来给人一种凌乱的感觉,在这里总结一下,理顺头绪. Spring 概述 Spr ...
- 【JAVA】Spring 数据源配置整理
在Spring中,不但可以通过JNDI获取应用服务器的数据源,也可以直接在Spring容器中配置数据源,此外,还可以通过代码的方式创建一个数据源,以便进行无依赖的单元测试. 配置数据源 ...
- Spring Ioc知识整理
Ioc知识整理(一): IoC (Inversion of Control) 控制反转. 1.bean的别名 我们每个bean元素都有一个id属性,用于唯一标识实例化的一个类,其实name属性也可用来 ...
- [Spring面试] 问题整理
1.谈谈你对spring IOC和DI的理解,它们有什么区别? IoC:Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spri ...
- Spring框架知识整理
Spring框架主要构成 Spring框架主要有7个模块: 1.Spring AOP:面向切面编程思想,同时也提供了事务管理. 2.Spring ORM:提供了对Hibernate.myBatis的支 ...
- 2018/9/6 spring框架的整理
spring知识的巩固整理AOP和ioc概念,以及了解到了为何要使用spring框架的目的,作用:变换资源获取的方向.更像是按需所求.配置bean的方式:利用XML的方式,基于注解的方式两种.1通过全 ...
随机推荐
- 换一种视角看DNS(采坑篇)
换一种视角看DNS 我们尽量用精炼的语言,尽可能的规划DNS的全貌(当然笔者水平有限,如有错误请不吝赐教). 通常啊我们在个人PC中能看到DNS的配置身影就是在上网的时候,通常如果你不配置DNS可能找 ...
- 天天写同步,5种SpringMvc异步请求了解下!
引言 说到异步大家肯定首先会先想到同步.我们先来看看什么是同步? 所谓同步,就是发出一个功能调用时,在没有得到结果之前,该调用就不返回或继续执行后续操作. 简单来说,同步就是必须一件一件事做,等前一件 ...
- 配置VS2013 + opencv 2.4.10
其实我内心是极力反对装这么老的版本的,但是要交课堂作业~~好无奈 [注] : 如果按照本文配置不成功,可以试一下其他博客里面的配置(多试一试总能成功的) https://jingyan.baidu.c ...
- HDU-4315 Climbing the Hill
题目链接 先回到阶梯博弈的裸题中,比如POJ-1704,所有的块只能向左移并且不能跨越,这个向左移的结果我们可以理解为将左边的宽度减少使得右边的宽度增加,等同于阶梯模型中将石子从高阶移动到低阶.那么最 ...
- hash应用
关于HASH 这应该是经常使用的一个算法,因为其预处理后,优秀的\(O(1)\)处理出子串,并且\(O(1)\)比较,大快人心,而且写法简单,令人心情愉悦; 但是其空间复杂度较高,并且有玄学模 ...
- 【noi 2.6_9280】&【bzoj 1089】严格n元树(DP+高精度+重载运算符)
题意:定义一棵树的所有非叶节点都恰好有n个儿子为严格n元树.问深度为d的严格n元树数目. 解法:f[i]表示深度为<=i的严格n元树数目.f[i]-f[i-1]表示深度为i的严格n元树数目.f[ ...
- IntelliJ IDEA 运行java程序时出现“程序发生找不到或无法加载主类 cn.test1.test1”错误
在你程序不出现错误,而且你的编译器已经成功导入后 成功导入的样子 你可以重新打开一个项目 这就可以了^_^
- POJ 3189
题意: 给你B个谷仓和n头牛,每个谷仓最多容纳m头牛.此时每头牛对每一个谷仓都有一个喜悦值,你需要把每一头牛都安排某个谷仓内,并且找出来那个每一头牛对它所住的谷仓打的分值,我们对这所有的分值取一个区间 ...
- C# 静态类 单例模式 对比
公司的类都需要使用单例模式实现,这个可以节省资源,避免重复对象的生成.但是静态类也可以做到这一点,而且写起来更简洁,于是查阅相关资料,希望弄明白两者的差别. 1.单例模式可以在用到的时候初始化,而静态 ...
- ASP.Net Core 5.0 MVC中AOP思想的体现(五种过滤器)并结合项目案例说明过滤器的用法
执行顺序 使用方法,首先实现各自的接口,override里面的方法, 然后在startup 类的 ConfigureServices 方法,注册它们. 下面我将代码贴出来,照着模仿就可以了 IActi ...