当前位置: 首页 > article >正文

gradle多模块依赖管理最佳实践

gradle多模块依赖管理最佳实践

  • 多模块项目依赖管理
    • 定义子模块
    • 使用buildSrc定义插件
      • SofastModulePlugin
      • Optional 依赖
    • 增加dependencies子模块
    • 其他子模块
      • web

多模块项目依赖管理

依赖管理是项目开发过程中必不可少的操作,在gradle如何优雅的管理多个模块依赖是一个非常值得探讨的问题,本文总结了最佳管理的方式,如 统一三方依赖版本,dependencies

定义子模块

rootProject.name = 'project'
include("dependencies")
include("common") 
include("web") 
include("domain") 
include("service") 

使用buildSrc定义插件

plugins {
    id 'java-gradle-plugin'
    id "java"
    id "groovy"
}

description = "sofast dependency manager"
group 'cc.sofast.dependency'
version '1.0.0'

repositories {
    mavenLocal()
    mavenCentral()
    gradlePluginPortal()
    maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' }
    maven { url 'https://repo.spring.io/milestone' }
}

dependencies {
    implementation('org.springframework.boot:org.springframework.boot.gradle.plugin:3.1.5')
    implementation('io.spring.gradle:dependency-management-plugin:1.1.3')
}

gradlePlugin {
    plugins {
        version {
            id = 'sofast.module.plugin'
            implementationClass = 'cc.sofastframework.gradle.SofastModulePlugin'
            displayName = "Dependency Manager Plugin"
            description = "Manage Dependent Versions"
        }
    }
}

SofastModulePlugin

public class SofastModulePlugin implements Plugin<Project> {

    @Override
    public void apply(Project project) {
        System.out.println("Sofast Dependency Manager plugin.");

        //java 插件
        project.getPlugins().apply(JavaPlugin.class);
        project.getPlugins().apply(JavaBasePlugin.class);

        //springboot
        Object springBootPluginEnable = project.getProperties().get("springBootPluginEnabled");
        if (Boolean.valueOf(String.valueOf(springBootPluginEnable)).equals(Boolean.TRUE)) {
            System.out.println("enabled SpringBootPlugin and DependencyManagementPlugin.");
            project.getPlugins().apply(SpringBootPlugin.class);
            project.getPlugins().apply(DependencyManagementPlugin.class);
        }

        project.getPlugins().apply(JavaConventionsPlugin.class);

        //依赖仓库
        project.getRepositories().mavenLocal();
        project.getRepositories().mavenCentral();
        project.getRepositories().maven(mavenArtifactRepository -> mavenArtifactRepository.setUrl("https://maven.aliyun.com/nexus/content/groups/public/"));
        project.getRepositories().maven(mavenArtifactRepository -> mavenArtifactRepository.setUrl("https://repo.spring.io/milestone"));
    }
}
  • JavaConventionsPlugin 引入optional 依赖
package cc.sofastframework.gradle;

import cc.sofastframework.gradle.optional.OptionalDependenciesPlugin;
import org.gradle.api.JavaVersion;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.tasks.bundling.Jar;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.external.javadoc.CoreJavadocOptions;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;


/**
 * @author apple
 */
public class JavaConventionsPlugin implements Plugin<Project> {

    private static final String SOURCE_AND_TARGET_COMPATIBILITY = "17";

    private static final String ENCODING = "UTF-8";

    @Override
    public void apply(Project project) {
        System.out.println("JavaConventionsPlugin is enabled");
        //enabled optional plugin
        project.getPlugins().apply(OptionalDependenciesPlugin.class);
        //configuration convention
        project.getPlugins().withType(JavaBasePlugin.class, (java) -> {
            configureJavaConventions(project);
            configureJavadocConventions(project);
            configureDependencyManagement(project);
        });
    }

    private void configureJavadocConventions(Project project) {
        project.getTasks().withType(Javadoc.class, (javadoc) -> {
            CoreJavadocOptions options = (CoreJavadocOptions) javadoc.getOptions();
            options.source(SOURCE_AND_TARGET_COMPATIBILITY);
            options.encoding(ENCODING);
            options.addStringOption("Xdoclint:none", "-quiet");
        });
    }

