Play.application() 的替代方案是什么

What is the alternative for Play.application()

我是 Play 框架的新手。我想读取 conf 文件夹中的文件。所以我用了

Play.application().classloader().getResources("Data.json").nextElement().getFile()

但我知道 play.Play 现在已被弃用。我可以用什么来读取文件。 我读了 this 篇文章,但几乎看不懂它说的是什么。

您阅读的 2.5 迁移文章重点介绍了 Play 从全局状态到依赖注入的迁移,作为连接依赖项的一种方式 - 因此删除了那些静态方法。如果您还没有真正理解这一点,请不要担心。

假设此配置条目(在 application.conf 或导入应用程序 .conf 的另一个文件中:-

my_conf_key = "some value"

下面是使用 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"))
  }

}

打印:-

some value

只需将应用程序注入 class 您需要的地方。假设它在控制器中:

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");    
    }
}

Salem 为您提供了一个特定用例的示例。在此 post 中,您可以找到有关 Play 中依赖注入的更详细说明。

而这个 post 是关于迁移到 Play 2.5 的。

希望对您有所帮助。

注入Application没有用,所以我不得不注入Environment然后调用environment.resource("resource.xsd");

示例:

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");
     }
}

播放有关应用程序界面的文档: https://www.playframework.com/documentation/2.6.9/api/java/play/Application.html