@Service中与Kotlin一起使用的Spring Boot @Autowired始终为null [英] Spring Boot @Autowired with Kotlin in @Service is always null

查看:471
本文介绍了@Service中与Kotlin一起使用的Spring Boot @Autowired始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 dependency injection is not working correctly (all instances are null). Here is an example:

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

在Java中执行相同操作不会出现任何问题:

Doing the same in Java works without any problems:

@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注释组件,则一切正常:

If I annotate the component with @Component in Kotlin everything works fine:

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

Google为Kotlin和@Autowired提供了许多不同的方法,我尝试了这些方法,但都得出了相同的NullPointerException 我想知道Kotlin和Java之间的区别是什么,我该如何解决?

Google provided many different approaches for Kotlin and @Autowired which I tried but all resulted in the same NullPointerException I would like to know what the difference between Kotlin and Java is and how I can fix this?

推荐答案

我遇到了完全相同的问题-注入效果很好,但是在添加@Transactional注释后,所有自动关联的字段均为空.

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

我的代码:

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

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

} 

这里的问题是,这些方法在Kotlin中默认为final,因此Spring无法为该类创建代理:

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:

固定代码:

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

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

} 

这篇关于@Service中与Kotlin一起使用的Spring Boot @Autowired始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