Search code examples
javaguicedropwizard

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. 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

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? simple extending the arguments seems to be unclean.


Solution

  • 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

    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