简体   繁体   English

如何在Dropwizard中的资源中使用配置字符串和DAO

[英]How to use the config string and DAO in a resource in Dropwizard

I want to use a String from my config.yml and inject some DAO with guice in a resource. 我想从我的config.yml中使用一个String,并使用guice在资源中注入一些DAO。 Consider the following code example 考虑下面的代码示例

@Path("/upload")
@Produces(MediaType.APPLICATION_JSON)
public class UploadResource {

  private static String UPLOAD_PATH;

  public UploadResource(String uploadPath) {
    this.UPLOAD_PATH = uploadPath;
  }
}

I have added a the config.yml parameter in my constructor and used the following command to add the string in the application class 我在构造函数中添加了config.yml参数,并使用以下命令在应用程序类中添加了字符串

final UploadResource uploadResource = new UploadResource(
configuration.getUploadFileLocation());
environment.jersey().register(uploadResource);

Usually I would inject some Dao as follows 通常我会如下注入一些刀

@Produces(MediaType.APPLICATION_JSON)
public class UploadResource {

  private final SomeDao someDao;

  @Inject
  public UploadResource(SomeDao someDao) {
    this.someDao = someDao;
  }
}

but since my constructor has already an string entry. 但是由于我的构造函数已经有一个字符串条目。 how would I handle this elegantly with Dropwizard? 如何使用Dropwizard优雅地处理此问题? simple extending the arguments seems to be unclean. 简单扩展参数似乎是不干净的。

So if you are using Dropwizard with Guice and would like to use some string in from the config.yml you need to do the following 因此,如果您在Guice中使用Dropwizard,并且想在config.yml使用一些字符串,则需要执行以下操作

to the resource you 到你的资源

@Path("/upload")
@Produces(MediaType.APPLICATION_JSON)
public class UploadResource {

  private final FileDao fileDao;
  private final String uploadPath;

  @Inject
  public UploadResource(FileDao fileDao, @Named("{someName}") String uploadPath) {
    this.fileDao = fileDao;
    this.uploadPath = uploadPath;
  }

}

and in the application class you need to bind a constant as follows 在应用程序类中,您需要按如下方式绑定常量

@Override
  public void run(
      final BackendConfiguration configuration,
      final Environment environment) {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {

                bindConstant().annotatedWith(Names.named("{someName}"))
                    .to(configuration.getUploadFileLocation());
              }
            });

Make sure you implemented the method getUploadFileLocation as discribed by lutz from this post here 请确保你实施的方法getUploadFileLocation从这个帖子discribed由卢茨这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM