Finding the Spring Version – 寻找Spring的版本

最后修改: 2020年 3月 6日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll demonstrate how to programmatically find out which version of Spring, JDK, and Java our application is using.

在本教程中,我们将演示如何以编程方式找出我们的应用程序正在使用的Spring、JDK和Java的版本。

2. How to Get Spring Version

2.如何获得Spring版本

We’ll start by learning how to obtain the version of Spring that our application is using.

我们将首先学习如何获得我们的应用程序正在使用的Spring版本。

In order to do this, we’ll use the getVersion method of the SpringVersion class:

为了做到这一点,我们将使用SpringVersion 类的getVersion方法

assertEquals("5.1.10.RELEASE", SpringVersion.getVersion());

3. Getting JDK Version

3.获得JDK的版本

Next, we’ll get the JDK version that we’re currently using in our project. It’s important to note that Java and the JDK aren’t the same thing, so they’ll have different version numbers.

接下来,我们将得到我们的项目中目前使用的JDK版本。需要注意的是,Java和JDK并不是一回事,所以它们会有不同的版本号。

If we’re using Spring 4.x, there’s a class called JdkVersion, which we can use to get this information. However, this class was removed from Spring 5.x, so we’ll have to take that into account and work around it.

如果我们使用的是Spring 4.x,有一个名为JdkVersion的类,我们可以用它来获取这些信息。然而,这个类在Spring 5.x中被删除了,所以我们必须考虑到这一点并绕过它。

Internally, the Spring 4.x JdkVersion class was getting the version from the SystemProperties class, so we can do the same. Making use of the class SystemProperties, we’ll access the property java.version:

在内部,Spring 4.x的JdkVersion 类是从SystemProperties类中获取版本,因此我们也可以这样做。利用SystemProperties类,我们将访问属性java.version

assertEquals("1.8.0_191", SystemProperties.get("java.version"));

Alternatively, we can access the property directly without using that Spring class:

另外,我们可以直接访问该属性,而不使用那个Spring类。

assertEquals("1.8.0_191", System.getProperty("java.version"));

4. Obtaining Java Version

4.获取Java版本

Finally, we’ll see how to get the version of Java that our application is running on. For this purpose, we’ll use the class JavaVersion:

最后,我们将看到如何获得我们的应用程序所运行的Java的版本。为此,我们将使用JavaVersion这个类。

assertEquals("1.8", JavaVersion.getJavaVersion().toString());

Above, we call the JavaVersion#getJavaVersion method. By default, this returns an enum with the specific Java version, such as EIGHT. To keep the formatting consistent with the above methods, we parse it using its toString method.

上面,我们调用JavaVersion#getJavaVersion方法。默认情况下,这将返回一个包含特定Java版本的枚举,例如Eight。为了保持与上述方法的格式一致,我们使用其toString方法对其进行解析。

5. Conclusion

5.结论

In this article, we learned that it’s quite simple to obtain the versions of Spring, JDK, and Java that our application is using.

在这篇文章中,我们了解到,获得我们的应用程序正在使用的Spring、JDK和Java的版本是非常简单的。

As always, the complete code is available over on GitHub.

一如既往,完整的代码可在GitHub上获得