为什么BeanPostProcessor的回调函数没被调用

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),这样每次调用都会创建,因此初始化容器之后每次都会调用的。

 一般ApplicationContext会自动检查是否在定义文件中有实现了BeanPostProcessor接口的类,如果有的话,Spring容器会在每个Bean(其他的Bean)被初始化之前和初始化之后,分别调用实现了BeanPostProcessor接口的类的postProcessAfterInitialization()方法和postProcessBeforeInitialization()方法,对Bean进行相关操作。
但是在楼主的定义文件中,只定义了一个bean,而且还是实现了BeanPostProcessor接口的Bean,我觉得问题应该是出现在这里,建议楼主把现有的Bean分为两个Bean试试,就是一个Bean用来实现BeanPostProcessor接口,然后另一个Bean用来配合实现了BeanPostProcessor接口的Bean。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值