@Autowired任何带有任意数量参数的方法名称

时间:2013-06-27 21:04:58

标签: java spring

我正在尝试按如下方式注释set方法:

package com.spring.examples;
public class MyBean
{
    private String name;
    private int age;

    @Autowired
    public void set(String name, int age)
    {
       this.name = name;
       this.age = age;
    }
}

配置文件:

<bean id="myBean" class="com.spring.examples.MyBean">
    <property name="name" value="Marie" />
    <property name="age" value="101" />
</bean>

我收到了这个错误:

  

没有为依赖项找到[java.lang.String]类型的限定bean:期望至少有1个符合条件的bean

如何配置此bean以正确调用set方法?

2 个答案:

答案 0 :(得分:10)

对具有任意数量参数的方法使用@Autowired是可以的。唯一的问题是应用程序上下文必须能够识别您要为每个参数注入的内容。

错误消息中的投诉非常清楚:您没有在应用程序上下文中定义的唯一String bean。

您的特定示例的解决方案是对每个参数使用@Value注释:

@Autowired
set(@Value("${user.name:anonymous}") String name, @Value("${user.age:30}") int age)

这将使用您的上下文中定义的PropertyPlaceholderConfigurer来解析这些属性,如果未定义这些属性,它将回退到提供的默认值。

如果要在上下文中注入定义为bean的对象,则只需要确保每个参数只有一个匹配的bean:

@Autowired
set(SomeUniqueService myService, @Qualifier("aParticularBean") SomeBean someBean)

在上面的例子中,假设应用程序上下文中只有SomeUniqueService的一个实例,但可能有几个SomeBean个实例 - 但是,只有其中一个实例有bean id“aParticularBean”。

作为最后一点,@Autowired的这种用法最适合构造函数,因为很少需要在构造对象后将属性设置为bulk。

编辑:

写完答案后我注意到了你的XML配置;它完全没用。如果您想使用注释,只需定义没有任何属性的bean,并确保在上下文中的某处声明<context:annotation-config/>

<context:annotation-config/>
<bean id="myBean" class="com.spring.examples.MyBean"/>
<!-- no properties needed since the annotations will be automatically detected and acted upon -->

这样,容器将检测需要注入的所有内容并采取相应措施。 XML <property/>元素只能用于调用java bean setter(只接受一个参数)。

此外,您可以使用@Component(或@Service或其他)等刻板印象来注释您的课程,然后使用<context:component-scan/>;这将消除以XML格式声明每个bean的需要。

答案 1 :(得分:0)

您还可以像这样定义StringInteger bean:

<bean id="name" class="java.lang.String">
  <constructor-arg value="Marie"/>
</bean>

<bean id="age" class="java.lang.Integer">
  <constructor-arg value="101"/>
</bean>

但我觉得这个简单案例很奇怪。我会选择两个安装员,如评论中所建议的那样:

package com.spring.examples;
public class MyBean
{
    private String name;
    private int age;

    public void setName(String name)
    {
       this.name = name;
    }

    public void setAge(int age)
    {
       this.age = age;
    }
}