我想使用Java在Play Framework 2.3.8中实现特定于模式的配置。我知道这在Scala中是可以实现的:
import java.io.File
import play.api._
import com.typesafe.config.ConfigFactory
object Global extends GlobalSettings {
override def onLoadConfig(config: Configuration, path: File, classloader: ClassLoader, mode: Mode.Mode): Configuration = {
val modeSpecificConfig = config ++ Configuration(ConfigFactory.load(s"application.${mode.toString.toLowerCase}.conf"))
super.onLoadConfig(modeSpecificConfig, path, classloader, mode)
}
}
目前我设法在java中实现相同但我无法将typesafe-s ConfigFactory.load(modeSpecificConfigFile)
返回对象从com.typesafe.config.Config
强制转换为play.Configuration
:
@Override
public Configuration onLoadConfig(Configuration configuration, File file, ClassLoader classLoader, Mode mode) {
String modeSpecificConfigFile = "application." + mode.toString().toLowerCase() + ".conf";
Logger.debug("Loading mode specific configuration from: " + modeSpecificConfigFile);
Configuration modeSpecificConfig = ConfigFactory.load(modeSpecificConfigFile);
return super.onLoadConfig(modeSpecificConfig , file, classLoader);
}
谢谢!
答案 0 :(得分:1)
将其包装到play.Configuration
:
Configuration modeSpecificConfig = new play.Configuration(ConfigFactory.load(modeSpecificConfigFile));
答案 1 :(得分:0)
此解决方案在 Play 2.4.6 中无效,因为正如in docs所述: onLoadConfig已弃用。此方法不执行任何操作。相反,请在配置文件中指定配置或创建自己的ApplicationLoader(请参阅GuiceApplicationBuilder.loadConfig)。
因此,我实现了一个更简单的替代解决方案,一个自定义配置加载器,共享下面的示例代码。
首先,假设您已经在" application.conf"中拥有了所有参数
然后创建" application.prod.conf"对于PROD环境
和(可选)创建" application.dev.conf"对于DEV环境
示例 application.prod.conf
# include the main config file, aka make all common params usable
include "application.conf"
# PROD specific params, you can also override params from the included conf
param.for.prod.1 = "etc etc"
here.override.for.prod = "blabla"
可在您的应用中使用: ConfigManager.java
public class ConfigManager {
public static play.Configuration modeSpecificConfig = new play.Configuration(
ConfigFactory.load(
"application." + Play.mode().toString().toLowerCase() + ".conf"
)
);
}
现在可以在您的应用中访问特定于环境的参数,您可以使用ConfigManager获取任何参数,例如:
ConfigManager.modeSpecificConfig.getString("keyname");
ConfigManager.modeSpecificConfig.getInt("keyname2");