gradle如何在Java上获取有关项目(dependecies artifactID)的信息

时间:2016-07-16 17:54:53

标签: java gradle groovy

在Gradle中,我可以在Groovy上获得项目信息(依赖项,工件和组ID),如下所示:

class TestPlugin implements Plugin<Project> {
        @Override
        void apply(Project project) {
            def example = project.tasks.create("example") << {
                def dep = project.configurations.runtime.allDependencies
                def info = project.configurations.runtime.getName()
                def g = project.configurations.runtime.getAllArtifacts()

            }

我怎样才能在Java上获得这个?

1 个答案:

答案 0 :(得分:0)

您可以添加一个任务,将您喜欢的任何值写入java Properties文件,如下所示:

apply plugin: 'java'
apply plugin: 'application'

def generatedResourcesDir = new File(project.buildDir, 'generated-resources')

tasks.withType(Jar).all { Jar jar -> 
    jar.doFirst {
        def props = new Properties()
        props.foobar = 'baz'
        generatedResourcesDir.mkdirs()
        def writer = new FileWriter(new File(generatedResourcesDir, 'build.properties'))
        try {
            props.store(writer, 'build properties')
            writer.flush()
        } finally {
            writer.close()
        }    
    }
} 

sourceSets {
    main {
        resources {
            srcDir generatedResourcesDir
        }
    }
}

mainClassName = 'BuildProps'

请注意,在根项目的构建输出目录中创建了一个目录(称为generated-resources,尽管您可以在合理的范围内随意调用它)。然后,在任何jar任务之前运行自定义任务,将属性文件写入此目录。最后,generated-resources目录被添加到resources源集。这意味着它将成为生成的jar文件中的资源,因此可以像任何其他资源一样访问;例如:

import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;

class BuildProps {
    public static void main(String[] args) {
        try (InputStream inputStream = 
                BuildProps.class.getClassLoader().getResourceAsStream("build.properties")) {
            Properties props = new Properties();
            props.load(inputStream);
            System.out.println("Build properties:");
            System.out.println("foobar=" + props.getProperty("foobar", ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

将打印:

Build properties:
foobar=baz

对于您特定的所需属性,您可以像这样设置它们:将行props.foobar = 'baz'替换为以下

def dependenciesProp = ''
for (def dependency : project.configurations.runtime.allDependencies) {
    dependenciesProp += dependency.toString() + ','
}
props.dependencies = dependenciesProp

props.runtimename = project.configurations.runtime.name

def artifactsProp = ''
for (def artifact : project.configurations.runtime.allArtifacts) {
    artifactsProp += artifact.toString() + ','
}
props.artifacts = artifactsProp