Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取Maven项目中的Java构建路径条目_Java_Maven_Maven Plugin - Fatal编程技术网

读取Maven项目中的Java构建路径条目

读取Maven项目中的Java构建路径条目,java,maven,maven-plugin,Java,Maven,Maven Plugin,我有一个项目,它的类路径(JavaBuildPath)中有依赖项。现在我已经将它转换为maven项目,并使用我定制的maven插件编译它。以下是我的POM文件- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http:

我有一个项目,它的类路径(JavaBuildPath)中有依赖项。现在我已经将它转换为maven项目,并使用我定制的maven插件编译它。以下是我的POM文件-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>ear</packaging>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
      <plugins>
         <plugin>
            <groupId>com.my.maven.plugin</groupId>
            <artifactId>my-maven-plugin</artifactId>
            <version>0.0.1</version>
            <extensions>true</extensions>
         </plugin>
      </plugins>
  </build>
</project>
lifecycle.xml-

<?xml version="1.0" encoding="UTF-8"?>
<lifecycles>  
  <lifecycle>  
    <id>customLifeCycle</id>  
    <phases>  
      <phase>  
        <id>compile</id>  
        <executions>  
          <execution>  
            <goals>  
              <goal>mycompile</goal>  
            </goals>  
          </execution>  
        </executions>  
      </phase> 
    </phases>  
  </lifecycle>  
</lifecycles> 
现在,在编译阶段,我想要一个在类路径中存在的JAR文件列表。我怎样才能得到它?我尝试了以下操作,但大多数都返回目标文件夹路径和类文件夹路径

List<String> list1 = project.getCompileClasspathElements();
List<String> list2 = project.getRuntimeClasspathElements();
List<String> list3 = project.getSystemClasspathElements();
List<String> list4 = project.getTestClasspathElements();
List<Dependency> list5 = project.getCompileDependencies();
Properties list6 = project.getProperties();
List<Dependency> list7 = project.getSystemDependencies();
List<Dependency> list8 = project.getRuntimeDependencies();
List list1=project.getCompileClasspathElements();
List list2=project.getRuntimeClasspathElements();
List list3=project.getSystemClasspathElements();
List list4=project.getTestClasspathElements();
List list5=project.getCompiledDependencies();
Properties list6=project.getProperties();
List list7=project.getSystemDependencies();
List list8=project.getRuntimeDependencies();
我的项目结构将被编译

这对我很有效

我在这里找到的


您缺少的关键要素是,它表示插件可用的一组依赖项。发件人:

将此Mojo标记为需要解析指定类路径中的依赖项才能执行。[…]如果注释根本不存在,mojo就不能对与Maven项目相关联的工件进行任何假设

要访问项目的编译时依赖项,可以使用:

编译
解析范围=
编译
+
系统
+
提供的
依赖项

除此之外,还可以访问运行时范围的依赖项,或者添加测试范围的依赖项。当Maven插件不存在此参数时,Maven项目的classpath元素将不可用,这就是您遇到的行为

因此,如果您想让Maven插件获得当前Maven项目依赖项的编译平铺JAR文件列表,您可以:

@Mojo(name = "mycompile", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)
public class MyCompileMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            List<String> list = project.getCompileClasspathElements();
            getLog().info(list.toString());
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoFailureException("Couldn't resolve compile dependencies", e);
        }
    }

}
请注意,要使其工作,您需要确保
编译
阶段(或
测试编译
)已运行。列表是惰性填充的。如果插件声明了
test
requireDependencyResolution
,则运行
mvn clean test
将确保插件可以访问测试范围依赖项。类似地,运行
mvn clean compile
(同时将阶段更改为
compile
)将确保插件在声明
requireDependencyResolution
时可以访问编译范围依赖项


两个旁注:

  • 文件
    lifecycle.xml
    必须位于
    src/main/resources/META-INF/maven
    中。请注意,此文件实际上在您的设置中完全未使用,因为您没有在
    组件.xml中使用新的
    customLifeCycle
    ,而是覆盖
    ear
  • 文件
    components.xml
    必须位于
    src/main/resources/META-INF/plexus
    中。注意,
    com.test:MyMaven插件:mycompile
    必须匹配插件的组id和工件id
  • 测试项目需要使用如下插件:

    <packaging>ear</packaging> <!-- because your lifecycle mapping override ear -->
    <dependencies>
      <!-- some dependencies like maven-core -->
      <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-core</artifactId>
        <version>3.0</version>
      </dependency>
    </dependencies>
    <build>
      <plugins>
        <plugin>
          <groupId>com.test</groupId>
          <artifactId>my-maven-plugin</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <extensions>true</extensions>
        </plugin>
      </plugins>
    </build>
    
    ear
    org.apache.maven
    马文堆芯
    3
    com.test
    我的maven插件
    0.0.1-快照
    真的
    
    然后可以运行
    mvncleanpackage
    ,插件将正确打印
    maven-core
    (例如)的JAR文件路径及其依赖项


完成上一个答案后,您可以阅读如下所有类路径:

public static List<String> getClassPaths() {
    List<String> list = new ArrayList<String>();
    Enumeration res;
    try {
        res = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (res.hasMoreElements()) {
            try {
                URL url = (URL)res.nextElement();
                InputStream is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);
                    Attributes mainAttribs = manifest.getMainAttributes();
                    String classpath = mainAttribs.getValue("Class-Path");
                    if (classpath != null)
                        list.add(classpath);
                }
            }
            catch (Exception e) {
                // Silently ignore wrong manifests or stop the compilation
            }
        }
    } catch (IOException e1) {
    // Silently ignore wrong manifests or stop the compilation
    }
    return list;
}
公共静态列表getclasspath(){
列表=新的ArrayList();
统计研究;
试一试{
res=Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while(res.hasMoreElements()){
试一试{
URL=(URL)res.nextElement();
InputStream=url.openStream();
如果(is!=null){
舱单=新舱单(is);
Attributes maintattribs=manifest.getmaintattributes();
字符串classpath=mainAttribs.getValue(“类路径”);
if(类路径!=null)
添加(类路径);
}
}
捕获(例外e){
//默默地忽略错误的清单或停止编译
}
}
}捕获(IOE1异常){
//默默地忽略错误的清单或停止编译
}
退货清单;
}
如果需要深入了解依赖关系,请执行以下操作:

