public class MyBean implements BeanPostProcessor {
public void say(){
System.out.printf("hello");
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/spring-config.xml"});
MyBean myBean = context.getBean(MyBean.class);
myBean.say();
}
}
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<bean id="myBean" class="com.alibaba.dubbo.demo.MyBean" />
运行结果:
[05/02/18 05:08:53:053 CST] main INFO support.ClassPathXmlApplicationContext: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6d9c638: startup date [Mon Feb 05 17:08:53 CST 2018]; root of context hierarchy
[05/02/18 05:08:53:053 CST] main INFO xml.XmlBeanDefinitionReader: Loading XML bean definitions from class path resource [spring/spring-config.xml]
inithello
Process finished with exit code 0
期待的市BeanPostProcessor里的before和after方法被调用,但实际没有。有谁知道为什么吗?
BeanPostProcessor类是为了让创建其他类的时候进行创建前后的一些操作,你这么写一般是不会调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法的。原因就是。在容器初始化定义的bean创建之前,容器会自己去查找所有的beanPostProcessor进行创建,你自定义的类,由于是实现了BeanPostProcessor接口,因此这时候会进行BeanPostProcessor的创建和注册,源码中,在注册BeanPostProcessor会进行getBean操作,即创建自定义的bean。由于默认的是单例模式,因此后面再次进行获取就不会再次调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法,因为已经放入了spring缓存,直接获取,不需要实例,因此没有调用。如果你真的想使用的时候调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法,将你的bean设置为原型模式(prototype),这样每次调用都会创建,因此初始化容器之后每次都会调用的。
https://www.cnblogs.com/soundcode/p/6476732.html
搞明白了,原来作为BeanPostProcessor的实现类,是不会作为普通bean传入这些回调方法处理的。随便加些其他的bean都会传进去进行后处理加工,但自己本身不会。