Spring Boot @Autowired with Kotlin in @Service is always null

后端 未结 3 1480
闹比i
闹比i 2021-02-19 00:21

Currently I try to rewrite my Java Spring Boot Application with Kotlin. I encountered a problem that in all of my classes which are annotated with @Service the depe

3条回答
  •  执念已碎
    2021-02-19 01:08

    I just bumped into exactly same issue - injection worked well, but after adding @Transactional annotation all the autowired fields are null.

    My code:

    @Service
    @Transactional  
    open class MyDAO(val jdbcTemplate: JdbcTemplate) {
    
       fun update(sql: String): Int {
           return jdbcTemplate.update(sql)
       }
    
    } 
    

    The problem here is that the methods are final by default in Kotlin, so Spring is unable to create proxy for the class:

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

    "Opening" the method fixes the issue:

    Fixed code:

    @Service
    @Transactional  
    open class MyDAO(val jdbcTemplate: JdbcTemplate) {
    
       open fun update(sql: String): Int {
           return jdbcTemplate.update(sql)
       }
    
    } 
    

提交回复
热议问题