Reputation: 21358
I am trying to run a Spring example using BeanPostProcessor
.
Below is the bean post processor
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;
}
}
here, is the spring configuration file
<bean id="car" class="com.core.Car" >
<property name="wheel" value="four" />
</bean>
<bean class="com.core.DisplayNamePostProcessor"></bean>
Here, is my bean class
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);
}
}
On running the above main method, I am getting the below exception
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)
Can someone please let me know what Ia m doing wrong and how to resolve this exception. Also, what is the root cause of it?
Upvotes: 0
Views: 300
Reputation: 280179
Any BeanPostProcessor
beans you declare will be picked up by the ApplicationContext
bean factory and used. Your implementation does this
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessBeforeInitialization for bean "+beanName);
return this;
}
Instead of doing anything to the target bean
, it simply returns itself. It thus overrides all beans it processes with a DisplayNamePostProcessor
bean.
Upvotes: 1