Search code examples
javaspringspring-ioc

Spring: Using @Configuration to dynamically return a Bean


Suppose you need to dynamically (at runtime) get an instance of a subtype of a given type.

How would you accomplish that using Spring IoC?


Solution

  • You can also use @Profile to achieve similar functionality in a more declarative way.

    @Configuration
    @Profile("default")
    public class TypeAConfig {
        @Bean
        public Type getType() {
            return new TypeA();
        }
    }
    
    @Configuration
    @Profile("otherProfile")
    public class TypeBConfig() {
        @Bean
        public Type getType() {
            return new TypeB();
        }
    }
    
    @Configuration
    public class SysConfig {
        @Autowired
        Type type;       
    
        @Bean Type getType() {
            return type;
        }
    }
    

    You can then control which implementation to use by specifying the profiles that Spring should activate, e.g. with the spring.profiles.active system property. More information in the JavaDoc for Profile