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

摘要:在使用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


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值