您的位置:首页 > 编程语言 > Java开发

springboot源码分析1-springboot版本号获取

2017-11-24 14:49 501 查看
摘要:在使用springboot的时候,可能经常会忽略掉springboot的版本问题。本文我们看一下springboot jar包中定义的版本信息以及版本获取类。本文内容相对而言比较简单。

1.java中定义项目的版本

回想一下在java中如何定义项目的版本。这个比较简单,只需要在jar包增加MANIFEST.MF文件(根目录)并添加的如下内容即可:
Manifest-Version: 1.0
Implementation-Title: 分享牛
Implementation-Version: 1.1关于MANIFEST.MF文件的位置如下所示:

2.springboot中版本信息

同样,在springboot中spring-boot-2.0.0.M3.jar包中MANIFEST.MF定义了相关的版本信息,具体内容如下所示:
Manifest-Version: 1.0
Implementation-Title: Spring Boot
Implementation-Version: 2.0.0.M3
Built-By: bamboo
Specification-Vendor: Pivotal Software, Inc.
Specification-Title: Spring Boot
Implementation-Vendor-Id: org.springframework.boot
Created-By: Apache Maven 3.5.0
Build-Jdk: 1.8.0_121
Specification-Version: 2.0
Implementation-URL: http://projects.spring.io/spring-boot/ Implementation-Vendor: Pivotal Software, Inc.

3.springboot中版本信息的获取工具类

了解了上述的版本定义之后,我们就开始说明如何进行MANIFEST.MF中定义的版本信息值的获取,可能聪明的小伙伴就想到了,直接读取MANIFEST.MF文件并解析Implementation-Version属性不就可以了,当然可以使用这种方式,但是我们可以直接利用Springboot框架本身提供的一些的类进行操作了,这个类就是SpringBootVersion类,该类的定义如下所示:

public final class SpringBootVersion {

private SpringBootVersion() {
}

/**
* Return the full version string of the present Spring Boot codebase, or {@code null}
* if it cannot be determined.
* @return the version of Spring Boot or {@code null}
* @see Package#getImplementationVersion()
*/
public static String getVersion() {
Package pkg = SpringBootVersion.class.getPackage();
return (pkg != null ? pkg.getImplementationVersion() : null);
}

}

当我们需要获取springboot中的版本,只需要调用SpringBootVersion类即可。 注意:SpringBootVersion类修饰符是final,所以我们不能定义子类去继承该类。

4.扩展点

SpringBootVersion类位于spring-boot-2.0.0.M3.jar包中,并且版本信息文件MANIFEST.MF位于spring-boot-2.0.0.M3.jar包中,那是不是我们就可以通过
spring-boot-2.0.0.M3.jar包中的任意一个类去获取版本信息呢?答案是肯定的。当然可以获取到的。实例代码如下:

public class SpringBootVersionTest {
public static void main(String[] args) {
String version = SpringBootVersion.getVersion();
System.out.println(version);
String implementationVersion = SpringApplication.class.getPackage().getImplementationVersion();

System.out.println(implementationVersion);
}
}

上述代码中,我们分别通过了SpringBootVersion类以及SpringApplication类进行版本信息的获取。运行上述的代码,控制台输出的信息如下:
2.0.0.M3
2.0.0.M3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: