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";
}
}

观察结果:

容器启动时,输出:

name:HelloKitty
age:1
访问项目http://localhost:8080/demo/index,index链接时,输出:
name:hello maomi
age:3
 
--------------------------------------------------------------------------------------------------------------------------
可以看到通过后处理器处理过后的bean信息已经改变。最后,看看源码中如何调用自定义实现的。
在初始化bean方法中:AbstractAutowireCapableBeanFactory.java
/**
* 初始化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讲解的更多相关文章

  1. Spring点滴五:Spring中的后置处理器BeanPostProcessor讲解

    BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...

  2. spring学习四:Spring中的后置处理器BeanPostProcessor

    BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...

  3. spring中Bean后置处理器实现总结

    BeanPostProcessor接口 bean的后置处理器实现功能主要是 可以在bean初始化之前和之后做增强处理.自定义MyBeanProcessor实现BeanPostProcessor接口,重 ...

  4. Spring Bean前置后置处理器的使用

    Spirng中BeanPostProcessor和InstantiationAwareBeanPostProcessorAdapter两个接口都可以实现对bean前置后置处理的效果,那这次先讲解一下B ...

  5. Spring 如何保证后置处理器的执行顺序 - OrderComparator

    Spring 如何保证后置处理器的执行顺序 - OrderComparator Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.htm ...

  6. Spring的后置处理器BeanPostProcessor

    一.BeanPostProcessor接口的作用 如果我们需要在Spring容器完成Bean的实例化.配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProce ...

  7. spring后置处理器BeanPostProcessor

    BeanPostProcessor的作用是在调用初始化方法的前后添加一些逻辑,这里初始化方法是指在配置文件中配置init-method,或者实现了InitializingBean接口的afterPro ...

  8. spring的后置处理器——BeanPostProcessor以及spring的生命周期

    后置处理器的调用时机 BeanPostProcessor是spring提供的接口,它有两个方法——postProcessBeforeInitialization.postProcessAfterIni ...

  9. Bean后置处理器 BeanPostProcessor

    1.BeanPostProcessor接口的作用 Bean后置处理器允许在调用初始化方法前后对Bean进行额外的处理,Bean后置处理器对IOC容器的所有bean实例逐一处理,而非单一实例. 我们可以 ...

随机推荐

  1. Nodejs之mssql模块的封装

    在nodejs中,mssql模块支持sqlserver数据库操作.今天将mssql模块的某些功能封装为一个类,方便以后调用.封装的功能有执行存储过程,执行查询语句操作等.如果本篇文章对大家有帮助,那就 ...

  2. MyEclipse CI 2018.8.0正式发布(附下载)

    MyEclipse线上特惠,在线立享专属折扣!火热开启中>> MyEclipse 2018最终版日前正式发布,新版本通过构建Eclipse Photo.支持Java 10和Java EE ...

  3. 使用Socket的简单Web服务器

    Socket类在System.Net.Sockets命名空间 常用的操作 Bind:绑定一个本地的终结点 Listen:进入监听状态,并设置等待队列 Accept:等待一个新连接,当连接到达时,返回一 ...

  4. HDU 1565

    http://acm.hdu.edu.cn/showproblem.php?pid=1565 先进行二分图黑白染色,S到黑,白到T,黑到白,问题转化成了求最大权独立集,最大点权独立集=sum-最小点权 ...

  5. Magento邮件发送完美设置

    Magento新站上线伊始,不料在邮件上遇到了问题.此时常用的邮件模板已经编辑完毕,诸如New Account, New Order, Password Forget等. CentOS下发送邮件很简单 ...

  6. stm32 DAC配置

    VDDA 和 VSSA 为 DAC 模块模拟部分的供电,而 Vref+则是 DAC 模块的参考电压.DAC_OUTx 就是 DAC 的 输出通道了 (对应 PA4 或者 PA5 引脚). 由第一张图可 ...

  7. Codeforces1106F 【BSGS】【矩阵快速幂】【exgcd】

    首先矩阵快速幂可以算出来第k项的指数,然后可以利用原根的性质,用bsgs和exgcd把答案解出来 #include<bits/stdc++.h> using namespace std; ...

  8. [Boolan-C++学习笔记]第一周整理

    1.两种典型类 Complex 无指针 String 有指针 编写思路差异较大 2.使用Class声明:Object Based.类与类之间的关系:Object Oriented 3.头文件的布局 # ...

  9. setsebool命令详解与SELinux管理

    setsebool命令是用来修改SElinux策略内各项规则的布尔值.setsebool命令和getsebool命令是SELinux修改和查询布尔值的一套工具组.SELinux的策略与规则管理相关命令 ...

  10. Linux驱动中常用的宏

    .module_i2c_driver(adxl34x_driver)展开为 static int __int adxl34x_driver_init(void) { return i2c_regist ...