GuiceApplicationBuilder

GuiceApplicationBuilder

在Play的JUnit测试中! 2.6.25在IntelliJ中执行的应用程序,我试图将测试config:Config注入由Guice创建的app:Application中。但是app:Application不包含注入的配置。我究竟做错了什么?

Config config = ConfigFactory.parseFile(new File("test.conf")).resolve();
// myapp.key resolved to "value"
String value = config.getString("myapp.key");
GuiceApplicationBuilder guiceApplicationBuilder = new GuiceApplicationBuilder();
guiceApplicationBuilder.withConfigLoader(environment -> ConfigFactory.load(config));
Application app = guiceApplicationBuilder.build();
// why myapp.key cannot be resolved?
app.config().getString("myapp.key");


test.conf

myapp.key = value


也尝试过(没有成功):

guiceApplicationBuilder.loadConfig(config);
guiceApplicationBuilder.configure(config);

最佳答案

实际上,您正在丢弃具有自定义配置加载器的Application Builder,因为该构建器是不可变的数据结构。像这样做:

GuiceApplicationBuilder guiceApplicationBuilder = new GuiceApplicationBuilder()
  .withConfigLoader(environment -> ConfigFactory.load(config));


或简单地

GuiceApplicationBuilder guiceApplicationBuilder = new GuiceApplicationBuilder()
  .configure(config);


查看方法的签名时,您会注意到它们全部返回(一个新值!)GuiceApplicationBuilder

09-08 00:45