【发布时间】:2015-12-04 15:29:47
【问题描述】:
我的问题是关于 EAR 应用程序。我想知道一个模块中的类如何读取另一个模块中的属性文件。
我正在使用 Eclipse Luna 和 Wildfly 8.2.1。
在 Eclipse 中:
* 我有一个名为 MyEar 的“企业应用程序项目”。
* 我有一个名为 MyWeb 的“动态 Web 项目”,它是 MyEar 的一部分。
* 我有一个名为 MySrc 的“实用项目”,它是 MyEar 的一部分。
在 MyWeb 项目中,我有一个名为 app.properties 的属性文件,它位于 WEB-INF\classes 文件夹中:
DefaultMaximumBatchSize=1000
在 MySrc 项目中,我有一个名为AppProperties 的类,它在启动时将app.properties 文件读入Properties 对象:
package com.srh.config;
import java.io.InputStream;
import java.util.Properties;
public class AppProperties {
private static final Properties APP_PROPERTIES;
static {
InputStream inputStream = null;
APP_PROPERTIES = new Properties();
try {
inputStream = AppProperties.class.getResourceAsStream("/app.properties");
System.out.println("AppProperties: inputStream=" + inputStream);
if (inputStream != null) {
APP_PROPERTIES.load(inputStream);
}
} catch (Exception e) {
System.out.println("AppProperties: Exception occured; e=" + e);
}
}
public static String getValue(String propertyName) {
if (propertyName == null || propertyName.equalsIgnoreCase(""))
return null;
else
return APP_PROPERTIES.getProperty(propertyName);
}
}
在 MyWeb 项目中,我有一个名为 AppContextListener 的侦听器,我正在测试从 AppProperties 查找值:
package com.srh.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.srh.config.AppProperties;
@WebListener
public class AppContextListener implements ServletContextListener {
public AppContextListener() {
}
public void contextInitialized(ServletContextEvent arg0) {
String defaultMaxBatchSize = AppProperties.getValue("DefaultMaximumBatchSize");
System.out.println("AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=" + defaultMaxBatchSize);
}
public void contextDestroyed(ServletContextEvent arg0) {
}
}
当我将 EAR 应用程序部署到 Wildfly 时,Eclipse 将其部署为 MyEar.ear,其中包含以下文件:
lib\MySrc.jarMETA-INF\application.xmlMyWeb.war\META-INF\MANIFEST.MFMyWeb.war\WEB-INF\web.xmlMyWeb.war\WEB-INF\classes\app.propertiesMyWeb.war\WEB-INF\classes\com\srh\listener\AppContextListener.class
MySrc.jar 里面有这些文件:
com\srh\config\AppProperties.classMETA-INF\MANIFEST.MF
当我启动 Wildfly 时,我在 server.log 中得到这个输出:
AppProperties: inputStream=null
AppContextListener:contextInitialized(ServletContextEvent): defaultMaxBatchSize=null
那么模块MySrc如何读取模块MyWeb中的属性文件呢?
谢谢
【问题讨论】:
-
如果您在 JavaEE 环境中运行,通常最好不要使用这样的静态单例。他们很麻烦。了解 CDI 注入框架的工作原理,并改用
@Singleton-annotated 类。然后通过单例的构造函数提供初始化所需的属性。
标签: java jakarta-ee wildfly ear properties-file