@Component, @Service, @Repository — Spring Technical Interview Questions & Answers
Semantic stereotypes for different bean roles.
@Component, @Service, @Repository
- These annotations all make beans, but names show the role.
- @Component: Generic Spring bean.
- @Service: Business logic layer.
- @Repository: Data access layer (also helps translate some DB exceptions).
- @Controller / @RestController: Web layer.
- Why stereotypes matter: Clear architecture and better readability for teams.
- Putting DB code in @Controller because ‘it works’.
- Same technical registration, different meaning for design.
Technical Interview Tip: Stereotypes communicate layer intent.
Code Examples for @Component, @Service, @Repository
@Component, @Service, @Repository — 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; }@Component, @Service, @Repository — spring injects beans; prefer constructor injection (@RequiredArgsConstructor or explicit ctor) over field @Autowired.
How to Explain @Component, @Service, @Repository to an Interviewer
What is @Component, @Service, @Repository (sb)?
Used for Student entity H2 / MySQL Not just the heading
Give one small example of @Component, @Service, @Repository (sb).
@Entity + JpaRepository Semantic stereotypes for different bean roles
What mistake do beginners make with @Component, @Service, @Repository (sb)?
LazyInitializationException after the session closes Show the fix
Where do you use @Component, @Service, @Repository (sb)?
H2 / MySQL Student entity