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.
The shortcut
For any annotation you meet, ask "Does it make a bean, wire a bean, or change behaviour?" That one question tells you what will go wrong if it is missing: no bean, a failed injection, or a feature that silently does not happen.
The error
No qualifying bean of type 'BookRepository'at startup.
The package trap is common: keep the main application class in the root package, and put everything else in sub-packages beneath it.
Drills
Answer fast — trust the rule.
Which family does @Service belong to?
You need a bean of a library class, java.time.Clock, that you cannot edit. What do you use?
Which three annotations does @SpringBootApplication combine?
LibraryApplication is in com.example.library. Which class will component scanning find?
Remember
- An annotation is a label; Spring reads the label and does the work.
- Ask "make a bean, wire a bean, or change behaviour?" to predict what breaks when it is missing.
- Trap: classes outside the main class's package are never scanned.
