首页 > 解决方案 > 如何在 Spring Boot 2 的 Java 类中使用 Kotlin 类?

问题描述

我使用以下配置从spring boot starter创建了一个 spring boot 项目:

现在我添加了 2 个简单的类,如下所示:

Kotlin 类:

class KotlinModel(
   var name: String = "",
   //var model: JavaModel
)

一个Java类:

class JavaModel {
   private String name = "";
   //private KotlinModel model;
}

当我取消注释//var model: JavaModel时,项目编译成功,但是当我取消注释时//private KotlinModel model;出现错误:

cannot find symbol
symbol: class KotlinModel
location: class fava.model.JavaModel

pom.xml如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.0.M3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
    <java.version>1.8</java.version>
    <kotlin.version>1.3.31</kotlin.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-kotlin</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jdk8</artifactId>
    </dependency>
</dependencies>
<build>
    <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
    <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-plugin</artifactId>
            <configuration>
                <compilerPlugins>
                    <plugin>jpa</plugin>
                    <plugin>spring</plugin>
                </compilerPlugins>
                <args>
                    <arg>-Xjsr305=strict</arg>
                </args>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-maven-noarg</artifactId>
                    <version>${kotlin.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-maven-allopen</artifactId>
                    <version>${kotlin.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

问题出在哪里?我该如何解决?

标签: javamavenspring-bootkotlin

解决方案


推荐阅读