Search code examples
javaguicedropwizard

How to get String from config.yml file in Dropwizard resource?


I want to geta String in my Dropwizard config.yml and access it from a resource class.

I have added the class to the configuration

public class DropwizardBackendConfiguration extends Configuration {

  @NotEmpty
  private String uploadFileLocation;

  @JsonProperty
  public String getUploadFileLocation() {
    return uploadFileLocation;
  }

  @JsonProperty
  public void setUploadFileLocation(String uploadFileLocation) {
    this.uploadFileLocation = uploadFileLocation;
  }

}

I am able to get the content in the run method

 public void run(
      final DropwizardBackendConfiguration configuration, final Environment environment) {
...
 System.out.println(configuration.getUploadFileLocation());


}

But how can I get this value in my resource class.


Solution

  • If you want to use the complete DropwizardBackendConfiguration or just the uploadFileLocation in a Jersey Resource, you will have to pass it as a constructor argument.

    The Getting Started guide illustrates this with the HelloWorldResource. In this example there are two constructor arguments:

    public HelloWorldResource(String template, String defaultName)
    

    An instance of this class is registered in the run method:

    @Override
    public void run(HelloWorldConfiguration configuration,
                    Environment environment) {
        final HelloWorldResource resource = new HelloWorldResource(
            configuration.getTemplate(),
            configuration.getDefaultName()
        );
        environment.jersey().register(resource);
    }
    

    Do something similar using your configuration and your resource class.