如何在Web应用程序中读取属性文件? [英] How to read properties file in web application?

查看:182
本文介绍了如何在Web应用程序中读取属性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

属性文件位置是 WEB-INF / classes / auth.properties

我不能使用JSF-具体方式(使用ExternalContext),因为我需要服务模块中的属性文件,它不依赖于Web模块。

I cannot use JSF-specific ways (with ExternalContext) because I need properties file in a service module which doesn't have a dependency on a web-module.

我已经尝试过

MyService.class.getClassLoader().getResourceAsStream("/WEB-INF/classes/auth.properties");

但它返回 null

我也尝试用 FileInputStream 读取它,但它需要完整的路径,这是不可接受的。

I've also tried to read it with FileInputStream but it requires the full path what is unacceptable.

任何想法?

推荐答案

几个笔记:


  1. 您应该更喜欢 ClassLoader 。 com / javase / 6 / docs / api / java / lang / Thread.html#getContextClassLoader%28%29rel =noreferrer> Thread#getContextClassLoader()

  1. You should prefer the ClassLoader as returned by Thread#getContextClassLoader().

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

这将返回可以访问所有资源的最基本的类加载器。 Class#getClassLoader()只返回有问题的类的(子)类加载器,它本身可能无法访问所需的资源。它总是在具有单个类加载器的环境中工作,但并不总是在具有复杂的类加载器层次结构的环境中工作,如webapps。

This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

/ WEB-INF 文件夹不在类路径的根目录中。 / WEB-INF / classes 文件夹是。所以你需要加载相对于它的属性文件。

The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.

classLoader.getResourceAsStream("/auth.properties");

如果您选择使用 Thread#getContextClassLoader(),删除前导 /

If you opt for using the Thread#getContextClassLoader(), remove the leading /.

特定于JSF的 ExternalContext#getResourceAsStream() 使用 ServletContext #getResourceAsStream() 引擎盖下只返回资源来自webcontent( / WEB-INF 文件夹所在的位置),而不是来自类路径。

The JSF-specific ExternalContext#getResourceAsStream() which uses ServletContext#getResourceAsStream() "under the hoods" only returns resources from the webcontent (there where the /WEB-INF folder is sitting), not from the classpath.

这篇关于如何在Web应用程序中读取属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