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通过全 ...
随机推荐
- Web信息收集-目标扫描-Nmap
Web信息收集-目标扫描-Nmap 一.Nmap简介 二.扫描示例 使用主机名扫描: 使用IP地址扫描: 扫描多台主机: 扫描整个子网 使用IP地址的最后一个字节扫描多台服务器 从一个文件中扫描主机列 ...
- java-poi创建模板
package com.jy.demo.web; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Cell; i ...
- DolphinScheduler1.3.2源码分析(二)搭建源码环境以及启动项目
前置依赖组件安装 找一台服务器,或者本地的虚拟机,然后在服务器上安装好jdk,zookeeper,mysql. 1.源码调试环境搭建 源码环境搭建可以参考DolphinScheduler官方网站的开发 ...
- SparkCore2
二.RDD编程 2.5 RDD中的函数传递 在实际开发中我们往往需要自己定义一些对于RDD的操作,那么此时需要主要的是,初始化工作是在Driver端进行的,而实际运行程序是在Executor端进行的, ...
- 2019牛客暑期多校训练营(第五场)H-subsequence 2 (拓扑排序+思维)
>传送门< 题意: 给你几组样例,给你两个字符a,b,一个长度len,一个长度为len的字符串str,str是字符串s的子串 str是s删掉除过a,b两字符剩下的子串,现在求s,多种情况输 ...
- POJ-2411 Mondriann's Dream (状压DP)
求把\(N*M(1\le N,M \le 11)\) 的棋盘分割成若干个\(1\times 2\) 的长方形,有多少种方案.例如当 \(N=2,M=4\)时,共有5种方案.当\(N=2,M=3\)时, ...
- 【uva 1395】Slim Span(图论--最小生成树+结构体快速赋值 模版题)
题意:给一个N(N<=100)个点的联通图(无自环和平行边),求苗条度(最大边-最小边的值)尽量小的生成树. 解法:枚举+Kruskal.先从小到大排序边,枚举选择的最小的边. 1 #inclu ...
- 【noi 2.6_9272】偶数个数字3(DP)
题意:问所有的N位数中,有多少个有偶数个数字3的数. 解法:f[i][j]表示i位数中含数字3的个数模2为j的个数.于是分第i位填3还是不填3讨论. 小tip:要模12345:for循环新定义了一个变 ...
- P1541 乌龟棋(DP)
题目背景 小明过生日的时候,爸爸送给他一副乌龟棋当作礼物. 题目描述 乌龟棋的棋盘是一行NNN个格子,每个格子上一个分数(非负整数).棋盘第1格是唯一的起点,第NNN格是终点,游戏要求玩家控制一个乌龟 ...
- python代理池的构建4——mongdb数据库的增删改查
上一篇博客地址:python代理池的构建3--爬取代理ip 一.mongdb数据库的增删改查(Mongo_pool.py) #-*-coding:utf-8-*- ''' 实现代理池的数据库模块 ●作 ...