Nathan Merrill
Nathan Merrill

Reputation: 8396

Spring: How to inject any one of 4 beans into another bean

I have an object Bar which requires object Foo for its constructor (where Foo is an interface type). Both Bar and Foo are beans.

I would like to @Autowire a Bar, and define in the annotation which Foo to use, without having creating a different @Bean for each type of Foo.

@Configuration
public class Config {
    @Bean
    public BarClass getBarClass(){
        return new BarClass(fooObject);//Where do I get this object from?
    }
    ...more BarClass beans...
    @Bean(name = "type1")
    public FooClass getFooClass1(){
        return new ConcreteFooClass();
    }
    @Bean(name = "type2")
    public FooClass getFooClass2(){
        return new SecondConcreteFooClass();
    }
    ...more FooClass beans...
}

@ContextConfiguration(classes=Config.class)
public class myClass {
    @Autowire
    BarClass b;//Somehow define here that you are supposed to use "type1" Foo to construct this BarClass
}

Upvotes: 3

Views: 551

Answers (2)

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22516

Try this, it's not tested ...

 public class BarFactory
    {   
       public static Bar createBar(Foo foo)
       {
          Bar bar= new Bar();
          bar.setFoo(foo);
          return bar;
       }
    }

<bean id="bar1" class="my.company.BarFactory"
                          factory-method="createBar">
    <constructor-arg ref="foo1"/>
</bean>

<bean id="bar2" class="my.company.BarFactory"
                          factory-method="createBar">
    <constructor-arg ref="foo2"/>
</bean>

Java Config:

@Configuration
public class Conf {

   //define foo1 and 2

    @Bean
    public Bar getBar1() {
        return BarFactory.createBar(foo1)
    }

    @Bean
    public Bar getBar2() {
        return BarFactory.createBar(foo2)
    }

}

Upvotes: 2

NimChimpsky
NimChimpsky

Reputation: 47300

You can,t do this without specifying a qualifier on bar class. But that should not be a problem have two bars with qualifiers, which have there relevant constructor args

Upvotes: 0

Related Questions