繁体   English   中英

从包含的 jar 中读取属性文件

[英]Read properties file from included jar

我正在尝试创建读取属性文件的注释解析器。 结构如下所示:

 - annotationParserModule
    - declaration of interace
    - annotationParser

现在我的应用程序有这样的结构:

 - main
   - java
   - resources
      - .properties file

我通过 maven 包含 annotationParserModule,所以如果我没记错的话,jar fire 包含在我的项目中。

但是,我需要读取annotationParserModule提供的 jar 之外的属性文件,这样可能吗? 如果是这样,实现这一目标的正确方法是什么?

感谢帮助。

如果您要读取的资源包含在应用程序的类路径中(例如,在 jar 中、在WEB-INF/lib文件夹中、使用-cp传递给java命令的文件夹等),您可以读取该文件使用Class类的getResourceAsStream方法。

为您的案例提供一个示例,其中包含以下文件夹:

- main
   - java
   - resources
      - yourconfig.properties

在您的YourAnnotationParser代码中,您可以拥有:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("yourconfig.properties");

如果文件是嵌套的:

- main
   - java
   - resources
      - iamafolder
          - yourconfig.properties

所以:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("iamafolder/yourconfig.properties");

顺便说一句,这是一个非常简单的响应,代码适用于常见场景,它在幕后所做的事情比“读取 jar 外的文件”更复杂,但是要完全理解它,您需要查看 java 类加载器和类路径工作。

如果文件在 java 类路径之外,您可以使用File类或URL 1 来读取内容。

在 applicationcontext.xml 中,您可以添加 bean 以从 jar 中读取属性文件

<bean id="com.mybean"
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:/resource.properties</value>
        </list>
    </property>
</bean>

这个 id 将是对另一个 bean 的引用

<bean id="com.mybean1">
    class="com.dependent.jar.classname">
    <property name="properties" ref="com.mybean" />
</bean>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM