1.新建Gradle项目:
2.建立src/main/groovy目录,并添加如下代码:
ConfigPlugin.groovy package com.wemall.config import org.gradle.api.Plugin import org.gradle.api.Project class ConfigPlugin implements Plugin<Project> { void apply(Project project) { project.extensions.create("configPluginExtension", ConfigPluginExtension) project.task("configTask", type: ConfigTask) } }
ConfigTask.groovy
package com.wemall.config import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import groovy.swing.impl.DefaultAction import groovy.xml.Namespace import groovy.xml.StreamingDOMBuilder class ConfigTask extends DefaultTask { static final String CONFIG_CENTER_URL = "http://192.168.127.137:8080/config-center-0.0.1-SNAPSHOT/"; @TaskAction void download() { def names = project.configPluginExtension.name; def version = project.configPluginExtension.version; names.each { name -> def inputStream = new URL(CONFIG_CENTER_URL + name).openStream(); println ("${project.projectDir} , ${project.buildDir}, ${project.rootDir}, ${project.resources}"); def file = new File("${project.projectDir}/src/main/resources/${name}"); file.withOutputStream { outputStream -> outputStream << inputStream; } } } }
ConfigPluginExtension.groovy
package com.wemall.config class ConfigPluginExtension { def name = []; def version = ""; }
3.在src/main/resources下建立MEAT-INFO/gradle-plugins目录,并添加com.wemall.config.properties配置文件
com.wemall.config.properties内容,这个properties文件的名称,就为自定义Gradle插件名称. implementation-class=com.wemall.config.ConfigPlugin
4.build.gradle文件内容:
apply plugin: ‘groovy‘ apply plugin: ‘maven‘ apply plugin: ‘maven-publish‘ dependencies { compile gradleApi() compile localGroovy() } group=‘com.wemall.config‘ version=‘1.0.7-SNAPSHOT‘ publishing { publications { maven(MavenPublication) { groupId project.group artifactId project.name version project.version //若是war包,就写components.web,若是jar包,就写components.java from components.java } } repositories { maven { if (project.version.endsWith(‘-SNAPSHOT‘)) { url = "http://192.168.184.155:8081/repository/maven-snapshots/" } else { url = "http://192.168.184.155:8081/repository/maven-releases/" } credentials { username ‘admin‘ password ‘admin123‘ } } } }
5.发布接入到nexus仓库中:
6.其他gradle项目引入插件:
buildscript { repositories { maven { url ‘http://192.168.184.155:8081/repository/maven-public/‘ } } dependencies { classpath group: ‘com.wemall.config‘,name: ‘config-plugin‘,version: ‘1.0.7-SNAPSHOT‘ } } plugins { id ‘java-library‘ } apply plugin: ‘com.wemall.config‘ dependencies { testImplementation ‘junit:junit:4.12‘ } configPluginExtension { name = ["a.properties", "b.properties", "c.properties"] version = "1.0.0-SNAPSHOT" }
7.在引入插件的项目中运行插件:
gradlew -q configTask
此时configTask插件就可以连接到网址的配置中上下载配置文件。configTask名称为ConfigPlugin.groovy文件中的project.task("configTask", type: ConfigTask)字符串名称。
原文地址:https://www.cnblogs.com/dingyingsi/p/9517699.html
时间: 2024-10-05 21:07:08