【发布时间】: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