简体   繁体   中英

How to autowire a bean in other class in a Spring Boot application?

In a Spring Boot application I have a class as below:

@Service
public class XYZ{
}

I want to use above in other class ABC like:

public class ABC{

    @Autowired
    private XYZ xyx;

}

It throws error that XYZ could not be found. I already have @SpringBootApplication in the class where the main method is written. Hence, this will automatically enable @ComponentScan on the package. ABC is created as a bean in spring configuration file. My understanding is, since XYZ has been annoted with @service, spring scans and creates and registers that bean. How can I access that bean in other class without using xml configuration?

How is ABC instantiated? The ABC object has to be instantiated by Spring.

In other words, the ABC class also has to be some sort of a @Component . It can be autowired by the @SpringBootApplication or in the case of web application, it can be a @Controller .

In addition to what @Sharon Ben Asher said above: Just in case if the error is thrown during a test execution and if the test context makes use of anything other than @SpringBootTest , then there is a chance for that context not to scan for @Service annotation beans.

For example, a test class annotated with @DataJpaTest won't scan for @Service beans; it requires an explicit @ComponentScan to parse it. Details on sample snippets could be found here https://stackoverflow.com/a/52939210/5107365 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM