简体   繁体   English

从导入的依赖项覆盖 Gradle 项目配置

[英]Override Gradle project configuration from imported dependency

I'm developing a project which serves as a platform for many other projects.我正在开发一个项目,作为许多其他项目的平台。 It is distributed as a library.它作为库分发。

I'm facing the following issue: I don't have control over the other projects and I want to have a consistent logging format.我面临以下问题:我无法控制其他项目,我希望拥有一致的日志记录格式。 In order to do that I want to have specific logging dependencies versions which are declared in my project's build.gradle so I can manipulate them.为了做到这一点,我想要在我的项目的 build.gradle 中声明特定的日志依赖版本,以便我可以操作它们。

How should I write my Gradle configuration so it can override or force a specific dependency version?我应该如何编写我的 Gradle 配置,以便它可以覆盖或强制特定的依赖版本? I'm using Gradle 6.2.1 and I've tried我正在使用 Gradle 6.2.1,我试过了

api(group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.0') {
        force = true
    }

but it doesn't work.但它不起作用。

There is no way for a library to dictate/override the dependencies of a consuming project.库无法指定/覆盖消费项目的依赖项。

If you want to control other projects and ensure they are using the appropriate libraries/versions, then you will need to write a Gradle plugin that overrides the dependency resolution of the project.如果您想控制其他项目并确保它们使用适当的库/版本,那么您需要编写一个 Gradle 插件来覆盖项目的依赖项解析。

For your use case (if I am understanding it correct) the plugin could be as simple as:对于您的用例(如果我理解正确的话),该插件可能很简单:

public class LoggingResolutionPlugin implements Plugin<Project> {

  @Override
  public void apply(Project project) {

    project.getConfigurations().all((configuration) -> {
      configuration.resolutionStrategy((resolutionStrategy) -> {
        resolutionStrategy.eachDependency((dependency) -> {

          ModuleVersionSelector requested = dependency.getRequested();
          if(requested.getGroup().equals("org.apache.logging.log4j")
          && requested.getName().equals("log4j-core")) {
             dependency.useVersion("2.13.0");
             dependency.because("Library must use 2.13.0 because reasons.");
          }
        });
      });
    });
  }
}

Further reading:进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM