Spring 的 BeanPostProcessor接口实现
来源:互联网 发布:简单java代码 编辑:程序博客网 时间:2024/05/29 11:30
今天学习了一下Spring的BeanPostProcessor接口,该接口作用是:如果我们需要在Spring容器完成Bean的实例化,配置和其他的初始化后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现。
下面我们来看一个简单的例子:
package com.spring.test.di;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
publicclass BeanPostPrcessorImplimplements BeanPostProcessor {
// Bean实例化之前进行的处理
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("对象" + beanName + "开始实例化");
return bean;
}
// Bean实例化之后进行的处理
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("对象" + beanName + "实例化完成");
return bean;
}
}
只要将这个BeanPostProcessor接口的实现定义到容器中就可以了,如下所示:
<beanclass="com.spring.test.di.BeanPostPrcessorImpl"/>
测试代码如下:
package com.spring.test.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
publicclass TestMain {
/**
*@paramargs
*/
publicstaticvoid main(String[] args)throws Exception {
//得到ApplicationContext对象
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"applicationContext.xml");
//得到Bean
ctx.getBean("logic");
}
}
运行以上测试程序,可以看到控制台打印结果:
对象logic开始实例化
对象logic实例化完成
BeanPostProcessor的作用域是容器级的,它只和所在容器有关。如果你在容器中定义了BeanPostProcessor,它仅仅对此容器中的bean进行后置。它不会对定义在另一个容器中的bean进行任何处理。
注意的一点:
BeanFactory
和ApplicationContext
对待bean后置处理器稍有不同。ApplicationContext
会自动检测在配置文件中实现了BeanPostProcessor
接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它。部署一个后置处理器同部署其他的bean并没有什么区别。而使用BeanFactory
实现的时候,bean 后置处理器必须通过下面类似的代码显式地去注册:
BeanPostPrcessorImpl beanPostProcessor =new BeanPostPrcessorImpl();
Resource resource = new FileSystemResource("applicationContext.xml");
ConfigurableBeanFactory factory = new XmlBeanFactory(resource);
factory.addBeanPostProcessor(beanPostProcessor);
factory.getBean("logic");
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring的BeanPostProcessor接口实现Demo
- Spring BeanPostProcessor接口的使用
- Spring中的BeanPostProcessor接口
- Spring之BeanPostProcessor接口
- spring BeanPostProcessor接口
- dubbo接口address从diamond获取按spring的BeanPostProcessor代理实现
- 简单设置Win7操作系统有效保护视力
- 调用SignTool进行签名 VC++
- 递归下降法实现计算表达式
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- MySQL 修改phpmyadmin中mysql root的空改为新密码后,如何从phpmyadmin可登录
- Spring 的 BeanPostProcessor接口实现
- ubuntu 获取mysql.h文件时遇到问题的解决
- log4j输出多个自定义日志文件
- Objective-C语法property详解
- UML的时序图
- C++ 函数
- showModalDialog参数使用
- Objective-C语法之KVC的使用
- apache mina开发同步通信客户端