问题
I am new to Play framework. I wanted to read a file which is in the conf folder. So I used Play.application().classloader().getResources("Data.json").nextElement().getFile()
But I got to know that play.Play is deprecated now. What can I use to read the file.
I read this article and can hardly understand what it says.
回答1:
Just inject the Application in the class where you need it. Supposing it is in a controller:
import play.Application;
import javax.inject.Inject;
import javax.inject.Provider;
class YourController extends Controller {
@Inject
Provider<Application> app;
public Result someMethod() {
// (...)
// File is placed in conf/Data.json
InputStrem is = app.get().classloader().getResourceAsStream("Data.json");
String json = new BufferedReader(new InputStreamReader(is))
.lines().collect(Collectors.joining("\n"));
return ok(json).as("application/json");
}
}
回答2:
The 2.5 migration article you read focuses on Play's migration from Global state to Dependency Injection as a means to wire dependencies - hence the removal of those static methods. If you don't really understand this yet, then do not worry.
Assuming this configuration entry (either in application.conf or another file imported into application .conf:-
my_conf_key = "some value"
Here is an example of looking up the configuration property using 2.5:-
import play.api._
import play.api.mvc._
import javax.inject.Inject
class TestConf @Inject() (conf: Configuration) extends Controller {
def config = Action {
Ok(conf.underlying.getString("my_conf_key"))
}
}
prints:-
some value
回答3:
Salem gave you an example for a specific use-case. In this post you can find more detailed explanation of dependency injection in Play.
And this post is about migration to Play 2.5.
I hope this will help you.
回答4:
Injecting Application
didn't work, so I had to inject Environment
and then call environment.resource("resource.xsd");
Example:
import javax.inject.Inject;
public class ExampleResource extends Controller{
private final Environment environment;
@Inject
public ExampleResource(Environment environment){
this.environment = environment;
}
public void readResourceAsStream() {
InputStream resource = environment.resourceAsStream("data.xsd");
// Do what you want with the stream here
}
public void readResource(){
URL resource = environment.resource("data.xsd");
}
}
Play Documentation about Application interface: https://www.playframework.com/documentation/2.6.9/api/java/play/Application.html
来源:https://stackoverflow.com/questions/39101033/what-is-the-alternative-for-play-application