如何将jdbiFactory DAO注入Dropwizard命令?

gga*_*zor 9 java dependency-injection jdbi dropwizard

我开始使用Dropwizard,我正在尝试创建一个需要使用数据库的Command.如果有人想知道我为什么要这样做,我可以提供充分的理由,但无论如何这不是我的问题.它是关于Dropwizard中的依赖性反转和服务初始化以及运行阶段.

Dropwizard鼓励使用它的DbiFactory来构建DBI实例,但是为了得到一个,你需要一个Environment实例和/或数据库配置:

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 Code Online (Sandbox Code Playgroud)

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

到目前为止,我已经能够通过在我的命令中扩展ConfiguredCommandDBI在其run()方法中创建实例来实现这一点,但这是一个糟糕的设计,因为应该将依赖项注入到对象中而不是在其中创建它们.

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

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

Tri*_*tan 8

你能使用EnvironmentCommand吗?