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

问题描述

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

我不能使用 JSF 特定的方式(使用 ExternalContext),因为我需要在不依赖于网络模块的服务模块中的属性文件.

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. 您应该更喜欢 .

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

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

这将返回可以访问所有资源的最父类加载器.Class#getClassLoader() 将只返回相关类的(子)类加载器,该类加载器本身可能无法访问所需的资源.它始终适用于具有单个类加载器的环境,但并不总是适用于具有复杂类加载器层次结构(如 Web 应用程序)的环境.

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() under the hood"只返回来自 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 应用程序中读取属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:50