目前,我尝试使用 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;
}
如果我用注释该组件@Component
在 Kotlin 中一切正常:
@Component
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) {
//dsl and teamService are injected properly
}
Google 为 Kotlin 提供了许多不同的方法@Autowired
我尝试过,但结果都一样NullPointerException
我想知道 Kotlin 和 Java 之间有什么区别以及如何解决这个问题?
我刚刚遇到了完全相同的问题 - 注入效果很好,但添加 @Transactional 注释后,所有自动装配字段都为空。
My code:
@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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)