| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
vr195994
9年前发布

maven java读取maven的pom.xml文件

可以使用maven官方的 maven-model里的MavenXpp3Reader类来读取pom.xml文件, 需要引用maven jar包:

<dependency>              <groupId>org.apache.maven</groupId>              <artifactId>maven-model</artifactId>              <version>3.0</version>          </dependency>

当然,也可以直接找到pom的安装路径下的lib目录找到maven-model-3.1.0.jar文件,引用到项目中。

import org.apache.maven.model.Model;  import org.apache.maven.model.io.xpp3.MavenXpp3Reader;  import org.codehaus.plexus.util.xml.pull.XmlPullParserException;    import java.io.File;  import java.io.FileNotFoundException;  import java.io.FileReader;  import java.io.IOException;    /**   * Created by outofmemory.cn on 2015/10/21.   */  public class Main {      public static void main(String[] args) throws IOException, XmlPullParserException {          MavenXpp3Reader reader = new MavenXpp3Reader();          String myPom = System.getProperty("user.dir") + File.separator + "pom.xml";          Model model = reader.read(new FileReader(myPom));      }  }

如果你需要解析pom的父pom,以及父依赖等信息,需要用到ModelBuildingRequest 类,实例代码如下。

ModelBuildingRequest req = new DefaultModelBuildingRequest();  req.setProcessPlugins( false );  req.setPomFile( file );  req.setModelResolver( new RepositoryModelResolver( basedir, pathTranslator ) );  req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );    Model model;  try  {      model = builder.build( req ).getEffectiveModel();  }  catch ( ModelBuildingException e )  {       ...  }