Skip to the workspace
Pebellslearn by building
The Spring Core  ›  Lesson

Annotations — Labels Spring Reads

Annotations 12 minAnnotations are labels that Spring reads at startup to make beans, wire them together, or add behaviour, and component scanning only covers packages under the main class.

spring boot / Annotations — Labels Spring Reads

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.