public static List<String> getClassPaths() {
    List<String> list = new ArrayList<String>();
    Enumeration res;
    try {
        res = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (res.hasMoreElements()) {
            try {
                URL url = (URL)res.nextElement();
                InputStream is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);
                    Attributes mainAttribs = manifest.getMainAttributes();
                    String classpath = mainAttribs.getValue("Class-Path");
                    if (classpath != null)
                        for (String lib : classpath.split(" ")) {
                            try {
                                list.addAll(getClassPathsFromJar(lib));
                            } catch (IOException ioe)
                            {
                                list.add(lib);
                            }
                        }
                }
            }
            catch (Exception e) {
                // Silently ignore wrong manifests or stop the compilation
            }
        }
    } catch (IOException e1) {
    // Silently ignore wrong manifests or stop the compilation
    }
    return list;
}

public static List<String> getClassPathsFromJar(String lib) throws IOException {
    List<String> entries = new ArrayList<String>();
    JarFile jar = new JarFile(lib);
    Manifest manifest = jar.getManifest();
    if (manifest == null) {
        entries.add(lib);
        return entries;
    }
    Attributes mainAttribs = manifest.getMainAttributes();
    String classpath = mainAttribs.getValue("Class-Path");
    if (classpath == null) {
        entries.add(lib);
        return entries;
    }
    for (String l : classpath.split(" ")) {
        entries.addAll(getClassPathsFromJar(l));
    }
    return entries;
}
公共静态列表getclasspath(){
列表=新的ArrayList();
统计研究;
试一试{
res=Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while(res.hasMoreElements()){
试一试{
URL=(URL)res.nextElement();
InputStream=url.openStream();
如果(is!=null){
舱单=新舱单(is);
Attributes maintattribs=manifest.getmaintattributes();
字符串classpath=mainAttribs.getValue(“类路径”);
if(类路径!=null)
for(字符串库:classpath.split(“”)){
试一试{
addAll(getClassPathsFromJar(lib));
}捕获(ioe异常ioe)
{
list.add(lib);
}
}
}
}
捕获(例外e){
//默默地忽略错误的清单或停止编译
}
}
}捕获(IOC)异常
@Mojo(name = "mycompile", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)
public class MyCompileMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            List<String> list = project.getCompileClasspathElements();
            getLog().info(list.toString());
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoFailureException("Couldn't resolve compile dependencies", e);
        }
    }

}
public void execute() throws MojoExecutionException, MojoFailureException {
    Set<Artifact> artifacts = project.getArtifacts();
    for (Artifact artifact : artifacts) {
        System.out.println(artifact.getFile());
    }
}
<packaging>ear</packaging> <!-- because your lifecycle mapping override ear -->
<dependencies>
  <!-- some dependencies like maven-core -->
  <dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-core</artifactId>
    <version>3.0</version>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>com.test</groupId>
      <artifactId>my-maven-plugin</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <extensions>true</extensions>
    </plugin>
  </plugins>
</build>
public static List<String> getClassPaths() {
    List<String> list = new ArrayList<String>();
    Enumeration res;
    try {
        res = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (res.hasMoreElements()) {
            try {
                URL url = (URL)res.nextElement();
                InputStream is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);
                    Attributes mainAttribs = manifest.getMainAttributes();
                    String classpath = mainAttribs.getValue("Class-Path");
                    if (classpath != null)
                        list.add(classpath);
                }
            }
            catch (Exception e) {
                // Silently ignore wrong manifests or stop the compilation
            }
        }
    } catch (IOException e1) {
    // Silently ignore wrong manifests or stop the compilation
    }
    return list;
}
public static List<String> getClassPaths() {
    List<String> list = new ArrayList<String>();
    Enumeration res;
    try {
        res = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (res.hasMoreElements()) {
            try {
                URL url = (URL)res.nextElement();
                InputStream is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);
                    Attributes mainAttribs = manifest.getMainAttributes();
                    String classpath = mainAttribs.getValue("Class-Path");
                    if (classpath != null)
                        for (String lib : classpath.split(" ")) {
                            try {
                                list.addAll(getClassPathsFromJar(lib));
                            } catch (IOException ioe)
                            {
                                list.add(lib);
                            }
                        }
                }
            }
            catch (Exception e) {
                // Silently ignore wrong manifests or stop the compilation
            }
        }
    } catch (IOException e1) {
    // Silently ignore wrong manifests or stop the compilation
    }
    return list;
}

public static List<String> getClassPathsFromJar(String lib) throws IOException {
    List<String> entries = new ArrayList<String>();
    JarFile jar = new JarFile(lib);
    Manifest manifest = jar.getManifest();
    if (manifest == null) {
        entries.add(lib);
        return entries;
    }
    Attributes mainAttribs = manifest.getMainAttributes();
    String classpath = mainAttribs.getValue("Class-Path");
    if (classpath == null) {
        entries.add(lib);
        return entries;
    }
    for (String l : classpath.split(" ")) {
        entries.addAll(getClassPathsFromJar(l));
    }
    return entries;
}