繁体   English   中英

如何告诉Spring忽略二传手?

[英]How do I tell Spring to ignore a setter?

我有一个带设置器和几个@Autowired字段的bean foo 通过设置器,我定义了在运行时使用哪个验证器。

我的问题:我也在Spring中定义了可用的验证器。

这意味着:尝试实例化foo ,我得到一个错误,即有多个实现IValidator bean,Spring无法确定使用哪个bean来调用我的setter。 咄。

有没有办法告诉Spring“忽略此设置器”?

[编辑]代码非常简单:

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;
    }
}

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>

抛出: UnsatisfiedDependencyException: Error creating bean with name 'bean' ... expected single matching bean but found 2: [optional1, optional2]

您可以在OptionalBean成员上使用@Qualifier

@Autowired
@Qualifier("optional1")  // or optional2
private OptionalBean optional;

或在二传手上:

@Autowired
@Qualifier("optional1")  // or optional2
public void setOptional( OptionalBean optional ) {
    this.optional = optional;
}

从XML文件中删除default-autowire="byType"

在这种情况下,将仅使用注释来对bean进行连线,因此只有标有@Autowired setter才会被Spring调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM