我以前问过这个问题,但从来没有任何有意义的答案。
如果ServiceClass在java spring中使用@Service进行注释,我可以这样做。
@Autowired
private ServiceClass serviceClass;或者更好
private final ServiceClass serviceClass;
public userManagementClass(ServiceClass serviceClass) {
this.serviceClass = serviceClass;
}然后我换了kotlin然后..。
@Autowired
private lateinit var addressRepository: AddressRepository在AddressRepository中使用@Repository进行注释是可以的,但是现在是第一个,ServiceClass和@Service
@Autowired
private lateinit var serviceClass: ServiceClass和
@Autowired constructor(
private val serviceClass: ServiceClass
)这两者都给出了错误的No beans of type found,我现在需要一个构造函数为我的服务在kotlin或什么?
我读过许多题为“理解科特林迟到”之类的文章,但我认为我仍然缺少一些核心思想,因为它们都没有任何意义.Kotlin文档是可以的,但只适用于您已经知道的概念。否则,它也是非常混乱的。
编辑似乎给ServiceClass构造函数也没有做任何事情
发布于 2019-04-30 09:35:24
在kotlin (在Java中,我认为)中,您可以在构造函数中注入依赖项,如下所示:
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
@Service
class ServiceClass constructor(
private val repository: AddressRepository
) {
// Do stuff here
}
@Repository
class AddressRepository这与以下情况相同:
@Service
class ServiceClass {
@Autowired
private lateinit var repository: AddressRepository
// Do stuff here
}
@Repository
class AddressRepository但是它允许您进行单元测试而不需要Spring上下文(@SpringBootTest)。
然后,您可以以另一种方式注入您的服务。
@Service
class OtherService constructor(
private val service: ServiceClass
) {
// Other stuff here
}这段代码对我来说没有什么问题。(IntelliJ 2019.1.1)
https://stackoverflow.com/questions/55917700
复制相似问题