新解决方案
实际上,在思考的过程中,我找到了一个比我之前的解决方案更好的解决方案,我对此感到非常高兴,并且不应该以任何方式干扰实际项目的构建。
在buildSrc 项目的build.gradle 中:
configurations {
wsimport
xjc
}
dependencies {
wsimport 'com.sun.xml.ws:jaxws-tools:2.1.4'
xjc 'com.sun.xml.bind:jaxb-xjc:2.2.4-1'
}
def generatedResourcesDirectory = "$buildDir/resources/generated"
task generateClasspathsPropertiesFile {
inputs.file configurations.wsimport
inputs.file configurations.xjc
def outputFile = file("$generatedResourcesDirectory/classpaths.properties")
outputs.file outputFile
doLast {
def classpaths = new Properties()
classpaths.wsimport = configurations.wsimport.asPath
classpaths.xjc = configurations.xjc.asPath
outputFile.parentFile.mkdirs()
outputFile.withOutputStream { classpaths.store it, null }
}
}
sourceSets.main.output.dir generatedResourcesDirectory, builtBy: generateClasspathsPropertiesFile
然后在各自的任务中:
class Xjc extends DefaultTask {
...
@TaskAction
def xjc() {
...
def classpaths = new Properties()
getClass().getResource('/classpaths.properties').withInputStream { classpaths.load it }
ant.taskdef name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: classpaths.xjc
ant.xjc ...
...
}
}
class Wsimport extends DefaultTask {
...
@TaskAction
def wsimport() {
...
def classpaths = new Properties()
getClass().getResource('/classpaths.properties').withInputStream { classpaths.load it }
ant.taskdef name: 'wsimport', classname: 'com.sun.tools.ws.ant.WsImport', classpath: classpaths.wsimport
ant.wsimport ...
...
}
}
旧解决方案
我目前如何解决这种情况 - 尽管我对此不太满意 - 除了需要应用的任务之外还有一个插件:
class XjcPlugin implements Plugin<Project> {
static final CONFIGURATION_NAME = "xjc_${System.currentTimeMillis()}"
@Override
void apply(Project project) {
project.configurations.create(CONFIGURATION_NAME) { visible: false }
project.dependencies {
"$CONFIGURATION_NAME" group: 'com.sun.xml.bind', name: 'jaxb-xjc', version: '2.2.4-1'
}
}
}
class Xjc extends DefaultTask {
...
@TaskAction
def xjc() {
if (!project.configurations.hasProperty(XjcPlugin.CONFIGURATION_NAME)) {
throw new ConfigurationException("xjc configuration is missing on project ${project.name}, did you forget to apply XjcPlugin?")
}
...
def runClassPath = project.configurations."$XjcPlugin.CONFIGURATION_NAME".asPath
ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: runClassPath)
ant.xjc(...)
}
}
但请注意,configurations.all { ... } 或 nebula-dependency-recommender-plugin 之类的内容也会影响这些配置,并可能产生意想不到的结果。