我有两个类Student和Address,它们分别实现了IStudent和IAddress接口。 Student类与Address类有关系。这就是我宣布它的参考成员的原因。
public class Student implements IStudent {
private String code;
private String name;
@Autowired
private IAddress address;
@Override
public String getCode() {
return this.code;
}
@Override
public String getName() {
return this.name;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public IAddress getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
我有地址类
public class Address implements IAddress{
private String city;
private String pinCode;
private String houseNo;
private String roadName;
@Override
public String getCity() {
return this.city;
}
@Override
public String getPinCode() {
return this.pinCode;
}
@Override
public String getHouseNo() {
return this.houseNo;
}
@Override
public String getRoadName() {
return this.roadName;
}
public void setCity(String city) {
this.city = city;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setRoadName(String roadName) {
this.roadName = roadName;
}
}
在我的applicationContext.xml文件中,我编写了以下bean定义
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
</bean>
<bean id="addressbean" class="main.Address">
<property name="houseNo" value="119/2"></property>
<property name="roadName" value="South Avenue"></property>
<property name="city" value="Delhi"></property>
<property name="pinCode" value="110005"></property>
</bean>
</beans>
当我在初始化bean之后检查了Student对象时,名称和代码已经使用setter方法分配。但是地址没有分配。因此它显示地址的空值。我用@Autowired注释标记了地址。你能帮忙吗?
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) factory.getBean("studentbean");
System.out.println(student.getAddress());
答案 0 :(得分:1)
您需要明确连接到Address not IAddress,因为CI只知道地址,如果您要连线
@Autowired
private Address address;
或者你需要定义一个带有IAddress类型的bean,但是确保你没有多个实现,或者spring会混淆,如果你有多个实现使用可以使用限定符来清除歧义
答案 1 :(得分:-1)
这整个例子有点奇怪但是你可以摆脱@Autowired注释并使用下面的bean配置;
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
<property name="address" >
<ref local="addressbean"/>
</property>
</bean>