0%

Gradle排除war中特定依赖的方法

背景

在往SAP Cloud Platform Neo上部署war文件后,有时会出现程序无法启动的错误。
通过排查错误日志,发现log中有类似下面的描述:

1
2
3
4
5
2019 05 28 09:31:00#+00#ERROR#org.slf4j.helpers.Util##anonymous#localhost-startStop-1#na#xxxx#sampleapp#web##na#na#na#na#SLF4J: Class path contains multiple SLF4J bindings. |
2019 05 28 09:31:00#+00#ERROR#org.slf4j.helpers.Util##anonymous#localhost-startStop-1#na#xxxx#sampleapp#web##na#na#na#na#SLF4J: Found binding in [jar:file:/usr/sap/ljs/bin/logback-classic.jar!/org/slf4j/impl/StaticLoggerBinder.class] |
2019 05 28 09:31:00#+00#ERROR#org.slf4j.helpers.Util##anonymous#localhost-startStop-1#na#xxxx#sampleapp#web##na#na#na#na#SLF4J: Found binding in [jar:file:/usr/sap/ljs/webapps/spring-boot-Olingo-oData-master/WEB-INF/lib/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class] |
2019 05 28 09:31:00#+00#ERROR#org.slf4j.helpers.Util##anonymous#localhost-startStop-1#na#xxxx#sampleapp#web##na#na#na#na#SLF4J: See http://www.slf4j.org/codes.html\#multiple_bindings for an explanation. |
2019 05 28 09:31:00#+00#ERROR#org.slf4j.helpers.Util##anonymous#localhost-startStop-1#na#xxxx#sampleapp#web##na#na#na#na#SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

仔细观察发现该错误是slf4j和logback的依赖冲突导致的。

解决办法

通过参考gradle-exclude-dependencies这篇文章,尝试了如下解决办法:

Dependency局部排除

通过对spring boot的依赖添加exclude描述来排除特定依赖。

1
2
3
4
5
6
7
8
compile("org.springframework.boot:spring-boot-starter-web:${project.bootVersion}"){
exclude group: 'org.slf4j', module: 'slf4j-api'
exclude group: 'ch.qos.logback', module: 'logback-classic'
}
compile("org.springframework.boot:spring-boot-starter-actuator:${project.bootVersion}"){
exclude group: 'org.slf4j', module: 'slf4j-api'
exclude group: 'ch.qos.logback', module: 'logback-classic'
}

Configuration全局排除

在全局配置中通通排除相关依赖。

1
2
3
4
configurations {
all*.exclude group: 'org.slf4j', module: 'slf4j-api'
all*.exclude group: 'ch.qos.logback', module: 'logback-classic'
}

providedRuntime打包时排除

上述两种方法能够解决问题,但是本地执行的时候却会报错,原因是Tomcat Embedded还是需要被排除的那些依赖。
怎样让gradle打包的时候排除这些依赖呢?gradle提供了providedRuntime和providedCompile等写法。
The War Plugin

1
2
providedRuntime("org.slf4j:slf4j-api")
providedRuntime("ch.qos.logback:logback-classic")