Reputation: 2308
I have 2 beans configured for a class so that I can configure the class with two different data layer implementations. What I'm wondering is if there is a pattern or best practice for selecting between the two different beans in my code. I know without Spring, the Factory pattern would be commonly used for this, but it seems a bit redundant being as beans are retrieved from Spring via a factory.
Upvotes: 0
Views: 2208
Reputation: 128829
There's no problem having a Factory within a Factory. It happens all the time in Spring, in fact. I'd say that sounds like a good approach here. Your data storage factory would be a Spring bean and be injected with the two different implementations, which are also beans. The job of the factory is to choose between them based on some input.
Upvotes: 1
Reputation: 340733
Declare both beans and mark one as primary. You can either use:
<bean primary="true" ...
in XML configuration or:
@Primary
@Bean
In @Configuration
approach. Spring will prefer primary beans when performing autowiring. Reference documentation.
Upvotes: 0