简体   繁体   English

在科特林自动接线

[英]Autowired in Kotlin

i've asked this before but never had any answer that made sense. 我之前曾问过这个问题,但从来没有任何有意义的答案。

if ServiceClass is annotated with @Service in java spring i can do 如果ServiceClass在Java Spring中用@Service注释,我可以做

@Autowired
private ServiceClass serviceClass;

or better yet 或更好

private final ServiceClass serviceClass;

public userManagementClass(ServiceClass serviceClass) {
        this.serviceClass = serviceClass;
    }

Then i changed to kotlin and.. 然后我换成了科特林和..

@Autowired
private lateinit var addressRepository: AddressRepository

where AddressRepository is annotated with @Repository is okey but now the first one, ServiceClass with @Service 使用@Repository注释@Repository位置不错,但现在第一个使用@Service ServiceClass

@Autowired
private lateinit var serviceClass: ServiceClass

and

@Autowired constructor(
      private val serviceClass: ServiceClass
)

both give error No beans of type found Do i now need a constructor for my services in kotlin or what? 都给出错误No beans of type found现在我是否需要在kotlin中为我的服务构造函数?

I've read many articles titled like "understanding kotlin lateinit" and what not, but i think im still missing some core ideas since none of them make any goddamn sense... Kotlin documentation is okey, but only for concepts you already know.. otherwise it also is very confusing. 我读过许多标题为“了解Kotlin Lateinit”的文章,但没有,但我认为我仍然缺少一些核心思想,因为它们都没有任何该死的意义……Kotlin文档是不错的,但仅适用于您已经知道的概念。否则也很混乱。

EDIT appears that giving ServiceClass a constructor didnt do anything either 编辑似乎给ServiceClass构造函数没有做任何事情

In kotlin (and in Java I think) you can inject your dependencies in the constructor like this: 在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

this is the same that: 这是相同的:

@Service
class ServiceClass {
    @Autowired
    private lateinit var repository: AddressRepository

    // Do stuff here
}

@Repository
class AddressRepository

but it allow you to make unit tests without the need of a Spring Context (@SpringBootTest). 但是它允许您进行单元测试,而无需Spring Context(@SpringBootTest)。

Then you can inject your service in another the same way 然后,您可以以其他相同方式注入服务

@Service
class OtherService constructor(
    private val service: ServiceClass
) {
    // Other stuff here
}

There's no bean problem with this code for me. 此代码对我来说没有bean问题。 (IntelliJ 2019.1.1) (IntelliJ 2019.1.1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM