spring BeanPostProcessor接口
来源:互联网 发布:中文版热力学模拟软件 编辑:程序博客网 时间:2024/05/22 11:59
如果我们需要在Spring容器完成Bean的实例化、配置和其它初始化后添加一些自己的逻辑处理,我们可以通过定义BeanPostProcessor接口实现。
解决:
package com.spring.supersoft.guanstudy;
public class BeanPostProcessorImpl implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("对象" + beanName + "开始实例化");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("对象" + beanName + "实例化完成");
return bean;
}
}
只要将这个BeanPostProcessor接口的实现定义到容器中就可以了,如下所示:
<bean class="com.spring.supersoft.guanstudy.BeanPostProcessorImpl"/>
测试代码如下:
public class Launcher {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// 得到ApplicationContext对象
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"applicationContext.xml");
// 得到Bean
ctx.getBean("good");
}
}
运行以上测试程序,可以看到控制台打印结果:
对象good开始实例化
对象good实例化完成
原理剖析:
BeanPostProcessor的作用域是容器级的,它只和所在容器有关;如果你在容器中定义了BeanPostProcessor,它仅仅对此容器中的bean进行后置。它不会对定义在另外一个容器中的bean进行任何处理。
另外,BeanFactory和ApplicationContext对BeanPostProcessor处理不同;
ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它;
部署一个BeanPostProcessor和部署其他普通bean没什么区别,只需要配置到xml文件中,如:(<bean class="com.spring.supersoft.guanstudy.BeanPostProcessorImpl"/>);
而使用BeanFactory实现的时候,BeanPostProcessor必须通过下面类似的代码显式地去注册:
BeanPostProcessorImpl beanPostProcessorImpl = new BeanPostProcessorImpl();
Resource resource = new FileSystemResource("applicationContext.xml");
ConfigurableBeanFactory factory = new XmlBeanFactory(resource);
factory.addBeanPostPostProcessor(beanPostProcessorImpl);
factory.getBean("good");
- Spring中的BeanPostProcessor接口
- Spring之BeanPostProcessor接口
- spring BeanPostProcessor接口
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- PASSION之Spring-BeanPostProcessor接口
- Spring 的 BeanPostProcessor接口实现
- spring源码解读:BeanPostProcessor接口
- Spring 的 BeanPostProcessor接口实现
- Spring 的 BeanPostProcessor接口实现
- Spring BeanPostProcessor接口的使用
- 一些优秀的 androidStudio开发插件
- Redis作者谈Redis应用场景
- mysql sql长度限制
- spring boot框架学习3-spring boot核心(2)
- 走格子
- spring BeanPostProcessor接口
- 文章标题
- 7. Python 结巴中文分词
- Java虚拟机体系结构由几部分组成?
- Ubuntu 16.04 安装 tensorflow
- 字符指针与字符数组真正的区别
- 通过spring实现javamail的那些事儿
- 使用PTGui用360度全景图制作Unity3D天空盒
- Grading of Gliomas by Using Radiomic Features on Multiple Magnetic Resonance Imaging (MRI) Sequences