search

Home  >  Q&A  >  body text

java - spring boot @Autowired

如何在一个没有注解的类中加入一个已经注解的@Autowired?

classA 没有添加xml也没有注解到spring中

classB @Component 已经加入注解

如何在classA 中用@Autowired 注解classB?

如果classA也 @Component了,classB可用,但是不注解就会报错。

阿神阿神2804 days ago781

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:58:21

    Make a SpringContextHolder

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:58:21

    @Component is a bean type annotation of spring. Only after adding this annotation will the bean be managed by spring. If this annotation is not added, spring will not be able to recognize this class, so an error will be reported. If this annotation is added, Then spring knows that these two classes are two beans in spring and can automatically inject each other. My understanding of spring is not deep enough, what I said may be wrong, it is just my personal opinion

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:58:21

    Get it from applicationContext using service name.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:58:21

    @Autowired means injection. To use injection, your class must be managed by spring, which means your class B必须是是一个spring的bean, class A也必须是一个spring的bean, 你报错就是因为你的class A不是一个spring的bean, spring无法帮你注入class B.
    如果要在不是spring bean的class A中使用class B只能手动把class Bset is put in.

    reply
    0
  • Cancelreply