@ComponentScan — Spring Technical Interview Questions & Answers
Telling Spring where to look for annotated beans.
@ComponentScan
- @ComponentScan tells Spring which packages to search for beans.
- It looks for @Component, @Service, @Repository, @Controller, and similar.
- By default, scan starts from the package of the @SpringBootApplication class.
- You can set basePackages if your code lives elsewhere.
- Class not scanned because it is outside the scanned packages.
- If a bean is ‘not found’, check package scan first.
Technical Interview Tip: Missing bean? Check @ComponentScan package range.
Code Examples for @ComponentScan
@ComponentScan — working example
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Service
class GreetingService {
String greet(String name) {
return "Hello, " + name;
}
}
@RestController
@RequiredArgsConstructor // constructor injection of final fields
class GreetingController {
private final GreetingService greetings;
@GetMapping("/greet")
String greet() {
return greetings.greet("Spring");
}
}
// Without Lombok — same idea:
// GreetingController(GreetingService greetings) { this.greetings = greetings; }@ComponentScan — spring injects beans; prefer constructor injection (@RequiredArgsConstructor or explicit ctor) over field @Autowired.
How to Explain @ComponentScan to an Interviewer
What is @ComponentScan (sb)?
Used for a short @ComponentScan sb example a small REST app Not just the heading
Give one small example of @ComponentScan (sb).
the smallest @ComponentScan sb example you can type Telling Spring where to look for annotated beans
What mistake do beginners make with @ComponentScan (sb)?
only saying “@ComponentScan sb” with no example Show the fix
Where do you use @ComponentScan (sb)?
a small REST app a short @ComponentScan sb example