欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中从maven拉取所需jar包及其依赖

程序员文章站 2022-07-03 20:22:41
...

背景

最近基于alibaba的jarslink框架开发了算法服务平台。各个算法模块以jar包的形式推送到maven仓库中,java代码需要根据配置信息,从*仓库拉取各个jar包及其依赖,本文记录下对应的代码实现

maven 依赖

<dependency>
  <groupId>org.kie.soup</groupId>
  <artifactId>kie-soup-maven-integration</artifactId>
  <version>7.21.0.Final</version>
 </dependency>

Java Demo

@Component
public class ModelMavenLoader{
  static{
    System.setProperty(MavenSettings.CUSTOM_SETTINGS_PROPERTY,ModelMavenLoader.class.getClassLoader().getResource("settings.xml").getPath());
  }
    
	public ModelMavenLoadResult loadWithDependency(DeployedModel deployedModel) throws Exception{
	    //下载依赖jar包
	    ArtifactResolver artifactResolver = new ArtifactResolver();
	    Artifact artifact = artifactResolver.resolveArtifact(deployedModel.toAFReleaseId());
	
	    List<DependencyDescriptor> dependecies = artifactResolver.getArtifactDependecies(deployedModel.toArtifactName());
	
	    File artifactJar = artifact.getFile();
	
	    List<File> dependencyFiles = new LinkedList<>();
	    for (DependencyDescriptor depend : dependecies) {
	        if (!DependencyFilter.COMPILE_FILTER.accept(depend.getReleaseId(), depend.getScope())) {
	            continue;
	        }
	        Artifact a = artifactResolver.resolveArtifact(depend.getReleaseId());
	        dependencyFiles.add(a.getFile());
	    }
	
	    ModelMavenLoadResult result = new ModelMavenLoadResult();
	    result.setArtifactJar(artifactJar);
	    result.setDependencyJars(dependencyFiles);
	
	    return result;
	}
}

Maven settings.xml

 <?xml version="1.0" encoding="UTF-8"?>
<settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd" xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <localRepository>/repository/</localRepository>
  <profiles>
    <profile>
      <repositories>
        <repository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>libs-release</name>
          <url>http://{ip:port}/artifactory/libs-release</url>
        </repository>
        <repository>
          <snapshots>
            <updatePolicy>always</updatePolicy>
          </snapshots>
          <id>snapshots</id>
          <name>libs-snapshot</name>
          <url>http://{ip:port}/artifactory/libs-snapshot</url>
        </repository>
      </repositories>
      <id>artifactory</id>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>artifactory</activeProfile>
  </activeProfiles>
</settings>

结语

基于这样一个工具类,开发中可以把插件推送到*仓库,由代码去主动的拉取插件及jar包,基于jarslink框架,可以实现服务的插件应用。希望大家有所收获