spring autowiring not working from a non-spring managed class

前端 未结 10 892
暗喜
暗喜 2020-12-03 06:43

I have a class (Class ABC) that\'s instantiated by calling the constructor. Class ABC in turn has a helper class (Class XYZ) injected using auto-wired.

Ours is a Sp

10条回答
  •  遥遥无期
    2020-12-03 07:30

    For noobs like me who do basic Spring Boot and aren't familiar with the lingo:

    • Your Services, Repos etc are all Beans
    • You can get your Beans from the ApplicationContext

    Ashish's answer works for me, but this article provides a bit more explanation imo.

    If you don't know the name of the bean you want, try looking in this array:

    String[] names = context.getBeanDefinitionNames();
    

    If you're confused by the talk of 'component scan' and config files, it may help to know that the @SpringBootApplication annotation (which you might find near your main() method) implicitly calls @Configuration and @ComponentScan.

    This means all files in that package (declared at the top of the main class) are picked up by Spring, and any beans you want to add can be written alongside main()

提交回复
热议问题