How to register multiple beans using a single @Bean -name method (or similar) in Spring?

I have a class similar to the following:

@Configuration public class ApplicationConfiguration { private <T> T createService(Class<T> serviceInterface) { // implementation omitted } @Bean public FooService fooService() { return createService(FooService.class); } @Bean public BarService barService() { return createService(BarService.class); } ... } 

The problem is that there are too many @Bean -annotated methods that differ only in their names, return types and arguments for calling the crateService method. I would like to make this class look like the following:

 @Configuration public class ApplicationConfiguration { private static final Class<?>[] SERVICE_INTERFACES = { FooSerivce.class, BarService.class, ...}; private <T> T createService(Class<T> serviceInterface) { // implementation omitted } @Beans // whatever public Map<String, Object> serviceBeans() { Map<String, Object> result = ... for (Class<?> serviceInterface : SERVICE_INTERFACES) { result.put(/* calculated bean name */, createService(serviceInterface)); } return result; } } 

Is this possible in Spring?

+6
source share
1 answer
 @Configuration public class ApplicationConfiguration { @Autowired private ConfigurableBeanFactory beanFactory; @PostConstruct public void registerServices() { beanFactory.registerSingleton("service...", new NNNService()); ... } } 
+2
source

All Articles