Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 66 ยท Practice and Review

Practice Exercises with Solutions

Fifteen graded Spring Boot exercises on dependency injection, configuration, REST, validation, JPA and security, each with a full solution and live stand-ins.

Reading about Spring Boot teaches you the vocabulary. Writing it teaches you the habits. This page gives you fifteen exercises, graded from easy to hard, on the topics that fill most real projects: dependency injection, configuration, REST, validation, JPA and security. Every exercise has a task, a hint in the task itself and a full solution that you can open once you have tried.

Spring Boot cannot run on this site, so write the solutions in your own project (create one with Creating a Project) and compare them with the ones here. Where an idea can be shown in plain Java, a live stand-in lets you edit and run it right here: exercise 3 is a tiny container that picks between two beans, and exercise 9 is a validator that reads annotations. The stand-ins are teaching models, not Spring itself, and each one says so.

How to practice: type each solution instead of pasting it, make one deliberate mistake (remove an annotation, misspell a property) and read the error. The next lesson, Common Mistakes and Debugging Startup Failures, shows how to read what you see.

Three levels, five exercises each

Easy (1-5) Beans, configuration, profiles.
Medium (6-10) REST, pagination, validation, errors.
Hard (11-15) JPA, N+1, transactions, security.

Try first, open the solution second.

1 / 2

Easy: beans and configuration

Exercise 1: Constructor injection

A service uses field injection. Rewrite it so the dependency is a final field set through the constructor, and explain why that is better. Background: IoC and Dependency Injection.

Java
@Service
public class InvoiceService {
    @Autowired
    private TaxCalculator taxCalculator;

    public int totalWithTax(int netCents) {
        return netCents + taxCalculator.taxFor(netCents);
    }
}
Solution
Java
@Service
public class InvoiceService {

    private final TaxCalculator taxCalculator;

    public InvoiceService(TaxCalculator taxCalculator) {
        this.taxCalculator = taxCalculator;
    }

    public int totalWithTax(int netCents) {
        return netCents + taxCalculator.taxFor(netCents);
    }
}

With a single constructor, @Autowired is not needed. The class can now be created in a plain unit test with new InvoiceService(fakeCalculator), the field can be final, and a missing dependency fails at startup instead of with a NullPointerException later.

Exercise 2: A bean for something you do not own

Your code calls Instant.now() in many places, which makes tests unpredictable. Register a Clock bean, inject it into a TokenService and write down how a test would use a fixed clock. Background: @Configuration and @Bean.

Solution
Java
@Configuration
public class TimeConfig {
    @Bean
    public Clock clock() {
        return Clock.systemUTC();
    }
}

@Service
public class TokenService {
    private final Clock clock;

    public TokenService(Clock clock) {
        this.clock = clock;
    }

    public boolean isExpired(Instant expiresAt) {
        return clock.instant().isAfter(expiresAt);
    }
}

// in a test, no Spring needed:
var fixed = Clock.fixed(Instant.parse("2026-11-08T10:00:00Z"), ZoneOffset.UTC);
assertThat(new TokenService(fixed).isExpired(Instant.parse("2026-11-08T09:00:00Z"))).isTrue();

Clock is a class from the JDK, so you cannot annotate it with @Component; an @Bean method is how third-party and JDK types enter the container. The bean name is the method name, clock.

Exercise 3: Two beans, one injection point

There are two implementations of PaymentGateway. OrderService should get the wallet gateway by default, but RefundService must always get the card gateway. Make both injections unambiguous without changing the interface. Background: Qualifiers, @Primary and Collections.

Edit and run the stand-in below. It is a small container that resolves constructor parameters by type, honours @Primary and @Qualifier, and fails when a choice is ambiguous. Real Spring does the same job with much more machinery. Run it once, then change new Container(true, ...) to false to see the error message that appears when no bean is marked primary.

Java A container that resolves two candidates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Solution
Java
public interface PaymentGateway { void charge(int cents); }

@Component
public class CardGateway implements PaymentGateway { /* ... */ }

@Component
@Primary
public class WalletGateway implements PaymentGateway { /* ... */ }

@Service
public class OrderService {
    private final PaymentGateway gateway;           // gets WalletGateway (the primary)
    public OrderService(PaymentGateway gateway) { this.gateway = gateway; }
}

@Service
public class RefundService {
    private final PaymentGateway gateway;
    public RefundService(@Qualifier("cardGateway") PaymentGateway gateway) {
        this.gateway = gateway;
    }
}

@Primary is the default choice, @Qualifier names a specific bean and wins over the default. The default bean name of CardGateway is cardGateway.

Exercise 4: Type-safe settings

Bind these properties to a record named MailProperties: app.mail.from (required, must be non-blank), app.mail.timeout (default five seconds) and app.mail.retries (default 3, at least 1). Background: Type-Safe @ConfigurationProperties.

Solution
Java
@ConfigurationProperties(prefix = "app.mail")
@Validated
public record MailProperties(
        @NotBlank String from,
        @DefaultValue("5s") Duration timeout,
        @DefaultValue("3") @Min(1) int retries) {}

