Search code examples
javaspringdependency-injectionjavabeansautowired

Autowiring a bean based on a property


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.


Solution

  • Apart from the newer feature of bean profiles, you can also take advantage of FactoryBean which instantiate a bean at the time of access. The idea is to inject the FactoryBean with the bean types (e.g. fqcn.BeanA or fqcn.BeanB). Then factory bean will return the bean factory to instantiate the correct type of the bean that you may need. The configuration of FactoryBean then can take advantage of properties coming from a resource bundle.