Skip to lesson

Practice: Spring Boot review and interview drill

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most Spring Boot bugs in reviews come from a short list of habits: field injection, a missing @Valid, logic in controllers, SQL built with +, and transactions that never start. Each has a short, reliable fix.

Bug hunt: a controller that breaks the layer rules

A code review is a second developer reading a change before it is merged. A Spring Boot reviewer checks a controller against the rules from this section.

The coupon controller below compiles and answers every request, which is why its bugs are easy to miss. Read it as a reviewer would.

Example 1 · CouponController.java, before review: it compiles and still has four bugs

Runs in: a small Spring Boot lab project (Web MVC, validation, JDBC) on the ShopLite database

CouponController.javaJava
package com.shoplite.lab;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
import com.shoplite.lab.CouponService.Coupon;
@RestController@RequestMapping("/lab/coupons")public class CouponController {
    @Autowired    private CouponService service;
    @PostMapping    public Coupon create(@RequestBody CouponRequest request) {        try {            return service.create(request);        } catch (Exception e) {            return null;        }    }}
Sample output
$ curl -i -X POST http://localhost:8080/lab/coupons -H "Content-Type: application/json" -d '{"code":"FEST10","percent":90}'
HTTP/1.1 200 
Content-Type: application/json
Content-Length: 30
Date: Fri, 16 Oct 2026 06:53:53 GMT

{"code":"FEST10","percent":90}

$ curl -i -X POST http://localhost:8080/lab/coupons -H "Content-Type: application/json" -d '{"code":"FEST10","percent":10}'
HTTP/1.1 200 
Content-Length: 0
Date: Fri, 16 Oct 2026 06:53:54 GMT

What this code does

  • No @Valid, so percent: 90 passes although CouponRequest says at most 50. The second request is a duplicate; the service throws, the catch returns null, and the client gets 200 with an empty body.
  • Field injection with @Autowired hides the dependency and makes the class hard to test without Spring. A create endpoint should answer 201 with a Location header.

Example 2 · CouponController.java, after review

Runs in: a small Spring Boot lab project (Web MVC, validation, JDBC) on the ShopLite database

