栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在多模块项目中读取属性文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在多模块项目中读取属性文件

问题在于资源文件(通常是您放入的文件

src/main/resources
)会出现在
WEB-INF/classes
war文件的子目录中。

现在,如果您尝试将其设置

propfilename
为:

String propfilename = "WEB-INF/classes/com/xyz/comp/prop.properties"

它仍然不能 可靠地 工作(想到JWS),因为您正在使用

Action
该类中的类加载器,而该类加载器在您尝试读取的jar / war中不存在。

这样做的正确方法是引入第三个模块/依赖性,在其中放置共享资源并使其他模块依赖于此。

对于JWS(Java Web Start)和其他使用类似类加载策略的框架,可以使用“锚点”方法。

用于类加载的Anchor方法

由于掌握给定类的类加载器通常需要您事先加载该类,因此一个技巧是将虚拟类放入仅包含资源(例如

properties
文件)的jar中。假设您在jar文件中具有以下结构:

org/example/properties/a.propertiesorg/example/properties/b.propertiesorg/example/properties/c.properties

只需在jar中放入一个虚拟类,使其看起来像这样:

org/example/properties/Anchor.classorg/example/properties/a.propertiesorg/example/properties/b.propertiesorg/example/properties/c.properties

然后,从其他代码中,您现在可以执行此操作,并确保类加载按预期进行:

Properties properties = new Properties();String propFile = "org/example/properties/a.properties";ClassLoader classLoader = Anchor.class.getClassLoader();InputStream propStream = classLoader.getResourceAsStream(propFile );properties.load(propStream);

这是一种更强大的方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466845.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号