问题描述
这就是我所拥有的:
@Component
class FooController {
fun createFoo() {
val foo = FooEntity()
foo.name = "Diogo"
fooRepository.save(foo)
}
@Autowired
internal lateinit var fooRepository: FooRepository
}
尝试呼叫createFoo()
时,出现以下错误:
When trying to call createFoo()
, I get the following error:
kotlin.UninitializedPropertyAccessException: lateinit property fooRepository has not been initialized
我认为在顶部添加@Component
可以使我的班级在Spring之前可以被发现,从而使@Autowired
正常工作,但是也许我弄错了吗?
I thought that adding a @Component
at the top would make my class discoverable by Spring and hence make @Autowired
work, but maybe I got it wrong?
推荐答案
所以我对Spring还是很陌生,他试图通过new
而不是在所有地方创建@Autowire
来创建FooController
的实例来调用FooController
.当我添加FooController
作为对其进行调用的类的依赖项时,它起作用了.
So I'm very new to Spring and was trying to call FooController
by creating a instance of it through new
instead of @Autowire
ing everywhere. When I added FooController
as a dependency of the class it was being called from, it worked.
这篇关于如何使@Autowired在常规课程中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!