CouponController.javaJava
package com.shoplite.lab;
import java.net.URI;
import org.springframework.http.HttpStatus;import org.springframework.http.ProblemDetail;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
import com.shoplite.lab.CouponService.Coupon;
import jakarta.validation.Valid;
@RestController@RequestMapping("/lab/coupons")public class CouponController {
    private final CouponService service;
    public CouponController(CouponService service) {          // fix 1: constructor injection        this.service = service;    }
    @PostMapping    public ResponseEntity<Coupon> create(@Valid @RequestBody CouponRequest request) {   // fix 2: @Valid        Coupon coupon = service.create(request);        return ResponseEntity.created(URI.create("/lab/coupons/" + coupon.code())).body(coupon);   // fix 4: 201    }
    @ExceptionHandler(DuplicateCouponException.class)    ProblemDetail duplicate(DuplicateCouponException e) {        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());    }}
Sample output
$ curl -i -X POST http://localhost:8080/lab/coupons -H "Content-Type: application/json" -d '{"code":"FEST10","percent":90}'
HTTP/1.1 400 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:56:57 GMT
Connection: close

{"detail":"Invalid request content.","instance":"/lab/coupons","status":400,"title":"Bad Request"}

$ curl -i -X POST http://localhost:8080/lab/coupons -H "Content-Type: application/json" -d '{"code":"FEST10","percent":10}'
HTTP/1.1 201 
Location: /lab/coupons/FEST10
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:56:57 GMT

{"code":"FEST10","percent":10}

$ curl -i -X POST http://localhost:8080/lab/coupons -H "Content-Type: application/json" -d '{"code":"FEST10","percent":15}'
HTTP/1.1 409 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:56:58 GMT

{"detail":"Coupon FEST10 already exists.","instance":"/lab/coupons","status":409,"title":"Conflict"}

What this code does

  • Constructor injection, @Valid, no try/catch, and ResponseEntity.created(...): 90% is now a 400 before the service runs, a new coupon is a 201 with Location, and a duplicate is a 409 ProblemDetail.
  • The lab app uses Spring's default ProblemDetail (spring.mvc.problemdetails.enabled=true); ShopLite's global handler adds the type and the list of broken fields.
  • The lab's bodies come out A to Z (detail first): it keeps Jackson 3's default property order, while ShopLite sets spring.jackson.mapper.sort-properties-alphabetically=false to follow the contract's order.

A reviewer checks constructor injection, @Valid on the body, the right status code, and no business logic or exception handling inside the controller. Here a 90% fest coupon is accepted although the record says at most 50; a duplicate code gets 200 with an empty body, so the client thinks it worked; and a new coupon returns 200 without a Location header.

The fixed version is shorter. Validation runs before the method, the service throws a meaningful exception, and one handler turns it into a 409 ProblemDetail. The controller is back to its only job: HTTP in, HTTP out.

Bug hunt: SQL built with +

SQL injection happens when text from a user is glued into an SQL statement, so the user can change the statement itself.

An endpoint meant to find one book returns the whole product table, including products outside the Books category. Look at how its SQL text is built.

Example 3 · BookRepository.java: the injectable method and the fixed one

Runs in: a small Spring Boot lab project (Web MVC, validation, JDBC) on the ShopLite database

BookRepository.javaJava
package com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;
import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.stereotype.Repository;
@Repositorypublic class BookRepository {
    public record Book(String sku, String name, BigDecimal price) {    }
    private static final String SELECT = "SELECT sku, name, price FROM products WHERE category_id = 5 AND ";
    private final JdbcClient jdbc;
    BookRepository(JdbcClient jdbc) {        this.jdbc = jdbc;    }
    /** BUG: the user's text becomes part of the SQL. */    public List<Book> findBySkuUnsafe(String sku) {        return jdbc.sql(SELECT + "sku = '" + sku + "'")                .query(Book.class)                .list();    }
    /** FIX: the SQL is fixed; the text travels as a parameter and can never change it. */    public List<Book> findBySku(String sku) {        return jdbc.sql(SELECT + "sku = ?")                .param(sku)                .query(Book.class)                .list();    }}
Sample output
$ curl -s "http://localhost:8080/lab/books-unsafe?sku=BK-CLEAN"
[{"sku":"BK-CLEAN","name":"Clean Code","price":499.00}]
$ curl -s "http://localhost:8080/lab/books-unsafe?sku=x'%20OR%20'1'='1"
[{"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00},{"sku":"MOB-GM35","name":"Samsung Galaxy M35","price":19999.00},{"sku":"MOB-IP15","name":"iPhone 15 128GB","price":69900.00},{"sku":"LAP-IPS3","name":"Lenovo IdeaPad Slim 3","price":42990.00},{"sku":"LAP-HPV15","name":"HP Victus 15 Gaming","price":64990.00},{"sku":"ACC-AD141","name":"boAt Airdopes 141","price":1299.00},{"sku":"ACC-PB20K","name":"Mi Power Bank 20000mAh","price":2199.00},{"sku":"ACC-M331","name":"Logitech M331 Silent Mouse","price":849.00},{"sku":"BK-CLEAN","name":"Clean Code","price":499.00},{"sku":"BK-PRAG","name":"The Pragmatic Programmer","price":650.00},{"sku":"BK-ATOMIC","name":"Atomic Habits","price":399.00},{"sku":"FSH-KURTA","name":"Cotton Kurta","price":899.00},{"sku":"FSH-SHOE","name":"Running Shoes","price":2499.00},{"sku":"HK-COOK3L","name":"Prestige Pressure Cooker 3L","price":1899.00},{"sku":"ACC-USBC1","name":"USB-C Cable 1m","price":199.00}]
$ curl -s "http://localhost:8080/lab/books?sku=x'%20OR%20'1'='1"
[]
$ curl -s "http://localhost:8080/lab/books?sku=BK-CLEAN"
[{"sku":"BK-CLEAN","name":"Clean Code","price":499.00}]

What this code does

  • %20 is a space in a URL, so the second request sends x' OR '1'='1. The unsafe method builds ... category_id = 5 AND sku = 'x' OR '1'='1' and returns all 15 products.
  • The safe method sends the same text as a parameter. MySQL compares it with the sku column as plain data, finds no such SKU and returns []; a real SKU still works.
  • query(Book.class) maps columns to the record's components by name, which is handy for small read-only records.

With "sku = '" + sku + "'", the input x' OR '1'='1 turns the WHERE clause into something that is true for every row, because AND binds tighter than OR. The same idea can read customers' e-mails, or delete data.

The fix is always the same: keep the SQL text fixed and send values as parameters (? or :name). The driver sends the value separately, and MySQL treats it as data, never as SQL. For things that cannot be parameters, such as a sort column, use an allow-list (ShopLite maps price to p.price).

Bug hunt: transactions that do not protect

A silent transaction bug is a method marked @Transactional that still leaves half-saved data, with no error to warn you.

The Transactions lesson showed the causes; in a review, look for each of them. The snippet shows all four in one class.

FeeService.javaJava
@Servicepublic class FeeService {
    public void payAll(List<Long> ids) {        ids.forEach(id -> this.pay(id));          // bug: self-invocation, no proxy    }
    @Transactional    private void pay(Long id) { ... }             // bug: private, never transactional
    @Transactional    public void refund(Long id) throws BankDownException {   // bug: checked, commits        try { writeRefund(id); } catch (DataAccessException e) { log.warn("ignored"); }   // bug: swallowed    }}

Look for these four causes:

  • the method is called with this. from the same class, or it is private;
  • a checked exception leaves it without rollbackFor;
  • a catch block inside it swallows the exception;
  • it writes inside readOnly = true (this one fails loudly: "Connection is read-only").

The fix for each is the same idea: let a runtime exception leave a public method that another bean calls.

Interview drill: core, DI and web (questions 1–10)

These are the Spring Boot questions asked most often in campus and fresher interviews. Say each answer aloud in two sentences, then check it against the lesson where it was taught.

  • What is the difference between Spring and Spring Boot? Spring is the framework: dependency injection, MVC, transactions, JDBC support. Spring Boot sets Spring up for you with starters, auto-configuration, an embedded server and one runnable jar.
  • What is dependency injection, and why constructor injection? The container creates objects and passes in what they need instead of each class calling new. Constructor injection makes dependencies final, required and visible, and lets plain unit tests pass fakes.
  • What is a bean and what is the ApplicationContext? A bean is an object Spring creates and manages; the ApplicationContext is the container that holds them and wires them together.
  • @Component, @Service, @Repository, @Controller: what is the difference? All are found by component scanning. The names show the layer; @Repository also adds database exception translation and @RestController adds JSON responses.
  • How does auto-configuration decide what to create? Each auto-configuration class has conditions such as @ConditionalOnClass and @ConditionalOnMissingBean; it creates a bean only if the library is present and you have not defined your own.
  • What does @SpringBootApplication do? It combines @Configuration, @EnableAutoConfiguration and @ComponentScan starting at its own package, which is why the main class sits in the root package.
  • What are @Primary and @Qualifier for? When two beans fit one injection point, @Primary marks the default and @Qualifier("name") picks one explicitly.
  • What are the default bean scope and its risk? Singleton: one shared object for the whole app. Fields that hold per-request data in a singleton are shared by all threads, so services must be stateless.
  • @RequestParam, @PathVariable and @RequestBody? @PathVariable reads part of the URL (/products/{id}), @RequestParam reads the query string (?page=0), @RequestBody turns the JSON body into a record.
  • How do you return 201 with a Location header? Return ResponseEntity.created(uri).body(dto), building the URI with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").

Interview drill: validation, errors, config, data and tests (questions 11–20)

The second half moves from "how Spring works" to "how you build a real API with it". Interviewers often follow up with "show me where you did that in your project": ShopLite has an example of every answer.

  • How does Bean Validation work in a controller? Constraints such as @NotBlank and @Size sit on the DTO; @Valid on the parameter makes Spring check them and throw MethodArgumentNotValidException (400) before the method runs.
  • How do you handle errors in one place? A @RestControllerAdvice with @ExceptionHandler methods maps exceptions to responses; ShopLite returns RFC 9457 ProblemDetail bodies from one GlobalExceptionHandler.
  • Why DTOs instead of returning entities? DTOs fix the API shape, hide internal fields, and let the database change without breaking clients.
  • What are profiles and how do you activate one? Sets of settings per environment (application-dev.properties, application-prod.properties), chosen with spring.profiles.active=prod or the SPRING_PROFILES_ACTIVE environment variable.
  • @Value or @ConfigurationProperties? @Value for one value; a validated @ConfigurationProperties record for a group, checked at startup.
  • What does Actuator give you? Production endpoints such as /actuator/health (with a database check) and /actuator/info; expose only what you need.
  • JdbcTemplate, JdbcClient or JPA? JdbcClient for plain SQL with full control; JPA when mapping rich object graphs saves code. Both use the same DataSource and transactions.
  • How does @Transactional work and when does it fail? A proxy begins, commits or rolls back around the method. It fails on self-invocation, private methods, swallowed exceptions and (by default) checked exceptions.
  • How do you keep secrets out of the code? ${DB_PASSWORD} placeholders, values from environment variables or a secret store, .env files in .gitignore.
  • How do you test a Spring Boot REST API? Unit tests with plain JUnit, @WebMvcTest slices with MockMvc for controllers, and a few @SpringBootTest integration tests against a real database.

Finish up

Mark complete & continue

Next: Project: ShopLite catalog on MySQL