我写了一个小代码来检查Spring中的@Autowired注解,这是我的一段代码
public class Address
{
private String street;
private String City;
private String State;
private String Country;
/* getter setter here */
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer
{
private String name;
private Address address;
// other getter setter here
@Autowired
public void setAddress(Address address)
{
this.address = address;
}
}
和 springexample.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="address1" class="org.springexamples.Address">
<property name="street" value="vihar" />
<property name="city" value="dehradun" />
<property name="state" value="Uttarakhand" />
<property name="country" value="India" />
</bean>
<bean id="addres2" class="org.springexamples.Address">
<property name="street" value="triveni vihar" />
<property name="city" value="dehradun" />
<property name="state" value="Uttarakhand" />
<property name="country" value="India" />
</bean>
<bean id="customer" class="org.springexamples.Customer">
<property name="name" value="deepak" />
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
</beans>
和主班
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AutowiredQualifierTest
{
public static void main(String[] args)
{
ApplicationContext context= new ClassPathXmlApplicationContext("springexample.xml");
Customer cust = (Customer)context.getBean("customer");
System.out.println(cust.getName() + " " + cust.getAddress().getStreet());
}
}
理想情况下,它应该显示一个异常,因为存在两个相同类型的 bean,但是它使用 id="address1" 拾取 bean,所以我得到了这个 bean 行为。