您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

问题在于资源文件(通常是您放入的文件src/main/resources)会出现在WEB-INF/classeswar文件的子目录中。

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

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

它仍然不能 可靠地 工作(想到JWS),因为您正在使用Action该类中的类加载器,而该类加载器在您尝试读取的jar / war中不存在。

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

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

由于掌握给定类的类加载器通常需要您事先加载该类,因此一个技巧是将虚拟类放入仅包含资源(例如properties文件)的jar中。假设您在jar文件中具有以下结构:

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

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

org/example/properties/Anchor.class
org/example/properties/a.properties
org/example/properties/b.properties
org/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);

这是一种更强大的方法

其他 2022/1/1 18:14:53 有686人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