如何将jdbiFactory DAO注入Dropwizard命令中? [英] How do you inject jdbiFactory DAOs into a Dropwizard Command?

查看:166
本文介绍了如何将jdbiFactory DAO注入Dropwizard命令中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 Dropwizard ,我正在尝试创建

I'm starting to work with Dropwizard and I'm trying to create a Command that requires to use the database. If someone is wondering why I'd want to do that, I can provide good reasons, but this is not the point of my question anyway. It's about dependency inversion and Service initialization and run phases in Dropwizard.

Dropwizard鼓励使用其 DbiFactory来构建DBI实例,但是要获得一个实例,您需要一个实例和/或数据库配置:

Dropwizard encourages to use its DbiFactory to build DBI instances but in order to get one, you need an Environment instance and/or the database configuration:

public class ConsoleService extends Service<ConsoleConfiguration> {

  public static void main(String... args) throws Exception {
    new ConsoleService().run(args);
  }

  @Override
  public void initialize(Bootstrap<ConsoleConfiguration> bootstrap) {
    bootstrap.setName("console");
    bootstrap.addCommand(new InsertSomeDataCommand(/** Some deps should be here **/));
  }

  @Override
  public void run(ConsoleConfiguration config, Environment environment) throws ClassNotFoundException {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, config.getDatabaseConfiguration(), "postgresql");
    // This is the dependency I'd want to inject up there
    final SomeDAO dao = jdbi.onDemand(SomeDAO.class); 
  }
}

如您所见,您已经在run()方法中对服务及其环境进行了配置,但是需要在initialize()方法中将命令添加到服务的引导程序中.

As you can see, you have the configuration for your Service and its Environment in its run() method, but commands need to be added to the Service's bootstrap in its initialize() method.

到目前为止,我已经能够通过扩展 ConfiguredCommand ,并在其run()方法内创建DBI实例,但这是一个错误的设计,因为依赖关系应为注入到对象中,而不是在内部创建.

So far, I've been able to achieve this by extending ConfiguredCommand in my Commands and creating DBI instances inside their run() methods, but this is a bad design, because dependencies should be injected into the object instead of creating them inside.

我更愿意通过其构造函数注入DAO或我的命令的任何其他依赖关系,但是这对我来说目前似乎是不可能的,因为当我需要创建和创建服务时,Environment和配置在服务初始化中不可用.将它们添加到其引导程序.

I'd prefer to inject DAOs or any other dependencies of my Commands through their constructor, but this seems currently impossible to me, as the Environment and the configuration are not accesible in Service initialization, when I need to create and add them to its bootstrap.

有人知道如何实现这一目标吗?

Does anyone know how to achieve this?

推荐答案

可以使用 查看全文

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