问题
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