Spring Boot Annotations
Annotations are how Boot 3 assembles Orders.
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.
@Qualifierand@Primaryonly when types collide.@Autowiredis optional on the sole constructor. - Environment:
@Profileand@ConditionalOnPropertywhen a bean must disappear. - Advice:
@Transactionalon the public use case;@ControllerAdvicefor one error shape.
Step-by-step explanation
- Mark the application with
@SpringBootApplicationand the properties scan. - Map
GETandPOSTunder/api/orderson a@RestController. - Put Jakarta constraints on the request record and
@Validon the parameter. Add the validation starter. - Annotate
OrderService.placewith@Transactional, and call it from another bean.
Informative example
Constraints on the record, @Valid on the parameter. Creating an order returns 201.
@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.
@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.
@Servicedoes not hide a bean. Any controller that injects it can expose it.@CrossOrigin(origins = "*")is unsafe once browsers send cookies. List origins.@PreAuthorizeneeds the security starter and@EnableMethodSecurity. The starter alone enables HTTP basic with useruserand a generated password in the log — a lab default, not a design.- A transaction that never starts can decrement stock and drop the order.
@NotBlankchecks shape; it is not parameterized SQL or output encoding.
Best practices
- Class-level
/api/ordersplus@GetMappingand@PostMapping. - Validate at the edge. Use
@Validatedon 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.validationorjavax.persistenceimports on Boot 3. The annotations that run arejakarta.*.- Constraints without
@Valid, or without the validation starter. The bad SKU reaches the service. @Transactionalon a private method or a self-call. Runtime exceptions will not roll back.@RequestMappingwith no method, soDELETEenters a read.@Valueon a static field, which stays at its initializer.@PreAuthorizecopied before method security is enabled.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionHow do @Component, @Service, @Repository, and @RestController differ?+
Answer
@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
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
@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.