使用import解决Maven项目单继承问题

至于Maven项目继承问题,最好的例子的就是我们做springboot项目的时候的如下代码:

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.3.3.RELEASE</version>
</parent>

我们知道Maven的继承和Java的继承一样,只能单继承,无法实现多继承,你是否想过我们如果要继承多个父模块的时候应该怎么做呢?或许你会想只往一个父模块中添加jar包依赖,只继承一个父模块就可以了,但是这样的话所有的jar包都混合在一起了,jar包分类就不在清晰了,其实我们可以用另外一种方式实现多模块继承,这个方法就是使用<type>pom</type><scope>import</scope>,解释一下:type标签的默认值是jar,代表我们依赖导入的是一个jar包,现在我们设置成了pom,说明导入的是一个父模块,后面的scope标签中的值import代表把父模块中的jar包导入进来,不过需要注意的是<type>pom</type><scope>import</scope>,这种方式只能用在<dependencyManagement></dependencyManagement>中,那么再来一个例子吧,在SpringCloud项目中,我们导入SpringCloud依赖和SpringBoot依赖的代码如下:

<dependencyManagement>

	<dependencies>
		<!-- SpringCloud的jar包依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>Dalston.SR1</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
		<!-- SpringBoot的jar包依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>1.5.9.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
		</dependencies>
		
	</dependencyManagement>

上面的做法其实就相当于实现了多继承,毕竟我们导入了SpringCloud和SpringBoot的两个父模块的jar包依赖

发布了177 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42449963/article/details/105222086