@SpringBootApplication
@ConfigurationPropertiesScan
public class ShopApplication { /* ... */ }
YAML
app:
  mail:
    from: [email protected]
    retries: 5

If from is missing or blank, the application fails at startup with a binding error that names the property. That is the point: bad configuration should stop the deployment, not surprise you at the first email.

Exercise 5: Same jar, different environments

The default log level is INFO. Production must use WARN for com.example and read the database password from the environment, while the dev profile uses DEBUG. Show the files and how each environment starts. Background: Profiles and Environment-Specific Config.

Solution
YAML
# application.yml (shared defaults)
logging:
  level:
    com.example: INFO
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
YAML
# application-dev.yml
logging:
  level:
    com.example: DEBUG
YAML
# application-prod.yml
logging:
  level:
    com.example: WARN
spring:
  datasource:
    password: ${DB_PASSWORD}
Terminal
# development
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev

# production
SPRING_PROFILES_ACTIVE=prod DB_PASSWORD='from-the-secret-store' java -jar shop.jar

The password is never in a file in the repository. A profile-specific file only overrides the keys it mentions.

Medium: REST, validation and errors

Exercise 6: A lookup endpoint that can say no

Add GET /books/{id} that returns the book as JSON, or an HTTP 404 with a Problem Details body when it does not exist. Background: REST Controllers and Error Handling and Problem Details.

Solution
Java
@RestController
@RequestMapping("/books")
public class BookController {

    private final BookService books;

    public BookController(BookService books) {
        this.books = books;
    }

    @GetMapping("/{id}")
    public BookResponse get(@PathVariable long id) {
        return books.find(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Book " + id + " not found"));
    }
}

With spring.mvc.problemdetails.enabled=true, Boot renders ResponseStatusException as an application/problem+json body with status, title and detail. Returning Optional from the controller would not give a 404 by itself.

Exercise 7: Create and say where it lives

POST /books creates a book. It must answer 201 Created with a Location header pointing at the new resource, and return the created book.

Solution
Java
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
    BookResponse created = books.create(request);
    URI location = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(created.id())
            .toUri();
    return ResponseEntity.created(location).body(created);
}

fromCurrentRequest() builds on the URL of the POST, so the header is correct behind a proxy or under a different context path, with no hard-coded host.

Exercise 8: Pages, not everything

GET /books currently returns every book. Return pages of 20 sorted by title by default, accept ?page=, ?size= and ?sort=, and refuse sizes above 100. Background: Designing a Clean API.

Solution
Java
@GetMapping
public Page<BookResponse> list(@PageableDefault(size = 20, sort = "title") Pageable pageable) {
    return books.findAll(pageable);
}
YAML
spring:
  data:
    web:
      pageable:
        max-page-size: 100

Requests above the maximum are capped to 100 rather than rejected. Allow sorting only on columns you have indexed, or one request such as ?sort=description can become a slow query.

Exercise 9: Validate the input

Reject a create-book request when the title is blank, the ISBN is not exactly 13 digits or the price is not positive. Return all problems at once. Background: Bean Validation.

The stand-in below is a miniature validator: annotations on a record's components, read by reflection, producing one message per violation. Real Bean Validation is a standard with many more constraints, groups and message interpolation; this version just shows the mechanism. Add a @Positive check of your own on a new field to extend it.

Java A reflection validator for a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Solution
Java
public record CreateBookRequest(
        @NotBlank String title,
        @Pattern(regexp = "\\d{13}", message = "must be exactly 13 digits") String isbn,
        @Positive int priceCents) {}

@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) { /* ... */ }

@Valid on the parameter triggers validation before the method body runs. Without it the annotations on the record do nothing. All violations are collected into one MethodArgumentNotValidException, which exercise 10 turns into a clear response. @NotBlank rejects null, empty and whitespace-only strings, unlike @NotNull.

Exercise 10: One place for error responses

Make validation failures return 400 with an application/problem+json body that lists each field and its message, without repeating try/catch code in controllers. Background: Error Handling and Problem Details.

Solution
Java
@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail onInvalid(MethodArgumentNotValidException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.BAD_REQUEST, "Request validation failed");
        problem.setTitle("Invalid request");
        Map<String, String> errors = new LinkedHashMap<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.putIfAbsent(error.getField(), error.getDefaultMessage());
        }
        problem.setProperty("errors", errors);
        return problem;
    }
}

A client now receives {"title":"Invalid request","status":400,"detail":"Request validation failed","errors":{"isbn":"must be exactly 13 digits"}}. Never put stack traces or exception class names in the body.

Hard: data and security

Exercise 11: Queries from method names

Given Book with a title, a priceCents and a ManyToOne author with a name, add repository methods that find the books of an author sorted by title, and return only title and price for a list screen. Background: Spring Data JPA Repositories.

Solution
Java
public record BookSummary(String title, int priceCents) {}

public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorNameOrderByTitleAsc(String authorName);

    List<BookSummary> findSummariesByAuthorName(String authorName);
}

The first method is derived from its name: AuthorName navigates author.name. The second returns a DTO projection, so Hibernate selects only the two columns instead of loading entities. If a derived name gets long or unreadable, switch to an @Query with a clear name.

