Java · Advanced level

Advanced level · Module 5: REST APIs with Spring Boot · Lesson 2 of 4

Layers and Dependency Injection

Structure the service into controller, service and repository layers wired together by Spring's dependency injection.

In this lesson you will

  • Separate controller, service and repository responsibilities
  • Use constructor injection and persist data with Spring Data

Key concepts

@Service and @Repositoryconstructor injectionSpring Data repositorylayered architecture

The lesson

Controllers translate HTTP into method calls and back; services hold business rules; repositories store and load data. Keeping these layers separate means rules can be tested without HTTP and storage can change without touching the rules.

Spring creates objects (beans) and injects their dependencies. Declare dependencies as final fields set through the constructor; Spring supplies them automatically. Constructor injection also makes classes easy to construct in plain unit tests.

Spring Data repositories generate common queries from interfaces: interface EventRepository extends CrudRepository<Event, Long> gives save, findById and findAll with no implementation code. Custom queries can be declared with method names or @Query.

Step by step

  1. Create an EventService with the business rules.
  2. Inject it into the controller through the constructor.
  3. Add a Spring Data repository and a schema script.
  4. Move all logic out of the controller into the service.

Practice activity

Refactor the events API into three layers and store events in a database.

Expected result: Events persist across restarts, the controller contains no business rules and the service can be unit-tested without Spring.

Check your understanding

  1. Where do business rules belong in a layered service?

    Show answer

    In the service layer.

  2. Why prefer constructor injection?

    Show answer

    Dependencies are explicit and final, and the class can be created easily in unit tests.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.