在@Service中与@Kutlin一起使用的Spring Boot始终为null

问题描述 投票:10回答:2

目前我尝试使用Kotlin重写我的Java Spring Boot应用程序。我遇到了一个问题,在我的所有使用@Service注释的类中,依赖注入都无法正常工作(所有实例都是null)。这是一个例子:

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

在Java中做同样的工作没有任何问题:

@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
}

谷歌为Kotlin和@Autowired提供了许多不同的方法,我尝试但是所有方法都产生了相同的NullPointerException我想知道Kotlin和Java之间的区别是什么以及如何解决这个问题?

java spring spring-mvc spring-boot kotlin
2个回答
10
投票

我只是碰到了完全相同的问题 - 注入效果很好,但在添加@Transactional注释后,所有自动连接的字段都为空。

我的代码:

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

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

} 

这里的问题是默认情况下Kotlin中的方法是final的,所以Spring无法为类创建代理:

 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)
   }

} 

4
投票

你使用哪个Spring Boot版本?由于1.4 Spring Boot基于Spring Framework 4.3,从那以后你应该能够使用构造函数注入而不需要任何@Autowired注释。你试过吗?

它看起来像这样,对我有用:

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

  // your class members

}
© www.soinside.com 2019 - 2024. All rights reserved.