tech_questions
tech_questions

Reputation: 273

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?

Upvotes: 2

Views: 4518

Answers (2)

Raj
Raj

Reputation: 936

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.

Upvotes: 0

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

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.

Upvotes: 1

Related Questions