Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 12

    Spring Boot Annotations

    Annotations are how Boot 3 assembles Orders.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Annotations are how Boot 3 assembles Orders. Startup reads them, builds bean definitions, and wraps some beans in proxies. Knowing the layer matters more than memorizing a poster, because several annotations fail open when a starter or a proxy is missing.

    Stereotypes mark beans: @Service, @Repository (plus persistence exception translation), @Controller. @RestController adds @ResponseBody, so a record becomes JSON. Prefer @GetMapping and @PostMapping. A bare @RequestMapping accepts every verb, including DELETE.

    @Transactional, @Valid, and @PreAuthorize run through a proxy or a starter. A private method, or this.save(), never enters the proxy. On Boot 3 the constraint and JPA packages are jakarta.*. @Validated on a properties record is Spring's annotation; @Valid on a controller parameter is Jakarta's, and both need spring-boot-starter-validation before they reject anything.

    Purpose of this lesson

    Choose the Orders annotation for web, beans, config, transactions, and validation, and recognize a silent no-op: wrong package, missing starter, or a call that never hits the proxy.

    Understanding the topic

    Each annotation answers one question. If you cannot name the question, you do not need it yet.

    • Startup: @SpringBootApplication, @Bean, @ConfigurationPropertiesScan.
    • HTTP: verb mappings, @PathVariable, @RequestBody, @ResponseStatus.
    • Wiring: constructor parameters. @Qualifier and @Primary only when types collide. @Autowired is optional on the sole constructor.
    • Environment: @Profile and @ConditionalOnProperty when a bean must disappear.
    • Advice: @Transactional on the public use case; @ControllerAdvice for one error shape.

    Step-by-step explanation

    1. Mark the application with @SpringBootApplication and the properties scan.
    2. Map GET and POST under /api/orders on a @RestController.
    3. Put Jakarta constraints on the request record and @Valid on the parameter. Add the validation starter.
    4. Annotate OrderService.place with @Transactional, and call it from another bean.

    Informative example

    Constraints on the record, @Valid on the parameter. Creating an order returns 201.

    java
    @RestController
    @RequestMapping("/api/orders")
    public class OrderController {
    private final OrderService orders;
    public OrderController(OrderService orders) { this.orders = orders; }
    @GetMapping("/{id}")
    OrderView getOne(@PathVariable long id) { return orders.get(id); }
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    OrderView create(@Valid @RequestBody CreateOrder body) {
    return orders.place(body.sku(), body.qty());
    }
    }
    record CreateOrder(@NotBlank String sku, @Positive int qty) {}

    These two look protected and are not. Every verb hits one. place calls save on itself, so no transaction starts.

    java
    @RequestMapping("/api/orders/{id}")
    OrderView one(@PathVariable long id) { return orders.get(id); }
    public void place(CreateOrder body) { save(body); }
    @Transactional public void save(CreateOrder body) { /* write */ }

    Real-world use

    TechLearningPro Orders uses verb-specific routes, and place is @Transactional because the insert and the stock reservation commit together. A @Profile("dev") pricing stub exists for laptops and is not @Primary next to the real RestClient. @PreAuthorize shows up with the security module and does nothing until @EnableMethodSecurity is present. Checked exceptions commit unless rollbackFor says otherwise.

    Security implications

    An annotation is not an authentication policy. Orders is public until a security filter chain says otherwise.

    • @Service does not hide a bean. Any controller that injects it can expose it.
    • @CrossOrigin(origins = "*") is unsafe once browsers send cookies. List origins.
    • @PreAuthorize needs the security starter and @EnableMethodSecurity. The starter alone enables HTTP basic with user user and a generated password in the log — a lab default, not a design.
    • A transaction that never starts can decrement stock and drop the order. @NotBlank checks shape; it is not parameterized SQL or output encoding.

    Best practices

    • Class-level /api/orders plus @GetMapping and @PostMapping.
    • Validate at the edge. Use @Validated on configuration records.
    • Put the transaction on the public use case that other beans call.
    • Compose a custom annotation only after the same trio has been copied several times.

    Common mistakes

    • javax.validation or javax.persistence imports on Boot 3. The annotations that run are jakarta.*.
    • Constraints without @Valid, or without the validation starter. The bad SKU reaches the service.
    • @Transactional on a private method or a self-call. Runtime exceptions will not roll back.
    • @RequestMapping with no method, so DELETE enters a read.
    • @Value on a static field, which stays at its initializer. @PreAuthorize copied before method security is enabled.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionHow do @Component, @Service, @Repository, and @RestController differ?+

    Answer

    All of the first three are scan stereotypes. @Repository translates persistence failures into DataAccessException. @RestController is @Controller plus @ResponseBody, so return values are written with Jackson.
    2IntermediateQuestionWhy does @Transactional on a self-call do nothing?+

    Answer

    The proxy is applied after initialization and sees only external calls. Private methods are not advised, and this.save() skips the proxy, so there is nothing to roll back. Put the annotation on the use case other beans invoke.
    3AdvancedQuestion@NotBlank is on the record and a bad body still succeeds. Name the causes.+

    Answer

    Missing @Valid on the parameter, no spring-boot-starter-validation, or a javax.validation import. Configuration records use @Validated and have the same starter requirement. @PreAuthorize is a similar silent no-op without @EnableMethodSecurity.

    Hands-on exercise

    Lab. Change a bare @RequestMapping to @GetMapping and show that DELETE is rejected. Post an empty SKU without @Valid, then add @Valid and the validation starter and expect 400. Move @Transactional from save up to place.

    Summary

    Orders annotations are a contract: scan this, bind this verb, validate this body, commit this use case. They fail open on a javax import, a missing @Valid, a self-invoked @Transactional, or @PreAuthorize without method security. Confirm the runtime honors each one.

    Ready to mark this lesson complete?Track your journey across the entire course.