I have two beans, beanA and beanB, in my Spring config. Both of these beans implement the same interface. I have a class with an autowired field of the interface type (i.e. it will be populated with an instance of beanA or beanB).
Initially there was only one bean, so I simply used the @Autowired annotation and the field was populated. However, now there’s two potential beans that could be autowired. I want to autowire the bean based on the existence of a property in one of my .properties resources. Is there any elegant way to do this?
The solution I’m using now is to use the @Qualifier annotation on the autowired field to specify beanA and then make a check to see if the property exists in code. If it does, I reassign the field to an instance of beanB. It’s a very clunky way of doing it, so I’m looking for a better option.
Apart from the newer feature of bean profiles, you can also take advantage of
FactoryBeanwhich instantiate a bean at the time of access. The idea is to inject theFactoryBeanwith the bean types (e.g.fqcn.BeanAorfqcn.BeanB). Then factory bean will return the bean factory to instantiate the correct type of the bean that you may need. The configuration ofFactoryBeanthen can take advantage of properties coming from a resource bundle.