gpt4 book ai didi

java - @Service 中带有 Kotlin 的 Spring Boot @Autowired 始终为空

转载 作者:IT老高 更新时间:2023-10-28 13:34:02 25 4
gpt4 key购买 nike

目前我尝试用 Kotlin 重写我的 Java Spring Boot 应用程序。我遇到了一个问题,在我所有使用 @Service 注释的类中,依赖注入(inject)都无法正常工作(所有实例都是 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
}

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

最佳答案

我刚刚遇到了完全相同的问题 - 注入(inject)效果很好,但是在添加 @Transactional 注释后,所有 Autowiring 的字段都为空。

我的代码:

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

}

关于java - @Service 中带有 Kotlin 的 Spring Boot @Autowired 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41298289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com