0

我刚刚开始使用 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;
    }
}

弹簧配置:

<beans>
  <bean id="customer" class="org.springinaction.Customer" autowire="byName" />

  <bean id="address" class="org.springinaction.Address">
    <property name="addressline" value="bangalore" />
  </bean>
</beans>

客户测试.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这个...任何人都可以帮我这个,以便正确地自动连接

4

3 回答 3

2

自动布线查找的“名称”是从 setter 方法的名称派生的 JavaBean 属性的名称,因此您的 Customer 类有一个名为n(来自setN方法)的属性,私有字段被命名的事实address是无关紧要的.

您需要使用 id 定义一个合适的 bean,n或者将 Customer 中的 getter 和 setter 更改为getAddresssetAddress匹配现有addressbean 的名称。

于 2013-01-26T20:23:28.440 回答
1

将您的 getter 和 setter 更改为:

public Address getAddress() {
    return address;
}

public void setAddress(Address n) {
    this.address = n;
}

根据Java bean 约定,您的 getter 和 setter 必须具有名称get(或 set)+ 首字母大写的属性名称

于 2013-01-26T20:20:01.667 回答
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;
....

有超过 1 个地址 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;
....
于 2013-01-28T16:30:08.140 回答