Spring Boot Tutorial 120 lessons · 2:38:34+ of video
Spring Boot Home What Spring Boot Is, Where Spring Boot Is Used and How a Web App Works
What Spring Boot Is Where Spring Boot Is Used How a Web App Works What You Need, Spring Initializr and The Project Structure
What You Need Spring Initializr The Project Structure The Main Class, Running the App and Your First Endpoint
The Main Class Running the App Your First Endpoint HTTP Methods, Status Codes and JSON
HTTP Methods Status Codes JSON Testing with curl, @RestController and @GetMapping
Testing with curl @RestController @GetMapping Path Variables, Query Parameters and Practice: A Greeting API
Path Variables Query Parameters Practice: A Greeting API What REST Is, Returning Objects as JSON and Records for Data
What REST Is Returning Objects as JSON Records for Data @PostMapping and @RequestBody, @PutMapping and @DeleteMapping
@PostMapping and @RequestBody @PutMapping @DeleteMapping ResponseEntity, Status Codes in Practice and Practice: A Book API in Memory
ResponseEntity Status Codes in Practice Practice: A Book API in Memory Inversion of Control, Beans and Dependency Injection
Inversion of Control Beans Dependency Injection @Service, Constructor Injection and @Component and Friends
@Service Constructor Injection @Component and Friends @Configuration and @Bean, Bean Scopes and Practice: Layers
@Configuration and @Bean Bean Scopes Practice: Layers application.properties, @Value and @ConfigurationProperties
application.properties @Value @ConfigurationProperties YAML, Profiles and Logging
YAML Profiles Logging CommandLineRunner, Environment Variables and Practice: A Configurable Shop
CommandLineRunner Environment Variables Practice: A Configurable Shop Why a Database, The H2 Database and What JPA Is
Why a Database The H2 Database What JPA Is Entities, Ids and Generated Values and Repositories
Entities Ids and Generated Values Repositories CRUD with JpaRepository, Seeding Data and Practice: Books in a Database
CRUD with JpaRepository Seeding Data Practice: Books in a Database Derived Query Methods, More Query Keywords and Sorting
Derived Query Methods More Query Keywords Sorting Paging, @Query with JPQL and Native Queries
Paging @Query with JPQL Native Queries Counting and Exists, Transactions and Practice: Search Books
Counting and Exists Transactions Practice: Search Books Relationships, @ManyToOne and @OneToMany
Relationships @ManyToOne @OneToMany Lazy Loading, Cascade and Many to Many
Lazy Loading Cascade Many to Many DTOs for Relationships, Avoiding Endless JSON and Practice: Authors and Books
DTOs for Relationships Avoiding Endless JSON Practice: Authors and Books Why Validate, Bean Validation and @Valid
Why Validate Bean Validation @Valid Validation Errors, Custom Exceptions and @ResponseStatus
Validation Errors Custom Exceptions @ResponseStatus @RestControllerAdvice, ProblemDetail and Practice: Clean Errors
@RestControllerAdvice ProblemDetail Practice: Clean Errors Controller, Service, Repository, Mapping Entities to DTOs and Update Requests
Controller, Service, Repository Mapping Entities to DTOs Update Requests PATCH, Filtering with Query Parameters and Pagination in the API
PATCH Filtering with Query Parameters Pagination in the API API Versioning, CORS and Practice: A Complete Books API
API Versioning CORS Practice: A Complete Books API Spring Security Basics, Locked by Default and SecurityFilterChain
Spring Security Basics Locked by Default SecurityFilterChain Users and Passwords, Password Encoding and Roles
Users and Passwords Password Encoding Roles Protecting Endpoints by Role, Method Security and Practice: A Secured API
Protecting Endpoints by Role Method Security Practice: A Secured API Why Test, JUnit Basics and Testing a Service
Why Test JUnit Basics Testing a Service Mockito, @WebMvcTest and MockMvc
Mockito @WebMvcTest MockMvc @DataJpaTest, @SpringBootTest and Practice: Test the API
@DataJpaTest @SpringBootTest Practice: Test the API Actuator, Health and Info and Packaging a Jar
Actuator Health and Info Packaging a Jar Project: The Plan, Entities, Repositories and Service
Project: The Plan Project: Entities Project: Repositories and Service Project: The Controller, Validation and Errors and Security
Project: The Controller Project: Validation and Errors Project: Security Project: Tests, Where to Go Next and Course Recap
Project: Tests Where to Go Next Course Recap Spring Boot · Lesson 31 of 120
@Service Where the logic lives.
⏱ 2 min read ▶ Video at 40:43 🎓 Free
▶ starts at 40:43 A controller's job is the web. Reading the request, and sending the response. The real work, the business logic, belongs in a service.
Controller: the web Service: the real work Keep them apart The controller knows about URLs, parameters, and status codes. The service knows the rules of the business, like how discounts work. The service knows nothing about the web. So it can be reused, and tested on its own.
Controller URLs and parametersStatus codes and JSONThin: calls the service Service Business rulesCalculations, decisionsNo web code at all At Service marks this class as a service bean. It holds a list of books. All returns them. And price with discount does the business rule. It takes a percentage off, and rounds to two decimal places.
BookService.java java Copy
@ Service
public class BookService {
private final List < Book > books = List. of (
new Book ( 1 , "Dune" , "Frank Herbert" , 9.99 ),
new Book ( 2 , "Circe" , "Madeline Miller" , 10.99 ));
public List< Book > all () {
return books;
}
public double priceWithDiscount ( int id , int percent ) {
Book book = books. get (id - 1 );
double price = book. price () * ( 100 - percent) / 100 ;
return Math. round (price * 100 ) / 100.0 ;
}
} Prefer to watch? The full Spring Boot course is free All lessons in one video with animations, real code and chapters.
Watch free The controller receives the service, through its constructor. The endpoint reads the id, and the discount, from the URL. Then it simply asks the service, and returns the answer. Run it. Dune costs nine ninety nine. With twenty percent off, it's seven ninety nine. And Circe, with ten off, is nine eighty nine.
BookController.java java Copy
@ RestController
public class BookController {
private final BookService service;
public BookController (BookService service ) {
this .service = service;
}
@ GetMapping ( "/books/{id}/price" )
public String price (@ PathVariable int id , @ RequestParam ( defaultValue = "0" ) int off ) {
return "Price: " + service. priceWithDiscount (id, off);
}
} Output
$ curl localhost:8080/books/1/price
Price: 9.99
$ curl "localhost:8080/books/1/price?off=20"
Price: 7.99
$ curl "localhost:8080/books/2/price?off=10"
Price: 9.89 Also uses Book.java public record Book (Integer id, String title, String author, double price) {} Also uses BookService.java @ Service
public class BookService {
private final List < Book > books = List. of (
new Book ( 1 , "Dune" , "Frank Herbert" , 9.99 ),
new Book ( 2 , "Circe" , "Madeline Miller" , 10.99 ));
public List< Book > all () {
return books;
}
public double priceWithDiscount ( int id , int percent ) {
Book book = books. get (id - 1 );
double price = book. price () * ( 100 - percent) / 100 ;
return Math. round (price * 100 ) / 100.0 ;
}
} Also uses _curl.sh curl localhost:8080/books/1/price
curl "localhost:8080/books/1/price?off=20"
curl "localhost:8080/books/2/price?off=10" Services hold the business logic, and controllers stay thin, handling only the web. At Service makes a class a service bean. Next, constructor injection.
Key takeaways @Service Business logic Thin controllers