コトリンアロッペンと春

Kotlin-allopenとSpring

1. 概要

In Kotlin, all classes are final by defaultは、明確な利点を超えて、Springアプリケーションで問題になる可能性があります。 簡単に言うと、Springの一部の領域は、最終クラス以外でのみ機能します。

自然な解決策は、openキーワードを使用してKotlinクラスを手動で開くか、kotlin-allopenプラグインを使用することです。これにより、Springが機能するために必要なすべてのクラスが自動的に開きます。

2. Mavenの依存関係

Kotlin-Allopenの依存関係を追加することから始めましょう:


    org.jetbrains.kotlin
    kotlin-maven-allopen
    1.1.4-3

プラグインを有効にするには、ビルドセクションでkotlin-allopenを構成する必要があります。


   ...
  
        ...
        
            kotlin-maven-plugin
            org.jetbrains.kotlin
            1.1.4-3
            
                
                    spring
                
                1.8
            
            
                
                    compile
                    compile
                    
                        compile
                    
                
                
                    test-compile
                    test-compile
                    
                        test-compile
                    
                
            
            
                
                    org.jetbrains.kotlin
                    kotlin-maven-allopen
                    1.1.4-3
                
            
        
    

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の「クラスが最終的ではない可能性がある」問題を解決する方法を説明しました。

この記事のソースコードはover on GitHubにあります。