Play 2.5.X:对象 Play 中的当前方法已弃用:这是对应用程序的静态引用,请改用 DI

Play 2.5.X: method current in object Play is deprecated: This is a static reference to application, use DI instead

我是 PlayFramework 新手。

请给我一个如何从我的视图访问配置参数的示例。我正在使用 PlayFramework 2.5.3

旧方法(不推荐使用@current):

@current.configuration.getString("environment.param")

新方式(据我了解,应该注入配置):

我知道如何从控制器访问它。

@Inject() (val messagesApi: MessagesApi, configuration: Configuration)

我如何使用它?

遗憾的是,您对此无能为力。当 DI 被引入 Play 时就是这样,关于模板的讨论不多。一种可能的解决方案是:

  1. 在控制器中注入Configuration
  2. 将其作为 implicit 发送到您的 view/template

    class Application @Inject() (implicit val config: Configuration) extends Controller {
    
        def index = Action {
            Ok(views.html.index("foo"))
        }
    }
    

您的模板将如下所示:

@(myParam1: Any)(implicit config: Configuration)
<h2>Some HTML here @myParam1 @config.getString("environment.param")</h2>

我完全知道这在某种程度上违背了 DI 的目的,但这就是现在的情况。

在 java 中,要在 play 2.5 中读取 application.conf,您应该在控制器中注入配置,如下所示:

public class HomeController extends Controller {
private Configuration configuration;

@Inject
public HomeController(Configuration configuration) {
    this.configuration = configuration;
}

public Result index() {
    String value = configuration.getString("key");
    System.out.println("value of key is " + key);
    return ok(value);
}

}

因为配置是具体的 class,所以不需要在模块 class 中绑定它。

另请参阅此讨论: DI for java in play 2.5

看起来 2.6.x 或 twirl 1.2.0

可能会有变化

https://github.com/playframework/twirl/pull/100

https://www.playframework.com/documentation/2.6.x/ScalaTemplates#Template-constructor