Maven基础-pom.xml中 配置全局变量及使用全局变量

在Maven的pom.xml中,通过声明全局变量可以有效地管理多个依赖的版本。例如,当需要统一管理Spring框架的多个模块版本时,可以在properties标签中定义一个spring.version变量,然后在每个依赖的version标签中引用该变量。这样,只需更改全局变量的值,就能快速更新所有相关依赖的版本,提高了项目维护的效率。
摘要由CSDN通过智能技术生成

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值