Can't inject a Kotlin service into a Java class

Viewed 213

I have the following Kotlin service:

@Service
open class KotlinServiceImpl(private val myRepository: MyRepository) : MyService { ... }

The Java class that's trying to get it:

private final MyService MyService;

public MyController(MyService myService) {
  this.myService = myService;
}

The error:

Parameter 0 of constructor in MyController required a bean of type 'MyService' that could not be found.

I'm using Gradle, and have the needed dependencies:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation 'org.jetbrains.kotlin:kotlin-reflect:1.3.72'

And the relevant Kotlin plugin is also applied:

plugins {
    id 'org.jetbrains.kotlin.jvm'
}

When I convert the Java interface MyService to Kotlin, I get the following error:

java.lang.NoClassDefFoundError: com/.../MyService

Using only Java classes solves the problem.

1 Answers

The class wasn't available at runtime. I finally noticed that our build file defines its own run task:

run {
    dependsOn pathingJar
    doFirst {
        classpath = files(
            "$buildDir/classes/java/main",
            "$buildDir/resources/main",
            pathingJar.archivePath)
    }

    Map<String, String> map = loadExecutionProperties()

    map.put("SPRING_PROFILES_ACTIVE", "...")
    map.put("APP_NAME", "app-name")
    environment(map)
}

So I need to add "$buildDir/classes/kotlin/main" to files in classpath.

I hope this will help future users.

Related