2

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?

Karan Khanna
  • 1,947
  • 3
  • 21
  • 49
tech_questions
  • 263
  • 5
  • 14

2 Answers2

1

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.

Karan Khanna
  • 1,947
  • 3
  • 21
  • 49
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

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.

Raj
  • 778
  • 1
  • 10
  • 14