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

家住魔仙堡 提交于 2019-12-23 07:26:56

问题


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?


回答1:


@Configuration
public class ApplicationConfiguration {

    @Autowired
    private ConfigurableBeanFactory beanFactory;

    @PostConstruct
    public void registerServices() {
        beanFactory.registerSingleton("service...", new NNNService());
        ... 
    }
}


来源:https://stackoverflow.com/questions/36260500/how-to-register-multiple-beans-using-single-bean-annotated-method-or-similar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!