简体   繁体   中英

How do I tell Spring to ignore a setter?

I have a bean foo which has a setter and a couple of @Autowired fields. With the setter, I define which validator to use at runtime.

My problem: I define the available validators in Spring, too.

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. Duh.

Is there a way to tell Spring "ignore this setter"?

[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 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]

You can use @Qualifier on the OptionalBean member:

@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.

In this case, only annotations will be used to wire the beans, and thus only setters marked with @Autowired will be called by Spring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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