Maven插件生成的资源文件无法在OSGi bundle中读取
解决OSGi Bundle中无法读取git.properties的问题
第一步:修正git-commit-id-plugin的文件生成路径
你当前的generateGitPropertiesFilename配置多嵌套了一层/classes,导致文件在jar中的路径是classes/git.properties,不在类路径根目录下,类加载器无法直接定位。
修改配置如下:
<plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> <executions> <execution> <goals> <goal>revision</goal> </goals> </execution> </executions> <configuration> <dotGitDirectory>${project.basedir}/../.git</dotGitDirectory> <generateGitPropertiesFile>true</generateGitPropertiesFile> <!-- 修正路径:直接输出到outputDirectory(即target/classes)根目录 --> <generateGitPropertiesFilename> ${project.build.outputDirectory}/git.properties </generateGitPropertiesFilename> <includeOnlyProperties> <includeOnlyProperty>^git.build.(time|version)$</includeOnlyProperty> <includeOnlyProperty>^git.commit.id.(abbrev|full)$</includeOnlyProperty> </includeOnlyProperties> <commitIdGenerationMode>full</commitIdGenerationMode> </configuration> </plugin>
修改后生成的git.properties会直接放在jar的类路径根目录(/git.properties)。
第二步:确保maven-bundle-plugin正确包含资源
maven-bundle-plugin默认会将target/classes下的所有文件打包到bundle中,但如果自定义了<resources>或<instructions>,需确认没有排除该文件。
如果你的maven-bundle-plugin配置中有<resources>节点,确保显式包含git.properties:
<plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <!-- 其他指令 --> <Include-Resource> {maven-resources}, git.properties </Include-Resource> </instructions> </configuration> </plugin>
若无自定义<resources>,默认配置即可,无需额外添加。
第三步:使用OSGi兼容的方式读取资源
OSGi环境中不能通过文件系统路径读取资源,必须通过类加载器获取:
方式1:通过当前类的类加载器读取
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("git.properties")) { if (inputStream != null) { Properties gitProps = new Properties(); gitProps.load(inputStream); // 读取示例:获取短版本提交ID String commitId = gitProps.getProperty("git.commit.id.abbrev"); } else { // 资源未找到的处理逻辑 } } catch (IOException e) { // 异常处理逻辑 }
方式2:通过上下文类加载器读取
如果在非组件类(如工具类)中读取,可使用上下文类加载器:
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("git.properties")) { // 读取逻辑同上 } catch (IOException e) { // 异常处理逻辑 }
第四步:验证MANIFEST.MF配置
打包后检查bundle的MANIFEST.MF文件,确保:
Bundle-ClassPath包含.(当前目录),例如:Bundle-ClassPath: .- 没有
Exclude-Resource规则排除git.properties
若Bundle-ClassPath被自定义,需确保包含资源所在路径(此处为.,因文件在根目录)。
内容的提问来源于stack exchange,提问作者dschulten
相关产品推荐
相关产品推荐

