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

查看:32
本文介绍了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.现在我必须复制并粘贴这些定义,并为每个新配置重命名它们.

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 定义?

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.)

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天全站免登陆