I a working on a project in spring boot.. is it possible to use in kotlin and java both in spring-boot project. I have tried by making a Kotlin @controller class and calling java @service class but it isn't working
Yes, it will definitely work
You simply need to configure it properly
check your build.gradle source sets and targets
Follow the below folder structure
src
main
java
kotlin
resources
I have done the following to successfully use Kotlin in my existing Spring Boot App. My IDE is IntelliJ.
(1)
Ensure that Kotlin plugin is installed in the IDE.
(2)
Get the required dependencies.
…
<properties>
…
<kotlin.version>1.6.10</kotlin.version>
<!--Edit the version to the latest stable version, if applicable-->
</properties>
…
<dependencies>
…
<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>
…
</build>
…
<plugins>
…
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
(3)
Create the required directories in your project.
(4)
Now update / rebuild the project. If any Maven / build errors show up then do one / all of the following:
(5)
Now you can create a Kotlin class under the src/main/kotlin package. For this,
Note:
If the Kotlin class does not have a package statement then it will not be visible from your Java classes.
To fix this,
Go to your Java class which has the main method. (This is the class which is annotated by @SpringBootApplication)
Copy the package statement of this class. This should most likely be the first statement of the Java class and should be something like
package com.xyz.myApplication;
Paste this statement in the Kotlin class so that this becomes the first statement of your Kotlin class as well.
Once everything is done, you can simply import and instantiate your Kotlin classes from inside your Java classes. You can also do vice versa, that is, import and instantiate your Java classes from inside your Kotlin classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.