我刚开始使用Spring并尝试通过名称进行自动装配 这是我的代码
地址类:
package org.springinaction;
public class Address {
private String addressline;
public String getAddressline() {
return addressline;
}
public void setAddressline(String addressline) {
this.addressline = addressline;
}
}
客户类:
package org.springinaction;
public class Customer {
private Address address;
public Address getN() {
return address;
}
public void setN(Address n) {
this.address = n;
}
}
Spring cofiguration:
<beans>
<bean id="customer" class="org.springinaction.Customer" autowire="byName" />
<bean id="address" class="org.springinaction.Address">
<property name="addressline" value="bangalore" />
</bean>
</beans>
CustomerTest.java
package org.springinaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CustomerTest {
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext("SpringInAction.xml");
Customer cust=(Customer)context.getBean("customer");
System.out.println(cust.getN());
}
}
当我尝试按名称进行自动装配时,如果属性名称与名称匹配则会自动装配。但在我的情况下,它不会发生。 它给了我null这个...任何人都可以帮助我这个,以便它正确地自动装配
答案 0 :(得分:2)
自动布线查找的“名称”是从setter方法的名称派生的JavaBean属性的名称,因此您的Customer类具有名为n
的属性(来自setN
方法),私有字段名为address
的事实无关紧要。
您需要定义一个ID为n
的合适bean,或者将Customer中的getter和setter更改为getAddress
和setAddress
,以匹配现有{{1}的名称豆。
答案 1 :(得分:1)
将你的getter和setter更改为:
public Address getAddress() {
return address;
}
public void setAddress(Address n) {
this.address = n;
}
根据Java beans convention,您的getter和setter必须具有名称获取(或设置)+首字母大写的属性名称。
答案 2 :(得分:0)
如果您只想让您的Customer bean注入您的Address bean,那么只需使用@Autowired注释,就不需要setter / getter:
<context:annotation-config /> // EDIT - think this required for autowiring
<bean id="customer" class="org.springinaction.Customer"/>
<bean id="address" class="org.springinaction.Address">
<property name="addressline" value="bangalore" />
</bean>
public class Customer {
@Autowired
Address address;
....
有多个地址bean吗?然后使用@Qualifier:
<bean id="customer" class="org.springinaction.Customer"/>
<bean id="work-address" class="org.springinaction.Address">
<property name="addressline" value="bangalore" />
</bean>
<bean id="home-address" class="org.springinaction.Address">
<property name="addressline" value="bangalore" />
</bean>
public class Customer {
@Autowired
@Qualifier ( value = "work-address" )
Address workAddress;
@Autowired
@Qualifier ( value = "home-address" )
Address homeAddress;
....