我有一个部署在 wildfly 中的应用程序,打包在一个 war 文件中。我需要从部署目录下 war 文件外的 xml 文件加载一些要在我的 java 代码中使用的属性。
deployments
-- myapplication.war
-- myproperties.xml
我的 java 代码如何访问这个属性? 请指教。
谢谢..
最佳答案
结合 CDI OWNER做得很好。
更新
Inject Java Properties in Java EE Using CDI在 github 上提供介绍和一些示例代码.作为下一步,您可以将属性部分委托(delegate)给所有者。
创建注解类型定义Config.java:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface Config {
}
获取 ConfigProducer.java:
@Produces
@Config
public Configuration produce(InjectionPoint ip) {
if (config == null) {
config = ConfigFactory.create(Configuration.class);
}
return config;
}
生产者必须由自己或另一个带有 @Startup @Singleton
注解的 bean 实例化。
设置您的所有者支持的 Configuration.java
@HotReload(type = HotReloadType.SYNC)
@LoadPolicy(LoadType.MERGE)
@Sources("file:${config.filepath}/config.properties")
public interface Configuration extends Config, Reloadable, Mutable, Accessible {
@Key("server.http.port")
int port();
@Key("server.host.name")
String hostname();
}
在一些bean中注入(inject)并使用配置:
@Stateless
public class SomeBean {
@Inject
@Config
private Configuration config;
}
不要忘记wildfly的standalone.xml中的路径配置:
<system-properties>
<property name="config.filepath" value="/your/path/"/>
</system-properties>
关于java - Wildfly 加载系统属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27386358/