我正在尝试使用BeanPostProcessor
运行Spring示例。
下面是bean后处理器
public class DisplayNamePostProcessor implements BeanPostProcessor{
DisplayNamePostProcessor(){
System.out.println("DisplayNamePostProcessor instantiated");
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessBeforeInitialization for bean "+beanName);
return this;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInitialization for bean "+beanName);
return this;
}
}
这里是弹簧配置文件
<bean id="car" class="com.core.Car" >
<property name="wheel" value="four" />
</bean>
<bean class="com.core.DisplayNamePostProcessor"></bean>
这是我的bean类
public class Car {
private String wheel;
public String getWheel() {
return wheel;
}
public void setWheel(String wheel) {
this.wheel = wheel;
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("application context loaded");
Car car = context.getBean("car", Car.class);
}
}
在运行上面的主要方法时,我得到以下异常
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'car' must be of type [com.core.Car], but was actually of type [com.core.DisplayNamePostProcessor]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:361)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
有人可以让我知道我做错了什么以及如何解决这个异常。另外,它的根本原因是什么?
答案 0 :(得分:1)
您声明的任何BeanPostProcessor
bean将被ApplicationContext
bean工厂选中并使用。你的实现做到了这个
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessBeforeInitialization for bean "+beanName);
return this;
}
而不是对目标bean
做任何事情,它只是返回自己。因此它覆盖了它使用DisplayNamePostProcessor
bean处理的所有bean。