手头开发项目为 M,是一个提供JSON接口,以及通过HttpInvoker提供接口服务的项目。因为部署到 JBoss 上,以 war 包的形式,所以如果里面 java 文件,需要获取 properties 文件的话,大致有以下几种方式:
1.最常规的,在 class 加载时,将 properties 加载到内存中。
private static Properties prop = new Properties();
staic{
try{
prop.load(new BufferedInputStream(new FileInputStream(System.getProperty("user.dir")+"/WEB-INF/config/cc.properties")));
}catcht(IOException e){
e.printStackTrace();
logger.error("");
}
}</span>
问题:使用Eclipse中的debug,直接运行项目到JBoss中,System.getProperty(user.dir) 获取的路径为:D:\TravelSkySoft\jboss-5.1.0.GA\bin --本地JBoss的安装目录。
实际这样是根本获取不到 cc.properties 的。
解决:临时解决方案,将cc.properties 直接放入 D:\TravelSkySoft\jboss-5.1.0.GA\bin,这样就可以正常运行以及使用了,但额外配置是个有风险的动作。
2.参照部署到 JBoss 上的 web 项目,里面的获取方式为:
Properties pp = new Properties();
HttpServletRequest request = getRequest();
ServletContext servletContext = request.getSession().getServletContext();
String rootPath = servletContext.getRealPath("/");
try {
pp.load(new BufferedInputStream(new FileInputStream(rootPath + "WEB-INF/conf/cc.properties")));
} catch (IOException e) {
logger.error("价值配置文件:/config/cc.properties失败 !", e);
e.printStackTrace();
}
protected HttpServletRequest getRequest(){
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
问题:项目运行不了了,估计是跟此项目中没有实现 HandlerInterceptor 接口,也没有前端有关,这个方式就只能使用在web项目上应该。
3.最终的解决方法,在 M 项目启动之后,注意到项目最后加载的 system property : "M.root" 这个路径恰好是当前项目的部署成功的一个路径。注:M.root 是配置在 web.xml 中,webAppRootKey 中的值,这样必须在项目启动完毕后,加载才完毕。修改加载路径如下:
prop.load(new BufferedInputStream(new FileInputStream(System.getProperty("M.root")+"/WEB-INF/config/cc.properties")));
在prop使用时,在进行初始化,读取 cc.properties 。这样就不必再额外配置 properties 到JBoss中去。