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

Jos*_*seA 4 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

配置文件:

<bean id="myBean" class="com.spring.examples.MyBean">
    <property name="name" value="Marie" />
    <property name="age" value="101" />
</bean>
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

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

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

Cos*_*atu 10

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

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

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

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

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

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

@Autowired
set(SomeUniqueService myService, @Qualifier("aParticularBean") SomeBean someBean)
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,假设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 -->
Run Code Online (Sandbox Code Playgroud)

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

此外,您可以使用类似@Component(@Service或任何)的刻板印象来注释您的类,然后使用<context:component-scan/>; 这将消除在XML中声明每个单独bean的需要.