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

旧城冷巷雨未停 提交于 2019-12-24 04:55:24

问题


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.


回答1:


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.




回答2:


It may be probably late but you this can be done by dropwizard-guice dependency, this library used Google guice for dependency injection using annotations to configure Java objects. As an extract from this article by Ricky Yim

You could can inject the properties into the resource like below

package com.github.codingricky;

import com.google.inject.Inject; 
import com.google.inject.name.Named;
import javax.ws.rs.GET; 
import javax.ws.rs.Path;

@Path("/hello")
public class HelloResource { 
   private final String message;

   @Inject
   public HelloResource(@Named("message") String message) {
      this.message = message;
   }

   @GET
   public String hello() {
      return message;
   }
}

These values are picked from your .yml configuration using modules,

public class ServerModule implements Module { 
   @Override
   public void configure(Binder binder) {
   }

   @Provides
   @Named("message")
   public String provideMessage(ServerConfiguration serverConfiguration) {
      return serverConfiguration.getMessage();
   }
}

Kindly look at the most recent library



来源:https://stackoverflow.com/questions/49771099/how-to-get-string-from-config-yml-file-in-dropwizard-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!