2016-12-23 13 views
6

現在、私はKotlinでJava Spring Boot Applicationを書き直そうとしています。 @Serviceで注釈が付けられているすべてのクラスで、依存関係注入が正しく機能していないという問題に遭遇しました(すべてのインスタンスはnullです)。ここでは一例です:Javaで同じことを春のブート@AutowiredのKotlinは@サービスで常にnullです

@Service 
@Transactional 
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) { 
    //dsl and teamService are null in all methods 
} 

は何の問題もなく動作します。

@Service 
@Transactional 
public class UserServiceController 
{ 
    private DSLContext dsl; 
    private TeamService teamService; 

    @Autowired 
    public UserServiceController(DSLContext dsl, 
          TeamService teamService) 
    { 
     this.dsl = dsl; 
     this.teamService = teamService; 
    } 

私はKotlinのすべてで@Componentを持つコンポーネントが正常に動作注釈を付ける場合:

@Component 
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) { 
    //dsl and teamService are injected properly 
} 

グーグル私が試みたコットリーンと@Autowiredのための多くの異なるアプローチを提供しましたが、すべて同じ結果になりましたNullPointerException 私はKotlinとJavaの違いを知りたいのですが、どうすればこの問題を解決できますか?

+0

valをvarに変更しようとしましたか? –

+0

[SpringプロキシクラスとKotlinでのNull Pointer例外の可能な複製](http://stackoverflow.com/questions/37431817/null-pointer-exception-in-spring-proxy-class-and-kotlin) – miensol

+0

はい私はすでに両方を試みた。 – Deutro

答えて

4

どのSpringブートバージョンを使用していますか? 1.4 Spring BootはSpring Framework 4.3に基づいているので、その後は@Autowired注釈なしでコンストラクタインジェクションを使用できるはずです。あなたはそれを試しましたか?

それはこのように見て、私の作品になります。

@Service 
class UserServiceController(val dsl: DSLContext, val teamService: TeamService) { 

    // your class members 

} 
+1

スーパードッグ:) – davidxxx

+0

こんにちは、デフォルトのコンストラクタが見つかりませんでした。 - 可能? ***(参考の一部はリポジトリです)*** – jasperagrante

+0

私はすでに私の問題を解決しました。 'デフォルトのコンストラクターがない 'か@Autowiredがすでに見つかっている人のために。コンストラクターにデフォルト値が設定されていないことを確認してください。 – jasperagrante

2

私はまったく同じ問題にぶつかった - 注入がうまく働いたが、@Transactionalのアノテーションを追加した後、すべてのautowiredフィールドがNULLです。

マイコード:

@Service 
@Transactional 
open class MyDAO(val jdbcTemplate: JdbcTemplate) { 

    fun update(sql: String): Int { 
     return jdbcTemplate.update(sql) 
    } 

} 

春は、クラスのプロキシを作成することができませんので、ここでの問題は、方法はKotlinで、デフォルトでは最終的なものであるということである。

o.s.aop.framework.CglibAopProxy: Unable to proxy method [public final int org.mycompany.MyDAO.update(... 

「オープニング」この方法は、問題を修正:

固定コード:

@Service 
@Transactional 
open class MyDAO(val jdbcTemplate: JdbcTemplate) { 

    open fun update(sql: String): Int { 
     return jdbcTemplate.update(sql) 
    } 

} 
+0

Kotlinには、これらのクラスを開くためのビルドプラグインがあります。https://kotlinlang.org/docs/reference/compiler-plugins.html –

関連する問題