Spring - 以编程方式生成一组bean [英] Spring - Programmatically generate a set of beans

查看:119
本文介绍了Spring - 以编程方式生成一组bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dropwizard应用程序需要为配置列表中的每个配置生成十几个bean。像健康检查,石英调度程序等等。

I have a Dropwizard application that needs to generate a dozen or so beans for each of the configs in a configuration list. Things like health checks, quartz schedulers, etc.

这样的事情:

@Component
class MyModule {
    @Inject
    private MyConfiguration configuration;

    @Bean
    @Lazy
    public QuartzModule quartzModule() {
        return new QuartzModule(quartzConfiguration());
    }


    @Bean
    @Lazy
    public QuartzConfiguration quartzConfiguration() {
        return this.configuration.getQuartzConfiguration();
    }

    @Bean
    @Lazy
    public HealthCheck healthCheck() throws SchedulerException {
        return this.quartzModule().quartzHealthCheck();
    }
}

我有多个MyConfiguration实例,所有需要像bean一样的bean这个。
现在我必须复制并粘贴这些定义并为每个新配置重命名。

I have multiple instances of MyConfiguration that all need beans like this. Right now I have to copy and paste these definitions and rename them for each new configuration.

我可以以某种方式迭代我的配置类并生成一组每个bean的bean定义?

Can I somehow iterate over my configuration classes and generate a set of bean definitions for each one?

我可以使用子类化解决方案或类型安全的任何东西,而不会让我复制并粘贴相同的代码并重命名方法我必须添加一项新服务。

I would be fine with a subclassing solution or anything that is type safe without making me copy and paste the same code and rename the methods ever time I have to add a new service.

编辑:我应该补充一点,我有其他依赖这些bean的组件(他们注入 Collection< HealthCheck> ; 例如。)

I should add that I have other components that depend on these beans (they inject Collection<HealthCheck> for example.)

推荐答案

我能想出的最佳方法是包装我的所有Quartz配置和调度程序都在1 uber bean中并手动连接,然后重构代码以使用uber bean接口。

The "best" approach I could come up with was to wrap all of my Quartz configuration and schedulers in 1 uber bean and wire it all up manually, then refactor the code to work with the uber bean interface.

uber bean创建所有我在PostConstruct中需要的对象,并实现ApplicationContextAware,以便它可以自动连接它们。它并不理想,但它是我能想到的最好的。

The uber bean creates all the objects that I need in its PostConstruct, and implements ApplicationContextAware so it can auto-wire them. It's not ideal, but it was the best I could come up with.

Spring没有一种以类型安全的方式动态添加bean的好方法。

Spring simply does not have a good way to dynamically add beans in a typesafe way.

这篇关于Spring - 以编程方式生成一组bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