原理:
Spring容器提供了很好的扩展性,除了可以与各种第三方框架良好的整合外,其IoC容器也允许开发者进行扩展,这种扩展甚至无需实现BeanFactory或ApplicationContext接口,允许两个后处理器对IoC容器进行扩展:
Bean后处理器:这种处理器会对容器中的Bean进行后处理,对Bean的功能进行额外的加强。
容器后处理器:这种处理器对IoC容器进行后处理,用于增强容器的功能。
①Bean后处理器:
Bean后处理器是一种特殊的Bean,这种特殊的Bean并不对外提供服务,它甚至可以没有id\属性。它主要负责对容器中的其他Bean执行后处理。
后处理器必须实现BeanPostProcessor接口。此接口有两个方法:Object postProcessorBeforeInitialization(Object object,String name) Object postProcessorAfterInitialization(Object object,String name)
第一个参数是系统即将后处理的Bean的实例,第二个参数是该Bean实例的名称。
实例:
1.chinese类:
package com.huawei.proxy;
public class Chinese
{
private String name="hehe";
public void setName(String name){
System.out.println("Spring执行注入.......");
this.name=name;
}
public void init(){
System.out.println(name);
System.out.println("初始化工作init");
}
}
2.LogBeanPostProcessor类:
package com.huawei.proxy;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class LogBeanPostProcessor implements BeanPostProcessor
{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
System.out.println("正在处理"+beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
System.out.println("已经处理完成"+beanName);
return bean;
}
}
3.MyBeanPostProcessor类:
package com.huawei.proxy;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor
{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//bean 是每一个实体bean的对象,beanName 是每一个实体bean的对象名称
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if(bean instanceof Chinese){
((Chinese)bean).setName(name);
System.out.println("**** "+beanName);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
}
4.运行主类:Demo1:
package com.huawei.proxy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Demo1
{
public static void main(String[] args)
{
ApplicationContext context=new FileSystemXmlApplicationContext("classpath:spring/applicationContext.xml");
Chinese demoService=(Chinese) context.getBean("chinese");
demoService.init();
}
}
运行结果为:
正在处理org.springframework.context.event.internalEventListenerProcessor
已经处理完成org.springframework.context.event.internalEventListenerProcessor
正在处理org.springframework.context.event.internalEventListenerFactory
已经处理完成org.springframework.context.event.internalEventListenerFactory
正在处理taskExecutor
已经处理完成taskExecutor
Spring执行注入.......
**** chinese
正在处理chinese
已经处理完成chinese
lili
初始化工作init
Process finished with exit code 0
由此可见LogBeanPostProcessor类和MyBeanPostProcessor类实现了BeanPostProcessor接口,所以所有bean在实例化之前和之后都会调用对应的方法的,由于MyBeanPostProcessor指定了,只有chinese类实例化的时候才会进入前方法,所以别的类不会进入MyBeanPostProcessor的类的前方法。