【问题标题】:How do you inject jdbiFactory DAOs into a Dropwizard Command?如何将 jdbiFactory DAO 注入 Dropwizard 命令?
【发布时间】:2014-10-15 03:58:08
【问题描述】:

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

Dropwizard 鼓励使用它的 DbiFactory to build DBI instances,但要获得它,您需要一个 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() 方法中,但需要在其initialize() 方法中将命令添加到服务的引导程序中。

到目前为止,我已经能够通过在我的命令中扩展ConfiguredCommand 并在其run() 方法中创建DBI 实例来实现这一点,但这是一个糟糕的设计,因为dependencies should be injected into the object instead of creating them inside

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

有谁知道如何做到这一点?

【问题讨论】:

    标签: java dependency-injection dropwizard jdbi


    【解决方案1】:

    你能用EnvironmentCommand吗?

    【讨论】:

    • 谢谢!当我发布问题时,这并不存在......我认为:)
    【解决方案2】:

    这就是我在 Dropwizard 中使用 Guice 的方式。在你的 run() 方法中添加一行

    Guice.createInjector(new ConsoleModule());
    

    创建类 ConsoleModule

    public class ConsoleModule extends AbstractModule {
    
     public  ConsoleModule(ConsoleConfiguration consoleConfig)
     {
         this.consoleConfig = consoleConfig;
     }
    
     protected void configure()
    {
       bind(SomeDAO.class).to(SomeDAOImpl.class).in(Singleton.class)
      }
    }
    

    【讨论】:

    • 虽然这是我的问题的解决方案,但我想找到一个不需要像 Guice 这样的 DI 容器的解决方案。还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多