我正在尝试按如下方式注释 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>
我遇到了这个错误:
No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies
如何配置此 bean 以正确调用 set
方法?
最佳答案
用@Autowired
就可以了在具有任意数量参数的方法上。唯一的问题是应用程序上下文必须能够识别您要为每个参数注入(inject)的内容。
错误消息中的投诉非常清楚:您没有在应用程序上下文中定义唯一的 String bean。
您的特定示例的解决方案是使用 @Value
每个参数的注释:
@Autowired
set(@Value("${user.name:anonymous}") String name, @Value("${user.age:30}") int age)
这将使用 PropertyPlaceholderConfigurer
在您的上下文中定义以解析这些属性,如果未定义这些属性,将回退到提供的默认值。
如果你想注入(inject)在你的上下文中定义为 beans 的对象,你只需要确保每个参数只有一个匹配的 bean:
@Autowired
set(SomeUniqueService myService, @Qualifier("aParticularBean") SomeBean someBean)
在上面的例子中,假设只有一个 SomeUniqueService
的实例在应用程序上下文中,但可能有多个 SomeBean
实例——但是,只有其中一个具有 bean id“aParticularBean”。
作为最后的说明,@Autowired
的这种用法最适合构造函数,因为在构造对象后很少需要将属性设置为批量。
编辑:
我在写完答案后注意到了你的 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 -->
这样,容器将检测到所有需要注入(inject)的东西并采取相应的行动。 XML <property/>
element 只能用于调用 java bean setter(只接受一个参数)。
此外,您可以使用类似 @Component
的原型(prototype)来注释您的类(或 @Service
或其他)然后使用 <context:component-scan/>
;这将消除在 XML 中声明每个单独的 bean 的需要。
关于java - @Autowired 带有任意数量参数的任意方法名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353158/