Lesson 29 / 38

Spring Boot, Spring Data JPA & Annotations

Go beyond hello-world Spring Boot — starters and auto-configuration, repository interfaces from Spring Data JPA, and the core stereotype and wiring annotations.

Starters and auto-configuration

A starter (spring-boot-starter-web, spring-boot-starter-data-jpa) is a curated dependency bundle. Auto-configuration inspects what's on the classpath and configures matching beans (a DataSource if a JDBC driver is present, an embedded Tomcat if starter-web is there) — you override only what you need in application.properties.

Spring Data JPA: repositories for free

Extend JpaRepository<Entity, IdType> and get save, findById, findAll, delete implemented for you. Declare a method following the naming convention and Spring derives the query from the method name — no SQL, no implementation.

interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByStatusAndCustomerId(Status status, Long customerId);
    Optional<Order> findFirstByCustomerIdOrderByCreatedAtDesc(Long customerId);
}

The core annotations

@Component marks any Spring-managed bean; @Service and @Repository are semantic specialisations of it for business logic and data access. @Autowired requests injection (optional on a single constructor since Spring 4.3). @RestController = @Controller + @ResponseBody, so every method's return value is written straight into the HTTP response as JSON.