Java 读取配置文件Web方案

1.新建类SystemInit.java

public class SystemInit implements ServletContextListener
{
/**
* 日志
*/
private static final Log log = LogFactory.getLog(SystemInit.class);

/**
* Servlet上下文
*/
private ServletContext context;

private static Configuration config;

/**
* 初始化方法
*/
public void init()
{
log.info("Init System ...... ");

try
{

// Constants.getAbsolutePath() == context.getRealPath("/")
// config.properties路径(例:D:\Program Files\tomcat6.0\webapps\pc\WEB-INF\classes\config.properties)
String configPath = context.getRealPath("/") + "WEB-INF"
+ File.separator + "classes" + File.separator
+ "config.properties";

PropertiesConfiguration properties = new PropertiesConfiguration(
configPath);

config = new Configuration(properties);

// 初始化系统路径
config.setContextPath(context.getContextPath());

// 初始化绝对路径
config.setAbsolutePath(context.getRealPath("/"));
}
catch (Exception ex)
{
log.error("System init fail catch Exception!", ex);
throw new RuntimeException("System init fail,Exception "
+ ex.getClass(), ex);
}

log.info("Init System end ...... ");
}

/**
* 销毁上下文
* @param servletcontextevent
*/
public void contextDestroyed(ServletContextEvent servletcontextevent)
{

}

/**
* 初始化上下文
* @param servletcontextevent
*/
public void contextInitialized(ServletContextEvent servletcontextevent)
{
context = servletcontextevent.getServletContext();

init();
}

/**
* 读取配置
* @return 配置
*/
public static Configuration getConfig()
{
return config;
}

/**
* 重新加载配置文件(对外调用提供更新)
*/
public void reload()
{
init();
}

}

2.新建Configuration.java

/**
* config.properties配置数据对象
*
* @author hpli/025415
* @version [版本号, 2012-3-19]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class Configuration
{
// context path
private String contextPath = "";

// 绝对路径
private String absolutePath = "";

// config配置Map集合
private Map<String, String> configMap;

public Configuration(PropertiesConfiguration properties)
{
// 初始化
configMap = new HashMap<String, String>();

// 获取config.properties所有key
Iterator iterator = properties.getKeys();

// 循环遍历设值
while (iterator.hasNext())
{
String key = (String)iterator.next();

configMap.put(key, properties.getString(key));
}

}

public String getContextPath()
{
return contextPath;
}

public void setContextPath(String contextPath)
{
this.contextPath = contextPath;
}

public String getAbsolutePath()
{
return absolutePath;
}

public void setAbsolutePath(String absolutePath)
{
this.absolutePath = absolutePath;
}

public Map<String, String> getConfigMap()
{
return configMap;
}

public void setConfigMap(Map<String, String> configMap)
{
this.configMap = configMap;
}
}

3.配置web.xml

添加监听

<listener>
<listener-class>com.huawei.virest.common.SystemInit</listener-class>
</listener>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值