Spring中的后置处理器BeanPostProcessor讲解
Spring中提供了很多PostProcessor供开发者进行拓展,例如:BeanPostProcessor、BeanFactoryPostProcessor、BeanValidationPostProcessor等一系列后处理器。他们的使用方式大多类似,了解其中一个并掌握他的使用方式,其他的可以触类旁通。
BeanPostProcessor接口作用:
如果我们想在Spring容器中完成bean实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。我们需要定义一个或多个BeanPostProcessor接口实现类,然后注册到Spring IoC容器中。
BeanPostProcessor API:
public interface BeanPostProcessor {
/**
* 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.
*/
//实例化、依赖注入完毕,在调用显示的初始化之前完成一些定制的初始化任务
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* 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.
*/
//实例化、依赖注入、初始化完毕时执行
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
BeanPostProcessor接口提供了两个供开发者自定义的方法:postProcessBeforeInitialization、postProcessAfterInitialization。
postProcessBeforeInitialization:该方法主要针对spring在bean初始化时调用初始化方法前进行自定义处理。
postProcessAfterInitialization:该方法主要针对spring在bean初始化时调用初始化方法后进行自定义处理。
测试代码:
com.test.model.Cat:
package com.test.model; /**
* 测试bean
*/
public class Cat {
private String name;
private int age; public void say() {
System.out.println("name:" + name);
System.out.println("age:" + age);
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}
spring容器中配置cat,和cat的beanPostProcessor:
<!--配置bean并初始化-->
<bean id="cat" class="com.test.model.Cat" >
<property name="name" value="HelloKitty" />
<property name="age" value="1" />
</bean>
<bean id="catBeanPostProcessor" class="com.test.postprocessor.CatBeanPostProcessor" />
com.test.postprocessor.CatBeanPostProcessor:
package com.test.postprocessor; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import com.test.model.Cat; /**
* 自定义后处理器
*/
public class CatBeanPostProcessor implements BeanPostProcessor{ @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Cat) {
//输出原始属性
Cat cat = (Cat) bean;
cat.say();
return bean;
}
return bean;
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Cat) {
//修改属性值,并返回
Cat cat = (Cat) bean;
cat.setName("hello maomi");
cat.setAge(3);
return cat;
}
return bean;
} }
IndexController:
package com.cy.controller; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.WebApplicationContextUtils; import com.test.model.Cat; @Controller
public class IndexController { //到index首页
@RequestMapping(value="index")
public String index(HttpServletRequest request){
/**
* 访问index同时,从容器中获取已经被初始化之后处理过的cat,打印信息
*/
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
Cat c = (Cat) ac.getBean("cat");
c.say(); return "index";
}
}
观察结果:
容器启动时,输出:
/**
* 初始化bean
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
//省略部分无关代码
Object wrappedBean = bean;
//初始化前
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
//调用初始化方法初始化bean
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()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
//postProcessBeforeInitialization方法调用
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException { Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
//调用自定义postProcessBeforeInitialization方法
Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
//postProcessAfterInitialization方法调用
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException { Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
//自定义postProcessAfterInitialization方法调用
Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
Spring中的后置处理器BeanPostProcessor讲解的更多相关文章
- Spring点滴五:Spring中的后置处理器BeanPostProcessor讲解
BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...
- spring学习四:Spring中的后置处理器BeanPostProcessor
BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...
- spring中Bean后置处理器实现总结
BeanPostProcessor接口 bean的后置处理器实现功能主要是 可以在bean初始化之前和之后做增强处理.自定义MyBeanProcessor实现BeanPostProcessor接口,重 ...
- Spring Bean前置后置处理器的使用
Spirng中BeanPostProcessor和InstantiationAwareBeanPostProcessorAdapter两个接口都可以实现对bean前置后置处理的效果,那这次先讲解一下B ...
- Spring 如何保证后置处理器的执行顺序 - OrderComparator
Spring 如何保证后置处理器的执行顺序 - OrderComparator Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.htm ...
- Spring的后置处理器BeanPostProcessor
一.BeanPostProcessor接口的作用 如果我们需要在Spring容器完成Bean的实例化.配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProce ...
- spring后置处理器BeanPostProcessor
BeanPostProcessor的作用是在调用初始化方法的前后添加一些逻辑,这里初始化方法是指在配置文件中配置init-method,或者实现了InitializingBean接口的afterPro ...
- spring的后置处理器——BeanPostProcessor以及spring的生命周期
后置处理器的调用时机 BeanPostProcessor是spring提供的接口,它有两个方法——postProcessBeforeInitialization.postProcessAfterIni ...
- Bean后置处理器 BeanPostProcessor
1.BeanPostProcessor接口的作用 Bean后置处理器允许在调用初始化方法前后对Bean进行额外的处理,Bean后置处理器对IOC容器的所有bean实例逐一处理,而非单一实例. 我们可以 ...
随机推荐
- 设置xml中控件的圆润边框效果
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http: ...
- hibernate级联 cascade属性(转)
在Hibernate中,针对持久化实体的配置文件中有Cascade这样一个属性,顾名思义就是级联,也就是说在操作当 前实体时,针对当前实体的操作会影响到相应配置的关联实体.比如针对当前实体进行保存操作 ...
- windows下清除svn密码
刚进公司的时候没有SVN账号,暂用别人的账号很平常,为了更好的代码管理,后面肯定用自己的账号. 那么怎么清除呢. 进入 C:\Documents and Settings\Administrator\ ...
- websevice之三要素
SOAP(Simple Object Access Protocol).WSDL(WebServicesDescriptionLanguage).UDDI(UniversalDescriptionDi ...
- 一个用vue-cli vue-router2.1 vue 2.1 vuex2.1 echarts统计 express 的 时间轴 记录每天活动
界面还挺好看的... 可以记录每天的点点滴滴... 1.使用 express 作为服务器 2.fs 模块 fs.writeFileSync 随机写入模拟数据 3.vuex 包括 states 存储数据 ...
- 配置thunderbirdmail
添加帐号 打开Edit→Account Settings ,选择左下放的 "Account actions"→"Add Mail Account". 在弹出框中 ...
- 步步入佳境---UI入门(1)--项目建立与实现
一,本文讲解建立一个空项目,怎么一步一步的创建程序,总体的感觉一下程序流程 1,首先建立一个项目,如下:single view project,我们首先删除CHAppDelegate文件和Main. ...
- 玩转TypeScript(2) --简单TypeScript类型
通过TypeScript的Module和Class,TypeScript提供了相对于javaScript更加清晰的代码构造,相较于javaScript的.js满天飞的代码,用TypeScript,你可 ...
- python 正则表达式 提取网页中标签的中文
转载请注明出处 http://www.cnblogs.com/pengwang52/. >>> p= re.compile(r'\<div class="commen ...
- android中传统的创建数据库
1.在Android工程中建立一个class类,且继承与SQLiteOpenHelper. 2.然后到Mainactivity中去new一个MyOpenHelper来找到它 3.第一次创建数据库的时候 ...