gpt4 book ai didi

java - 如何将 jdbiFactory DAO 注入(inject) Dropwizard 命令?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:18:36 25 4
gpt4 key购买 nike

我开始使用 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() 中将命令添加到服务的 Bootstrap 中 方法。

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

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

有人知道如何实现吗?

最佳答案

你能用EnvironmentCommand吗? ?

关于java - 如何将 jdbiFactory DAO 注入(inject) Dropwizard 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22319965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com