AI Hints
Home›Spring Boot Tutorial›@Configuration and @Bean, Bean Scopes and Practice: Layers
Spring Boot · Lesson 36 of 120

Practice: Layers

Your turn.

⏱ 2 min read▶ Video at 47:28🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Let's practise splitting an app into layers. A controller for the web, and a service for the logic.

  • Controller: web
  • Service: logic
  • Joined by injection

The service is ready

Here's a book service, with three books. Under returns the books that cost at most max, using a stream filter.

BookService.javajava
@Service
public class BookService {

    private final List<Book> books = List.of(
        new Book(1, "Dune", "Frank Herbert", 9.99),
        new Book(2, "The Hobbit", "J.R.R. Tolkien", 8.99),
        new Book(3, "Circe", "Madeline Miller", 10.99));

    public List<Book> under(double max) {
        return books.stream().filter(b -> b.price() <= max).toList();
    }
}

The controller

Your turn. Pause the video, and try this. Write a controller that receives the book service, through its constructor. Add GET slash books slash cheap, with a max parameter, that defaults to ten. Here is one solution. The controller is thin. It only reads max, and asks the service. Max eight point nine nine gives just The Hobbit.

✍️ Exercise: The controller

BookController: inject BookService via the constructor. GET /books/cheap?max=x → service.under(max). max defaults to 10.

Show hint

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

Show solution
BookController.javajava
@RestController
public class BookController {

    private final BookService service;

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

    @GetMapping("/books/cheap")
    public List<Book> cheap(@RequestParam(defaultValue = "10") double max) {
        return service.under(max);
    }
}
Output
$ curl localhost:8080/books/cheap
[
  {"id":1,"title":"Dune","author":"Frank Herbert","price":9.99},
  {"id":2,"title":"The Hobbit","author":"J.R.R. Tolkien","price":8.99}
]
$ curl "localhost:8080/books/cheap?max=8.99"
[{"id":2,"title":"The Hobbit","author":"J.R.R. Tolkien","price":8.99}]

What module four taught

Spring creates your objects, called beans, and keeps them in the container. Dependency injection passes each bean what it needs, through its constructor. At Service, and at Component, mark beans. At Bean methods create beans for other classes. And beans are singletons, by default.

keyvalue
IoCSpring creates objects
DIconstructor injection
Beans@Service, @Component, @Bean
Scopesingleton by default

Summary

You now understand how Spring wires an app together. That's the end of module four. Next module, configuration.

Key takeaways
  • Beans
  • Dependency injection
  • Layers
Next up: application.properties — settings outside the code