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

背景

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

maven 依赖


  org.kie.soup
  kie-soup-maven-integration
  7.21.0.Final
 

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 dependecies = artifactResolver.getArtifactDependecies(deployedModel.toArtifactName());
    
        File artifactJar = artifact.getFile();
    
        List 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

 

  /repository/
  
    
      
        
          
            false
          
          central
          libs-release
          http://{ip:port}/artifactory/libs-release
        
        
          
            always
          
          snapshots
          libs-snapshot
          http://{ip:port}/artifactory/libs-snapshot
        
      
      artifactory
    
  
  
    artifactory
  

结语

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

你可能感兴趣的:(Java中从maven拉取所需jar包及其依赖)