Search code examples
springspring-mvcspring-bootspring-java-config

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


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


Solution

  • 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"); 
        }
    }