[英]How do I tell Spring to ignore a setter?
I have a bean foo
which has a setter and a couple of @Autowired
fields. 我有一个带设置器和几个
@Autowired
字段的bean foo
。 With the setter, I define which validator to use at runtime. 通过设置器,我定义了在运行时使用哪个验证器。
My problem: I define the available validators in Spring, too. 我的问题:我也在Spring中定义了可用的验证器。
That means: As soon as I try to instantiate foo
, I get an error that there are several beans which implement IValidator
and Spring can't decide which one to use to call my setter. 这意味着:尝试实例化
foo
,我得到一个错误,即有多个实现IValidator
bean,Spring无法确定使用哪个bean来调用我的setter。 Duh. 咄。
Is there a way to tell Spring "ignore this setter"? 有没有办法告诉Spring“忽略此设置器”?
[EDIT] The code is really simple: [编辑]代码非常简单:
public class AutowireTestBean {
// Required bean without setter
@Autowired
private TestBean autowired;
public TestBean getAutowired() {
return autowired;
}
// Standard setter. If this bean is missing, nothing bad happens
private OptionalBean optional;
public void setOptional( OptionalBean optional ) {
this.optional = optional;
}
public OptionalBean getOptional() {
return optional;
}
}
The XML looks like this: XML如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-autowire="byType"
default-lazy-init="true">
<bean id="bean" class="AutowireTestBean" />
<bean id="autowired" class="TestBean" />
<bean id="optional1" class="OptionalBean" />
<bean id="optional2" class="OptionalBean" />
<context:annotation-config />
</beans>
This throws: UnsatisfiedDependencyException: Error creating bean with name 'bean' ... expected single matching bean but found 2: [optional1, optional2]
抛出:
UnsatisfiedDependencyException: Error creating bean with name 'bean' ... expected single matching bean but found 2: [optional1, optional2]
You can use @Qualifier
on the OptionalBean
member: 您可以在
OptionalBean
成员上使用@Qualifier
:
@Autowired
@Qualifier("optional1") // or optional2
private OptionalBean optional;
or on the setter: 或在二传手上:
@Autowired
@Qualifier("optional1") // or optional2
public void setOptional( OptionalBean optional ) {
this.optional = optional;
}
Remove default-autowire="byType"
from your XML file. 从XML文件中删除
default-autowire="byType"
。
In this case, only annotations will be used to wire the beans, and thus only setters marked with @Autowired
will be called by Spring. 在这种情况下,将仅使用注释来对bean进行连线,因此只有标有
@Autowired
setter才会被Spring调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.