我正在尝试为 Dropwizard 创建一个计划作业,该作业每分钟运行一次并查询数据库中的值。
为此,我需要在initialize()舞台上注册一些 DAO 和服务,如下所示:
@Override
public void initialize(final Bootstrap<KMDServiceConfiguration> bootstrap) {
//JDBI
final DBIFactory factory = new DBIFactory();
final DateTimeArgumentFactory dateTimeFactory = new DateTimeArgumentFactory();
final DBI jdbi = factory
.build(environment, config.getDataSourceFactory(), "kmd");
jdbi.registerArgumentFactory(dateTimeFactory);
//DAOs
final UserDao userDao = jdbi.onDemand(UserDao.class);
final NotificationDao notificationDao = jdbi.onDemand(NotificationDao.class);
//Domain services
final UserService userService = new UserServiceImpl(userDao);
final NotificationService notificationService = new NotificationServiceImpl(notificationDao);
final MessageService messageService = new MessageServiceImpl(userService, notificationService);
final Job worker= new MessageWorker(messageService);
bootstrap.addBundle(new JobsBundle(worker));
Run Code Online (Sandbox Code Playgroud)
JDBI 需要 Dropwizardenvironment和配置对象。
是否可以在这个阶段访问这些以便正确设置我的依赖项?
您应该能够通过 DW Application 类中的“run”方法初始化作业,该方法可以访问配置和环境属性。我已经整理了一个简单的项目来展示这一点,但这就是 run 方法的样子:
@Override
public void run(SOQ49638642Configuration configuration, Environment environment) throws Exception {
final DBI dbi = (new DBIFactory()).build(environment, configuration.getDataSourceFactory(), "kmd");
final SOQ49638642Job soq49638642Job = new SOQ49638642Job(new SOQ49638642Service(dbi.onDemand(SOQ49638642Dao.class)));
final JobsBundle jobsBundle = new JobsBundle(soq49638642Job);
jobsBundle.run(configuration, environment);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,不可能在“初始化”阶段获取这些对象。您还可以查看 DW 的 Guice 集成,例如dropwizard-guicey,它为 DW 中的捆绑包和模块的 DI 提供了很好的机制。
| 归档时间: |
|
| 查看次数: |
1905 次 |
| 最近记录: |