Exercise 12: Fix the N+1

A page lists authors with the titles of their books. The log shows one query for the authors and one more for every author. Fix it in two ways. Background: Entity Relationships and the N+1 Problem.

Solution
Java
public interface AuthorRepository extends JpaRepository<Author, Long> {

    @Query("select a from Author a join fetch a.books")
    List<Author> findAllWithBooks();

    @EntityGraph(attributePaths = "books")
    List<Author> findByNameStartingWith(String prefix);
}

Both load authors and books in one SQL join. Do not combine a collection join fetch with paging: Hibernate then paginates in memory and warns. For paged lists, load the page of authors first and fetch their books in a second query by id, or enable batch fetching with spring.jpa.properties.hibernate.default_batch_fetch_size=50.

Exercise 13: The transaction that did nothing

archiveAll() calls archive(order), which is annotated @Transactional(propagation = REQUIRES_NEW) so each order gets its own transaction. In practice, one failure rolls back everything. Explain and fix. Background: Transactions with @Transactional.

Java
@Service
public class ArchiveService {
    public void archiveAll(List<Order> orders) {
        orders.forEach(this::archive);          // calls on this: no proxy involved
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void archive(Order order) { /* ... */ }
}
Solution

@Transactional works through a proxy placed around the bean. A call from outside goes through the proxy, but this.archive(...) is a plain Java call that skips it, so the annotation is ignored. Move the method to another bean:

Java
@Service
public class OrderArchiver {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void archive(Order order) { /* ... */ }
}

@Service
public class ArchiveService {
    private final OrderArchiver archiver;

    public ArchiveService(OrderArchiver archiver) {
        this.archiver = archiver;
    }

    public void archiveAll(List<Order> orders) {
        for (Order order : orders) {
            try {
                archiver.archive(order);        // goes through the proxy
            } catch (RuntimeException e) {
                log.warn("Could not archive order {}", order.getId(), e);
            }
        }
    }
}

TransactionTemplate is an alternative when you want programmatic control inside one class.

Exercise 14: Lock down the API

Make GET /books/** public, DELETE /books/** admin-only and everything else require login, without sessions. Store passwords hashed. Background: Spring Security Fundamentals.

Solution
Java
@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())      // stateless API, no cookie-based login
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/books/**").permitAll()
                .requestMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

Rules are checked in order and the first match wins, so the specific rules come before anyRequest(). Disabling CSRF is acceptable here only because the API does not use cookie-based sessions; see CSRF, CORS and Secure Defaults. Production APIs normally replace HTTP Basic with tokens, as in JWT and OAuth 2 Resource Server.

Exercise 15: Only the owner may delete

In a blog, a post may be deleted by an administrator or by its author, and by nobody else. Express the rule on the service method so no controller can forget it.

Solution
Java
@Service
public class PostService {

    @PreAuthorize("hasRole('ADMIN') or @postPermissions.isAuthor(#id, authentication.name)")
    public void delete(long id) {
        posts.deleteById(id);
    }
}

@Component("postPermissions")
public class PostPermissions {

    private final PostRepository posts;

    public PostPermissions(PostRepository posts) {
        this.posts = posts;
    }

    public boolean isAuthor(long postId, String username) {
        return posts.findById(postId)
                .map(post -> post.getAuthorUsername().equals(username))
                .orElse(false);
    }
}

@EnableMethodSecurity (exercise 14) turns the annotation on. A failed check throws AccessDeniedException, which the security filter turns into 403. Returning false for a missing post means the caller sees 403 rather than learning which ids exist; decide deliberately whether a 404 is better for your API.

What to do next

Score yourself honestly: if you needed the solution for more than five exercises, re-read the lesson linked from each one before moving on. Then build one of the projects, for example Project: Todo REST API or Project: Bookstore Orders Service, without looking at the code. The exercises above are the individual moves; a project is where you learn to combine them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A class has two beans of the same interface type and no qualifier. What does Spring do at startup?

    Ambiguity is an error, which is why @Primary or @Qualifier is needed. The stand-in in exercise 3 prints the same kind of message.
  2. 2. Why does this.archive(order) ignore a @Transactional annotation on archive?

    The transaction is added by a proxy around the bean. A call from inside the bean never goes through the proxy.
  3. 3. What must be on the controller parameter for the annotations on a request record to be checked?

    @Valid (or @Validated) triggers validation. Without it, constraint annotations are just metadata.
  4. 4. Which query approach avoids the N+1 problem for authors and their books?

    A join fetch or entity graph loads the association in the same SQL statement instead of one extra query per author.

Summary

  • Prefer constructor injection, @Bean for types you do not own, and @Primary or @Qualifier to settle ambiguity.
  • Bind settings to validated records with defaults, and keep environment differences in profiles and environment variables.
  • Controllers return clear status codes (201 with Location, 404 with Problem Details), page their lists and validate input with @Valid.
  • Fix N+1 with join fetch or entity graphs, and remember that transactional behaviour lives in proxies, so self-calls skip it.
  • Put security rules in one SecurityFilterChain and, for ownership rules, on service methods with @PreAuthorize.

Next: Common Mistakes and Debugging Startup Failures.