Gradle: compileOnly and runtimeOnly

时光总嘲笑我的痴心妄想 提交于 2020-06-15 18:59:50

问题


I'd read the documentation but I'm not able to understand how to create a working example to understand better their differences.

And ofc I've created a playground project to check what happens when I use one or another.

app.gradle

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$rootProject.kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    compileOnly project(":compileonlylibrary")
    runtimeOnly project(":runtimeonlylibrary")
}

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        FooCompile() // this crash in runtime
        BarRuntime() // this doesn't compiles obviously
    }
}
// FooCompile belongs to compileonlylibrary
// BarRuntime belongs to runtimeonlylibrary

And that's it, I'm stuck here, I'm not able to create a proper example in order to improve my knowledge of Gradle configurations.

Could someone give me a hand? I can provide more details if needed.


回答1:


CompileOnly dependencies are available while compiling but not when running them.

This is equivalent to the provided scope in maven.

It means that everyone who wants to execute it needs to supply a library with all classes of the CompileOnly library.

For example, you could create a library that uses the SLF4J API and you could set it to CompileOnly.

Anyone using the library needs to (explicitely) import some version of the SLF4J API in order to use it.

RuntimeOnly libraries are the opposite, they are available at runtime but not at compile-time.

For example, you don't need the concrete SLF4J logger(e.g. logback) at compile time (as you use the SLF4J classes in order to access it) but you need it at runtime as you want to use it.

Let's look at the following example:

You have a library that uses the SLF4J:

compileOnly org.slf4j:slf4j-api:1.7.30

and you could have a project using the library:

implementation project(":yourlibrary")
implementation org.slf4j:slf4j-api:2.0.0-alpha1
runtimeOnly ch.qos.logback:logback:0.5

SLF4J detects the concrete logger at runtime, it does not need to know the logging library (like logback) at runtime. This is why you can use runtimeOnly for the concrete logger.


Note that compileOnly is broadly used with Jakarta EE as lots of dependencies are provided by the JEE container/application server as shown in the blog the OP found.



来源:https://stackoverflow.com/questions/61696863/gradle-compileonly-and-runtimeonly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!