Spring Boot:配置同一类的2个不同品种

时间:2016-07-10 21:55:15

标签: spring-boot

鉴于以下类,我想配置Composite类的2个实例,一个使用FooA,另一个使用FooB。

interface IFoo { }
class FooA implements IFoo { }

class FooB  implements IFoo {}

class Composite {

    private IFoo foo;
    public void setFoo(IFoo foo) {
        this.foo = foo;
    }  
}

在bean配置文件中,我执行此操作:

<bean id="fooA", class="FooA"/>
<bean id="fooB", class="FooB"/>
<bean id="compositeA" class="Composite">
    <property name="foo" value-ref="fooA"/>
</bean>

<bean id="compositeB" class="Composite">
    <property name="foo" value-ref="fooB"/>
</bean>

如何在Spring Boot中以类似的简洁方式完成此任务?

2 个答案:

答案 0 :(得分:1)

与我想象的完全相同,用@Configuration带注释的类代替bean xml文件

 @Configuration
 public class SpringConfig {

     @Bean
     @Qualifier("compositeA")
     public Composite compositeA() {
         Composite c = new Composite();
         c.setFoo(fooA());
         return c;             
     }

     @Bean
     @Qualifier("compositeB")
     public Composite compositeB() {
         Composite c = new Composite();
         c.setFoo(fooB());
         return c;
     }

     @Bean
     public FooA fooA() {
         return new FooA();   
     }

     @Bean
     public FooB fooB() {
         return new FooB();   
     }
 } 

答案 1 :(得分:0)

With the Qualifier annotation pointed out by stringy05, I've done the following. FooA and FooB don't need to be specified as Beans in the @Configuration file.

// FooA.java
@Component
public class FooA implements IFoo {}

// FooB.java
@Component
public class FooB implements IFoo {}


// Inside a class annotated as @Configuration
@Bean
public Composite compA(@Qualifier("fooA")IFoo foo) {
    Composite c= new Composite();
    c.setFoo(foo);
    return c;
}

@Bean
public Composite compB(@Qualifier("fooB")IFoo foo) {
    Composite c= new Composite();
    c.setFoo(foo);
    return c;
}

For additional brevity (which I should have done in the first place), I'll give Composite a constructor that takes IFoo as an argument, thus reducing both Bean method bodies to

return new Composite(foo);