本文介绍了如何使@Autowired在常规课程中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

@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 @Autowireing everywhere. When I added FooController as a dependency of the class it was being called from, it worked.

这篇关于如何使@Autowired在常规课程中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 09:07