在Spring启动应用程序中读取Manifest文件

问题描述 投票:0回答:2

我们使用Spring-boot来构建微服务。在我的项目设置中,我们有一个名为platform-b​​oot的常见maven模块,主类带有注释SpringBootApplication

如果我们想要创建一个新的微服务(比如Service-1),我们只需添加一个platform-b​​oot模块的依赖项,并在pom.xml中提供主类路径,我们就可以了。

问题是当我尝试通过在依赖模块中的'main-class'中编写代码来读取Service-1的Manifest.MF文件时。它读取platform-b​​oot的Manifest.MF文件。

下面是我在主类中阅读Manifest.MF文件的代码片段。

MyMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
//Returns the path of MyMain.class which is nested jar

请建议一种方法来阅读Service-1的Manifest.MF文件。

PS:我想阅读Maifest.MF文件以获得Implementation-Version。请建议是否有任何其他方式获得它。

java maven spring-boot manifest manifest.mf
2个回答
1
投票

嗨,请你详细说明阅读你的服务的必要性 - 1manifest.mf?

如果您只想将service1作为父公共模块中的依赖项并且不应该与service1可引导应用程序冲突,则可以通过spring-boot-maven-plugin中的exec配置生成两个jar。


1
投票

我找到了两种方法来解决这个问题:

  1. 我们可以使用maven-dependency-plugin在执行阶段prepare-package时解压缩子jar。这个插件会将我的platform-b​​oot jar中的类文件解压缩到我的Service-1。 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.0.2</version> <executions> <execution> <id>unpack</id> <phase>prepare-package</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>my.platform</groupId> <artifactId>platform-boot</artifactId> <type>jar</type> <overWrite>false</overWrite> <outputDirectory>${project.build.directory}/classes</outputDirectory> <includes>**/*.class,**/*.xml,**/*.text</includes> <excludes>**/*test.class</excludes> </artifactItem> </artifactItems> <includes>**/*.java, **/*.text</includes> <excludes>**/*.properties</excludes> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>true</overWriteSnapshots> </configuration> </execution> </executions> </plugin>
  2. 第二种方法更简单,在spring-boot-maven-plugin中添加一个目标build-info。这将在您的META-INF文件夹中写入文件build-info.properties,并可通过以下代码访问。 <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>build-info</goal> <goal>repackage</goal> </goals> </execution> </executions> </plugin> 在main方法中,您可以使用已在ApplicationContext中注册的BuildProperties bean获取此信息。 ApplicationContext ctx = SpringApplication.run(Application.class, args); BuildProperties properties = ctx.getBean(BuildProperties.class); 事实上,Spring-actuator也使用这个BuildProperties来获取有助于监控的构建信息。
© www.soinside.com 2019 - 2024. All rights reserved.