Annotations — Labels Spring Reads
Open any Spring Boot class and the first thing you see is a stack of @ words. They are not decoration. Each one is a label that Spring reads at startup and acts on. Once you can sort them into a few families, a new codebase stops looking cryptic.
The rule
An annotation is a label; Spring reads the label and does the work.
An annotation adds information to a class, method, field or parameter without changing its code. On its own it does nothing. Spring scans your classes at startup, notices the labels, and reacts.
The labels you will use daily fall into four families:
| Family | Labels | What Spring does |
|---|---|---|
| Make a bean | @Component, @Service, @Repository, @Controller, @RestController |
Creates the class as a bean during component scanning |
| Define beans by hand | @Configuration with @Bean methods |
Calls each @Bean method and registers what it returns |
| Inject | @Autowired, @Qualifier, @Value, @Primary |
Chooses what goes into a constructor, field or parameter |
| Add behaviour | @Transactional, @GetMapping, @PreAuthorize |
Wraps or routes calls to the method |
@Service and @Repository are both specialised forms of @Component. They create beans the same way, but they tell a reader which layer the class belongs to, and @Repository also makes Spring translate database errors into its own exception types.
@Bean is for objects you cannot annotate, usually classes from a library:
@Configuration
public class ClockConfig {
@Bean
public Clock clock() {
return Clock.systemDefaultZone(); // LoanService injects this to compute due dates
}
}And one label holds three: @SpringBootApplication combines @SpringBootConfiguration (a kind of @Configuration), @EnableAutoConfiguration, and @ComponentScan. Component scanning starts at the package of that class and covers every package below it.