Spring @Configuration classes, how to configure multiple instances of the same bean passing different parameters

4.9k views Asked by At

I have a Spring Java Configuration class that defines a bean inside, e.g.:

@Configuration
public class SomeConfig{

    private String someProperty;  

    public SomeConfig(String someProperty){
        this.someProperty=someProperty;
    }

    @Bean
    public SomeBean someBean(){
        SomeBean s = new SomeBean(someProperty);
        return s;    
    }
}

I need to have several instances of SomeBean, each of them configured with a different someProperty value.

  1. In a Spring Boot application is it possible to @Import the same class multiple times? SELF-ANSWERED: If you import the same @Configuration class, it will override the existing one.
  2. How can something like this be done with Spring Java Config?

UPDATE:

In XML I can do:

<bean class="x.y.z.SomeBean">
    <constructor-arg value="1"/>
</bean>
<bean class="x.y.z.SomeBean">
    <constructor-arg value="2"/>
</bean>

I am looking for an equivalent with Java Config

2

There are 2 answers

0
codependent On BEST ANSWER

I just had to use another @Configuration class that defined as many SomeConfig beans as needed:

@Configuration
public class ApplicationConfig{

    @Bean
    public SomeConfig someConfig1(){
        return new SomeConfig("1");
    }

    @Bean
    public SomeConfig someConfig2(){
        return new SomeConfig("2"); 
    }
}
2
mokarakaya On
@Configuration
public class SomeConfig{

    private String someProperty;  

    @Bean
    public OtherBean otherBeanOne(){
        OtherBean otherBean = new OhterBean();
        otherBean.setSomeBean(someBean("property1"));
        return otherBean;    
    }


    @Bean
    public OtherBean otherBeanTwo(){
        OtherBean otherBean = new OhterBean();
        otherBean.setSomeBean(someBean("property2"));
        return otherBean;    
    }

    @Bean
    public SomeBean someBean(String someProperty){
        SomeBean s = new SomeBean(someProperty);
        return s;    
    }


}