播放 2.5.3:使用依赖注入获取配置值 [英] Play 2.5.3: Using dependency injection to get configuration values
问题描述
我正在尝试将 Playframework 应用程序从 2.4 迁移到 2.5.3,但在从 application.conf
文件中获取值时遇到问题:
I'm trying to migrate a Playframework application from 2.4 to 2.5.3 and I have problems to get values from application.conf
file:
之前从 application.conf
获取值我所做的是:
Before to get a value of from application.conf
what I do was:
Play.application().configuration().getString("label")
现在,因为 Play.application()
已被弃用,我应该使用依赖注入.基于框架文档,我使用以下说明:
Now as Play.application()
is deprecated, I should use Dependency injection. Based on the framework documentation I use the following instructions:
- 定义导入:import
javax.inject.*;import play.Configuration;
- 定义类属性:
@Inject 私有配置配置;
- 在我的类上使用配置类属性
- Define import: import
javax.inject.*; import play.Configuration;
- Define class property:
@Inject private Configuration configuration;
- Use the configuration class property on my class
当我在控制器 Application.java
上按照这些说明操作时,它运行良好:
When I follow these instructions on my controller Application.java
it is working perfectly:
但是当我尝试在我的项目中的其他类对象上使用它时,依赖注入不起作用并且我总是得到一个 NullPointerException
.
But when I try to use it on an other class object from my project, the dependency injection is not working and I always get a NullPointerException
.
谁能举个例子告诉我如何使用依赖注入从 application.conf
获取值?
Can someone give me an example about how to get values from application.conf
using dependency Injection?
我尝试使用 DI 的 Java 代码的某些部分:
Some part of my java code where I try to use the DI:
import javax.inject.Inject;
import play.Configuration;
import play.Logger;
public class Zipper {
@Inject private Configuration configuration;
public void unZip(String zipFilePath) {
Logger.debug("Display : zipFilePath"+zipFilePath);
Logger.debug("before call parameter from application.conf");
Logger.debug("configuration.getString = "+configuration.getString("Unzipedfile.path"));
Logger.debug("aftercall parameter from application.conf");
}
}
而且我总是得到一个空指针异常,在 configuration.getString("Unzipedfile.path")
And I always get a null pointer exception, at the line with configuration.getString("Unzipedfile.path")
推荐答案
我把答案放在这里,为了帮助任何有同样问题的人
I put here the answer, in order to help anyone with the same issue
我的错误来自于我以前从调用类实例化 Zipper Java 类的方式.
My error came from the way i used to instantiate my Zipper java class from my calling class.
感谢 Igmar Palsenberg,他给了我答案:https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!topic/play-framework/uLFqTM9_Iy4
Thx to Igmar Palsenberg, he provided me the answer : https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!topic/play-framework/uLFqTM9_Iy4
我使用 Zipper zipTest = new Zipper(); 来实例化我的 Zipper 类,我必须使用 Zipper zipTest = injector.instanceOf(Zipper.class);
I used Zipper zipTest = new Zipper(); to instanciate my Zipper class and i have to use Zipper zipTest = injector.instanceOf(Zipper.class);
这篇关于播放 2.5.3:使用依赖注入获取配置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!