Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register multiple beans using single @Bean-annotated 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 which differ only in their names, return types and arguments for the crateService method call. I would like to make this class similar to 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 it possible in Spring?

like image 981
Victor Avatar asked Mar 28 '16 10:03

Victor


1 Answers

@Configuration
public class ApplicationConfiguration {

    @Autowired
    private ConfigurableBeanFactory beanFactory;

    @PostConstruct
    public void registerServices() {
        beanFactory.registerSingleton("service...", new NNNService());
        ... 
    }
}
like image 105
user6291866 Avatar answered Sep 22 '22 13:09

user6291866