why Spring basic @Autowired is not working?



I'm new in Spring. But trying basic stuff. According to theory I should work, it is not working. I have 2 same beans with different id. I should be able to @Autowired with unique id @Qualifier("PersonBean2"). But it give error. I have no idea what is wrong where. Please inform me? Thanks!


Where is config springBeans.xml :-



<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/GAf8ZW">

<bean

class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>


<bean id="customer" class="com.mkyong.common.Customer" >
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>

<bean id="PersonBean1" class="com.mkyong.common.Person">
<property name="name" value="mkyong1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean>

<bean id="PersonBean2" class="com.mkyong.common.Person">
<property name="name" value="mkyong2" />
<property name="address" value="address 2" />
<property name="age" value="28" />
</bean>

</beans>


Customer.java:-



public class Customer {

@Autowired
@Qualifier("PersonBean2")
private Person person;
private int type;
private String action;
}


Person.java:-



public class Person {
private String name;
private String address;
private int age;
}


All setter and getter removed.


Test app.java:-



public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");

Customer cust = (Customer) context.getBean("customer");
System.out.println(cust);
}
}


Error:-



Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error
creating bean with name 'customer': Autowiring of fields failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field:
private
.mkyong.common.Person com.mkyong.common.Customer.person; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of
type
[com.mkyong.common.Person] is defined: expected single matching bean but found 2:

[PersonBean1, PersonBean2]

No comments:

Post a Comment