All previous answers use fairly direct use of spring DI. However, it is also possible to use a ServiceLocatorFactoryBean to create a factory without specifying any bean in the factory. First define the interface for the factory:
public interface MyFactory { Strategy get(String type); }
Then in your application:
@Configuration public class AppConfiguration { @Autowired private BeanFactory beanFactory; public ServiceLocatorFactoryBean myFactoryLocator() { final ServiceLocatorFactoryBean locator = new ServiceLocatorFactoryBean(); locator.setServiceLocatorInterface(MyFactory.class); locator.setBeanFactory(beanFactory); return locator; } @Bean public MyFactory myFactory() { final ServiceLocatorFactoryBean locator = myFactoryLocator(); locator.afterPropertiesSet(); return (MyFactory) locator.getObject(); } }
Now you can define a bean (using the @Service, @Component, or @Bean annotation) that implements / extends and automatically registers with MyFactory bean and can be created using
myFactory.get("beanName");
The best part is you can register the bean strategy as lazy and with different areas.
source share