如何让@Autowired在普通类中工作?

2024-04-22

这是我所得到的:

@Component
class FooController {

    fun createFoo() {
        val foo = FooEntity()
        foo.name = "Diogo"

        fooRepository.save(foo)
    }

    @Autowired
    internal lateinit var fooRepository: FooRepository

}

当尝试打电话时createFoo(),我收到以下错误:

kotlin.UninitializedPropertyAccessException: lateinit property fooRepository has not been initialized

我以为添加一个@Component在顶部将使我的课程可以被 Spring 发现,从而使@Autowired工作,但也许我弄错了?


只需添加@Component到班级还不够。

1)当你使用@Component您必须确保通过组件扫描来扫描该类。这取决于您如何引导应用程序,但您可以使用<context:component-scan base-package="com.myCompany.myProject" />对于 XML 配置或@ComponentScan用于java配置。

如果您使用 Spring boot - 则无需声明@ComponentScan你自己,因为@SpringBootApplication继承它,默认情况下它会扫描当前包及其所有子包中的所有类。

2)你必须从spring上下文中获取bean。创建一个对象new不管用。

基本上有两种方法可以从应用程序上下文中获取 bean:

  • 如果您有权访问 ApplicationContext 对象,那么您可以执行以下操作:

ApplicationContext ctx = ...; MyBean mb = ctx.getBean(MyBean.class);//getting by type

  • 在上下文中声明的任何 spring bean 都可以使用依赖注入来访问其他 bean (@Autowired)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让@Autowired在普通类中工作? 的相关文章

随机推荐