    private void configureJavaConventions(Project project) {
        if (!project.hasProperty("toolchainVersion")) {
            JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class);
            javaPluginExtension.setSourceCompatibility(JavaVersion.toVersion(SOURCE_AND_TARGET_COMPATIBILITY));
        }
        project.getTasks().withType(JavaCompile.class, (compile) -> {
            compile.getOptions().setEncoding(ENCODING);
            List<String> args = compile.getOptions().getCompilerArgs();
            if (!args.contains("-parameters")) {
                args.add("-parameters");
            }
            if (project.hasProperty("toolchainVersion")) {
                compile.setSourceCompatibility(SOURCE_AND_TARGET_COMPATIBILITY);
                compile.setTargetCompatibility(SOURCE_AND_TARGET_COMPATIBILITY);
            } else if (buildingWithJava17(project)) {
                args.addAll(Arrays.asList("-Werror", "-Xlint:unchecked", "-Xlint:deprecation", "-Xlint:rawtypes",
                        "-Xlint:varargs"));
            }
        });
    }

    private boolean buildingWithJava17(Project project) {
        return !project.hasProperty("toolchainVersion") && JavaVersion.current() == JavaVersion.VERSION_17;
    }

    private void configureDependencyManagement(Project project) {
        ConfigurationContainer configurations = project.getConfigurations();
        Configuration dependencyManagement = configurations.create("dependencyManagement", (configuration) -> {
            configuration.setVisible(false);
            configuration.setCanBeConsumed(false);
            configuration.setCanBeResolved(false);
        });
        configurations
                .matching((c) -> c.getName().endsWith("Classpath") || c.getName().toLowerCase().endsWith("annotationprocessor"))
                .all((c) -> c.extendsFrom(dependencyManagement));
        Dependency pulsarDependencies = project.getDependencies().enforcedPlatform(project.getDependencies()
                .project(Collections.singletonMap("path", ":dependencies")));
        dependencyManagement.getDependencies().add(pulsarDependencies);
        project.getPlugins().withType(OptionalDependenciesPlugin.class, (optionalDependencies) -> configurations
                .getByName(OptionalDependenciesPlugin.OPTIONAL_CONFIGURATION_NAME).extendsFrom(dependencyManagement));
    }
}

Optional 依赖

public class OptionalDependenciesPlugin implements Plugin<Project> {

	/**
	 * Name of the {@code optional} configuration.
	 */
	public static final String OPTIONAL_CONFIGURATION_NAME = "optional";

	@Override
	public void apply(Project project) {
		Configuration optional = project.getConfigurations().create("optional");
		optional.setCanBeConsumed(false);
		optional.setCanBeResolved(false);
		project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> {
			SourceSetContainer sourceSets = project.getExtensions().getByType(JavaPluginExtension.class)
					.getSourceSets();
			sourceSets.all((sourceSet) -> {
				project.getConfigurations().getByName(sourceSet.getCompileClasspathConfigurationName())
						.extendsFrom(optional);
				project.getConfigurations().getByName(sourceSet.getRuntimeClasspathConfigurationName())
						.extendsFrom(optional);
			});
		});
	}

}

增加dependencies子模块

dependencies 模块统一管理三方包的版本和dependencies 依赖如下:

import static org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES

plugins {
    id 'java-platform'
}

javaPlatform {
    allowDependencies()
}

ext {
    seataVersion = '1.6.1'
    feignVersion = '12.1'
    mybatisPlusVersion = '3.5.3.1'
}

dependencies {
    constraints {
        api "io.seata:seata-rm-datasource:$seataVersion"
        api "io.github.openfeign:feign-core:$feignVersion"
        api "com.baomidou:mybatis-plus-boot-starter:$mybatisPlusVersion"
    }
    println("spring boot version: " + BOM_COORDINATES)
    api platform(BOM_COORDINATES)
    api platform('org.springframework.cloud:spring-cloud-dependencies:2022.0.4')
}

其他子模块

web

//引入插件
plugins {
    id 'sofast.module.plugin'
}

//引入依赖,会自动引入dependencies 继承其定义的版本
dependencies {
    implementation(project(":domain"))
    optional 'org.springframework.boot:spring-boot-starter-jdbc'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
}

http://www.kler.cn/a/108885.html

相关文章:

  • 基于BILSTM及其他RNN序列模型的人名分类器
  • redis实现消息队列的几种方式
  • 【ubuntu】单进程申请4GB内存
  • 重学SpringBoot3-整合 Elasticsearch 8.x (三)使用Repository
  • 前端web
  • layui 文件上传前检查文件大小,后面再点上传出现重复提交的问题
  • Linux之系统编程
  • 磨人的Ts
  • 最新Microsoft Edge浏览器如何使用圆角
  • D-LINK SQL注入漏洞让攻击者获得管理员权限
  • 10、SpringCloud -- 优化重复下单
  • macOS M1安装wxPython报错
  • shell中的运算
  • How to install the console system of i-search rpa on Centos 7
  • kubeadm源码解读与实战(2)
  • 主定理(一般式)
  • SOLIDWORKS Simulation2024仿真10大新功能
  • Pytorch代码入门学习之分类任务(一):搭建网络框架
  • [2021]不确定成本下的处理分配
  • 39 深度学习(三):tensorflow.data模块的使用(基础,可跳)
  • [量化投资-学习笔记002]Python+TDengine从零开始搭建量化分析平台-MA均线的多种实现方式
  • 行为型模式-行为型模式
  • Python练习
  • vim使用
  • 十八、字符串(3)
  • 公众号留言功能有必要开吗?如何开通留言?