Search code examples
javaspringjavabeans

Spring bean autowiring based on property


I want to specify in property file, which bean will be autowired.
I found the solutions but all of them are using @Profile annotation, which means that they are based on specified profile, not specified property.

I did it in that way:

@Configuration
public class WebServiceFactory {
    @Value("${webservice}")
    private String webService;
    @Lazy
    @Autowired
    private GraphQLService graphQLService;
    @Lazy
    @Autowired
    private RestService restService;

    @Primary
    @Bean
    WebService getWebService() {
        switch (webService) {
            case "graphQlService":
                return graphQLService;
            case "restService":
                return restService;
            default:
                throw new UnsupportedOperationException("Not supported web service.");
        }
    }
}

Bean type I want to autowire is interface WebService, GraphQLService and RestService are it's implementations.
Is there any better way to do this?


Solution

  • You can do this using the normal configuration of Spring.

    class A{
     B bBean;
     ...//setters/getters here.
    }
    
    class B{}
    

    You can have a configuration file (It also can be a configuration class)

    <bean id = "a" class = "A">
          <property name="bBean" ref="b"/>     
       </bean>
    
    <bean id = "b" class = "B">   
       </bean>
    

    The bBean configuration can be in a different file, so you can import it from you classpath. Instead of using a property file you use a configuration file in the classpath o systemfile. If B is a different implementation then you modify your config file with the right class.