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实例逐一处理,而非单一实例. 我们可以 ...
随机推荐
- 第n次考试
题目: 1.堆方块 [题目描述] 给定N个方块,排成一行,将它们编号1到N. 再给出P个操作: M i j表示将i所在的那一堆移到j所在那一堆的顶上. C i表示一个询问,询问i下面有多少个方块. ...
- [需要补充]javaEE中servlet方法service与doXXX的关系
刚开始很模糊他们的关系,不清楚 service protected void service(HttpServletRequest req, HttpServletResponse resp) thr ...
- OPENWRT常用设置
常用设置: 计划任务,定时重启 系统--计划任务,每行一个计划任务. 然后是计划任务列表的格式: [minute] [hour] [day of month] [month] [day of week ...
- Hibernate基于【XML】和【注解】——完整实例
Eclipse中新建Java Project工程: 工程结构 和 需要的Jar包: 我用的SqlServer数据库,所以连接数据库的Jar包是sqljdbc4.jar 一.基于XML配置 1.实体 ...
- 2016 ACM/ICPC Asia Regional Qingdao Online 1001 I Count Two Three(打表+二分搜索)
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission( ...
- I.MX6 Ar8031 device register hacking
/***************************************************************************** * I.MX6 Ar8031 device ...
- Gym 101745 D.Stamp Stamp Stamp
题目网页链接: http://codeforces.com/gym/101745/problem/D 思路:首先可以确保能够成功染色的字符串都是结果串的子串,那么O(n^2)枚举子串之后dp转移即可. ...
- ElasticSearch(八):springboot集成ElasticSearch集群并使用
1. 集群的搭建 见:ElasticSearch(七) 2. springboot配置集群 2.1 创建springboot项目,使用idea创建,不过多介绍(创建项目时候建议不要勾选elastics ...
- Slack 开发入门之 Incoming Webhooks:往 Slack 的 Channel 中发消息
一个工程师团队使用 Slack 进行团队协作比 QQ / 微信流的效率高多啦.除了基本的 IM 之外,它的扩展性也是非常重要的一点. 本文介绍 Slack 的开发入门:Incoming Webhook ...
- 网络流--最大流ek模板
标准大白书式模板,代码简单但由于效率并不高,所以并不常用,就是这样 #include<stdio.h> #include<string.h> #include<queue ...