Kotlin-allopenとSpring
1. 概要
Kotlinでは、すべてのクラスがデフォルトでfinal であり、明確な利点を超えて、Springアプリケーションで問題が発生する可能性があります。 簡単に言えば、Springの一部の領域は、非最終クラスでのみ機能します。
自然な解決策は、 open キーワードを使用してKotlinクラスを手動で開くか、 kotlin-allopen プラグインを使用することです。これにより、Springが機能するために必要なすべてのクラスが自動的に開きます。
2. Mavenの依存関係
Kotlin-Allopen依存関係を追加することから始めましょう。
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>1.1.4-3</version>
</dependency>
プラグインを有効にするには、ビルドセクションでkotlin-allopenを構成する必要があります。
<build>
...
<plugins>
...
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>1.1.4-3</version>
<configuration>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>1.1.4-3</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
3. 設定
次に、単純な構成クラスであるSimpleConfiguration.ktについて考えてみましょう。
@Configuration
class SimpleConfiguration {
}
4. Kotlinなし-Allopen
プラグインなしでプロジェクトをビルドすると、次のエラーメッセージが表示されます。
org.springframework.beans.factory.parsing.BeanDefinitionParsingException:
Configuration problem: @Configuration class 'SimpleConfiguration' may not be final.
Remove the final modifier to continue.
それを解決する唯一の方法は、手動で開くことです。
@Configuration
open class SimpleConfiguration {
}
5. Kotlin-Allopenを含む
Springのすべてのクラスを開くのはあまり便利ではありません。 プラグインを使用すると、必要なすべてのクラスが開きます。
コンパイルされたクラスを見ると、次のことがはっきりとわかります。
@Configuration
public open class SimpleConfiguration public constructor() {
}
6. 結論
この簡単な記事では、SpringとKotlinの「クラスが最終的なものではない可能性がある」問題を解決する方法を見てきました。
この記事のソースコードは、GitHubのにあります。