2016-02-18 14 views
22

Kotlinで次のようにすることはできますか?kotlinの@Autowiredのような春の注釈の使い方は?

@Autowired 
internal var mongoTemplate: MongoTemplate 

@Autowired 
internal var solrClient: SolrClient 
+1

あなたは試したことがありますか?もう少し建設的なものにするには、[Spring Boot template](https://kotlinlang.org/docs/tutorials/spring-boot-restful.html)全体がありますが、その答えは「はい」です。 – mabi

+0

@mabiチュートリアルリンクありがとうございます:) – eendroroy

答えて

53

を、あなたはいくつかのオプションを持って、私は注釈付きのコンストラクタをお勧めしますが、lateinitまた動作し、いくつかのケースでは、おそらく便利:

Lateinit:

@Component 
class YourBean { 

    @Autowired 
    lateinit var mongoTemplate: MongoTemplate 

    @Autowired 
    lateinit var solrClient: SolrClient 
} 

コンストラクタ:

@Component 
class YourBean @Autowired constructor(
    private val mongoTemplate: MongoTemplate, 
    private val solrClient: SolrClient 
) { 
    // code 
} 

春4.3とコンストラクタ:

@Component 
class YourBean(
    private val mongoTemplate: MongoTemplate, 
    private val solrClient: SolrClient 
) { 
    // code 
} 

コンストラクタのバージョンでは、すべての依存関係を確認豆の作成時間と注入されたすべてのフィールド - val、他の手でのlateinit注入フィールドvarのみであり、実行時フットプリントはほとんどありません。そして、コンストラクタでクラスをテストするために、リフレクションは必要ありません。

リンク:

  1. Documentation on lateinit
  2. Documentation on constructors
  3. Developing Spring Boot applications with Kotlin
5

はい、Javaアノテーションは、ほとんどのJavaのようにKotlinでサポートされています。あなたはクラスの主コンストラクタに注釈を付ける必要がある場合は、あなたがコンストラクタキーワードを追加する必要がhttps://kotlinlang.org/docs/reference/annotations.html

から

: 一つ落とし穴がプライマリコンストラクタに注釈であることは明白な「コンストラクタ」キーワードが必要ですコンストラクタ宣言、およびその前に注釈を追加します。これが可能であることを確認するために

class Foo @Inject constructor(dependency: MyDependency) { 
    // ... 
} 
関連する問題