1.为什么要使用全局变量
在我们的pom.xml配置文件中,当我们引入的依赖较多且对版本要求一致时,
此时,对依赖的管理就比较的繁琐。
比如 : 我们引入Spring的相关依赖,要求版本都是5.2.9.RELEASE
,则可以声明一个统一的版本的全局变量,在各个依赖中统一引用。此时,如果想对版本进行替换,则只需要修改一下这个全局变量即可。
2.如何配置及使用
2.1 声明全局变量的格式
在
properties
标签中声明
<properties>
<变量名>变量值</变量名>
</properties>
例如下面的变量:
<properties>
<spring.version>4.3.10.RELEASE</spring.version>
</properties>
2.2 使用全局变量的格式
通过
${变量名}
的形式引用变量的值。
例如下面的格式:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
2.3 实际案例
假设:现在需要手动导入 spring 的四个核心的jar包,且 版本都是
5.2.9.RELEASE
.
【实际上,maven会自动帮我们把相关的依赖导入,这里只是为了演示全局变量的效果】
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 当前项目的坐标信息-->
<groupId>com.northcastle</groupId>
<artifactId>helloworld-maven-java</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 1.自定义的属性设置,可以自己进行配置和修改
声明了一个全局的变量 : spring.version
-->
<properties>
<spring.version>5.2.9.RELEASE</spring.version>
</properties>
<!-- 2.在依赖中使用声明的 全局变量 -->
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
3.完成
Congratulations!
You are one step closer to success!