Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Spring Boot Documentation

Production-ready Java backends — dependency injection, REST controllers, JPA, validation and Spring Security.

Spring Boot makes it fast to build production-ready Java backends. It sits on the Spring Framework and adds auto-configuration (sensible defaults), starter dependencies, and an embedded server (Tomcat) — so a REST API is a single runnable JAR. It is the most common Java stack in Indian service companies and many product companies.

1. Introduction & Setup

Requirements: Java 17+ (21 LTS recommended) and Maven or Gradle. Create a project at start.spring.io with:

  • Project: Maven · Language: Java · Spring Boot: 3.x
  • Dependencies: Spring Web, Spring Data JPA, Validation, MySQL Driver (or H2 for learning), Lombok (optional), Spring Boot DevTools
demo/
├── pom.xml
└── src/
    ├── main/java/com/codify/demo/
    │   └── DemoApplication.java
    ├── main/resources/
    │   └── application.properties
    └── test/java/…
package com.codify.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication     // = @Configuration + @EnableAutoConfiguration + @ComponentScan
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
./mvnw spring-boot:run          # Windows: mvnw.cmd spring-boot:run

Output (last lines):

Tomcat started on port 8080 (http) with context path '/'
Started DemoApplication in 2.134 seconds

⚠️ Common error: Web server failed to start. Port 8080 was already in use. — stop the other process or set server.port=8081 in application.properties.

2. Core Concepts: IoC, Beans & Dependency Injection

  • Bean: an object created and managed by the Spring IoC container (Inversion of Control).
  • Dependency Injection (DI): Spring gives a class the objects it needs instead of the class creating them with new — easier testing and loose coupling.

Stereotype annotations mark classes as beans (found by component scanning):

Annotation Layer
@Component generic bean
@Service business logic
@Repository data access (also translates DB exceptions)
@Controller / @RestController web layer
@Configuration + @Bean create beans manually (e.g. third-party objects)

Constructor injection (recommended — fields can be final, easy to test):

@Service
public class NoteService {
    private final NoteRepository repo;

    public NoteService(NoteRepository repo) {   // Spring injects it; @Autowired is optional with one constructor
        this.repo = repo;
    }
}
@Configuration
public class AppConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Bean scopes: singleton (default — one instance), prototype (new each time), request, session.

3. Building a REST Controller

@RestController
@RequestMapping("/api/notes")
public class NoteController {
    private final NoteService service;

    public NoteController(NoteService service) { this.service = service; }

    @GetMapping
    public List<Note> list(@RequestParam(defaultValue = "") String q) {
        return service.search(q);
    }

    @GetMapping("/{id}")
    public Note get(@PathVariable Long id) {
        return service.get(id);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Note create(@Valid @RequestBody NoteRequest body) {
        return service.create(body);
    }

    @PutMapping("/{id}")
    public Note update(@PathVariable Long id, @Valid @RequestBody NoteRequest body) {
        return service.update(id, body);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();   // 204
    }
}
Annotation Reads
@PathVariable /notes/{id}
@RequestParam ?q=graph&page=2
@RequestBody JSON body → Java object (Jackson)
@RequestHeader a header
ResponseEntity<T> full control over status, headers and body

4. Configuration & Profiles

# src/main/resources/application.properties
server.port=8080
spring.application.name=notes-api

spring.datasource.url=jdbc:mysql://localhost:3306/codify
spring.datasource.username=root
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

app.jwt.secret=${JWT_SECRET}

The same in YAML (application.yml):

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/codify
    username: root
    password: ${DB_PASSWORD}

Read values in code:

@Value("${app.jwt.secret}")
private String jwtSecret;

Profiles: application-dev.properties, application-prod.properties; activate with spring.profiles.active=dev or --spring.profiles.active=prod.

ddl-auto values: create (drop and create), create-drop, update (alter to match entities — dev only), validate (check only — production with Flyway/Liquibase migrations), none.

5. Spring Data JPA & Entities

JPA maps Java classes to tables (ORM); Hibernate is the implementation; Spring Data JPA writes the repository code for you.

@Entity
@Table(name = "notes")
public class Note {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 120)
    private String title;

    @Column(columnDefinition = "TEXT")
    private String body;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private User author;

    @CreationTimestamp
    private Instant createdAt;

    // getters and setters (or Lombok @Getter @Setter)
}
public interface NoteRepository extends JpaRepository<Note, Long> {
    List<Note> findByTitleContainingIgnoreCase(String q);          // derived query
    Page<Note> findByAuthorId(Long authorId, Pageable pageable);
    boolean existsByTitle(String title);

    @Query("SELECT n FROM Note n WHERE n.createdAt > :since ORDER BY n.createdAt DESC")
    List<Note> recent(@Param("since") Instant since);              // JPQL
}

JpaRepository already gives save, findById, findAll, deleteById, count, paging and sorting.

Relationships:

Annotation Example
@OneToOne User — Profile
@OneToMany(mappedBy = "author") User — Notes
@ManyToOne Note — Author (owns the FK)
@ManyToMany + @JoinTable Student — Course

Pagination:

Page<Note> page = repo.findAll(PageRequest.of(0, 20, Sort.by("createdAt").descending()));

⚠️ N+1 problem: loading 50 notes and then each note's author runs 51 queries. Fix with @EntityGraph(attributePaths = "author") or JOIN FETCH in JPQL.

6. Service Layer, DTOs & Validation

Keep controllers thin; put logic in services; don't expose entities directly — use DTOs.

public record NoteRequest(
    @NotBlank @Size(min = 3, max = 120) String title,
    @Size(max = 10000) String body
) {}

public record NoteResponse(Long id, String title, String body, Instant createdAt) {
    static NoteResponse from(Note n) { return new NoteResponse(n.getId(), n.getTitle(), n.getBody(), n.getCreatedAt()); }
}
@Service
@Transactional
public class NoteService {
    private final NoteRepository repo;
    public NoteService(NoteRepository repo) { this.repo = repo; }

    @Transactional(readOnly = true)
    public Note get(Long id) {
        return repo.findById(id).orElseThrow(() -> new NotFoundException("Note " + id + " not found"));
    }

    public Note create(NoteRequest req) {
        Note n = new Note();
        n.setTitle(req.title().trim());
        n.setBody(req.body());
        return repo.save(n);
    }
}

Validation annotations: @NotNull, @NotBlank, @Size, @Min, @Max, @Email, @Pattern, @Past, @Positive. Trigger with @Valid on the parameter.

@Transactional: all DB operations in the method commit together or roll back together (on unchecked exceptions by default).

7. Exception Handling

public class NotFoundException extends RuntimeException {
    public NotFoundException(String msg) { super(msg); }
}

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Map<String, String> notFound(NotFoundException e) {
        return Map.of("message", e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> invalid(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(f -> errors.put(f.getField(), f.getDefaultMessage()));
        return errors;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, String> other(Exception e) {
        return Map.of("message", "Something went wrong");
    }
}

Spring Boot 3 also supports the standard ProblemDetail (RFC 7807) error format: spring.mvc.problemdetails.enabled=true.

8. Spring Security & JWT

Adding spring-boot-starter-security locks every endpoint by default. Configure what's public:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http, JwtFilter jwtFilter) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())                         // stateless REST API with tokens
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**", "/actuator/health").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/notes/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }

    @Bean
    PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
}

Flow: /api/auth/login checks the password with passwordEncoder.matches() and returns a JWT (library: jjwt or Spring's OAuth2 resource server); a OncePerRequestFilter reads Authorization: Bearer …, validates it and sets the SecurityContext. Method-level rules: @PreAuthorize("hasRole('ADMIN')") with @EnableMethodSecurity.

CORS for a React front end:

@Bean
WebMvcConfigurer cors() {
    return new WebMvcConfigurer() {
        @Override public void addCorsMappings(CorsRegistry r) {
            r.addMapping("/api/**").allowedOrigins("http://localhost:5173").allowedMethods("*");
        }
    };
}

(With Spring Security also call http.cors(Customizer.withDefaults()).)

9. Testing, Actuator & Deployment

@WebMvcTest(NoteController.class)
class NoteControllerTest {
    @Autowired MockMvc mvc;
    @MockitoBean NoteService service;          // @MockBean before Spring Boot 3.4

    @Test
    void returns404() throws Exception {
        when(service.get(9L)).thenThrow(new NotFoundException("Note 9 not found"));
        mvc.perform(get("/api/notes/9")).andExpect(status().isNotFound());
    }
}
  • @SpringBootTest — full application context (integration tests); @DataJpaTest — repositories with an in-memory DB; Testcontainers for a real MySQL/Postgres in Docker.
  • Actuator (spring-boot-starter-actuator): /actuator/health, /actuator/metrics, /actuator/info for monitoring.
  • Build & run:
./mvnw clean package          # creates target/demo-0.0.1-SNAPSHOT.jar
java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

Deploy the JAR on a VM, as a Docker image (./mvnw spring-boot:build-image), or on Render/Railway/AWS Elastic Beanstalk.

10. Advanced Concepts

  • Auto-configuration: Boot looks at the classpath (e.g. a MySQL driver + JPA) and configures beans automatically; your own beans override them. See the report with --debug.
  • Starters: curated dependency bundles — spring-boot-starter-web, -data-jpa, -security, -validation, -test, -actuator, -mail, -cache, -data-redis.
  • Caching: @EnableCaching + @Cacheable("notes") on a method; Redis or Caffeine as the store.
  • Scheduling: @EnableScheduling + @Scheduled(cron = "0 0 9 * * *").
  • Async: @EnableAsync + @Async methods; Java 21 virtual threads: spring.threads.virtual.enabled=true.
  • Database migrations: Flyway (db/migration/V1__init.sql) or Liquibase.
  • API docs: springdoc-openapi → Swagger UI at /swagger-ui.html.
  • Microservices: Spring Cloud (Gateway, Config, OpenFeign, Resilience4j), messaging with Kafka/RabbitMQ.
  • AOP: @Aspect for cross-cutting concerns (logging, timing) — @Transactional itself works through proxies, so calling a @Transactional method from the same class skips it.

11. Examples with Output

Example 1 — Hello endpoint

@RestController
public class HelloController {
    @GetMapping("/hello")
    public Map<String, String> hello(@RequestParam(defaultValue = "Coder") String name) {
        return Map.of("message", "Hello, " + name + "!");
    }
}
curl "http://localhost:8080/hello?name=Asha"
{"message":"Hello, Asha!"}

Example 2 — Validation error

curl -X POST http://localhost:8080/api/notes -H "Content-Type: application/json" -d '{"title":""}'
{"title":"size must be between 3 and 120"}

(With @NotBlank as well, the message may be must not be blank — Spring reports one message per field.)

Example 3 — Derived query

repo.save(new Note("Graphs BFS"));
repo.save(new Note("Graph DFS"));
System.out.println(repo.findByTitleContainingIgnoreCase("graph").size());
2

12. Practice Problems

  1. Create a Student CRUD API with H2, then switch to MySQL using a dev profile.
  2. Add DTOs and validation (@NotBlank, @Email) and return field-wise error messages.
  3. Add GET /api/students?page=0&size=10&sort=name with Pageable.
  4. Model Student ↔ Course as many-to-many and list a student's courses.
  5. Write a @RestControllerAdvice that returns JSON for 404, 400 and 500.
  6. Secure the API with Spring Security + JWT; make GET public and POST/DELETE admin-only.
  7. Add Swagger UI with springdoc and Actuator health checks.
  8. Write @WebMvcTest and @DataJpaTest tests, then package and run the JAR.

13. Interview Questions

1. Spring vs Spring Boot? Spring is the framework (IoC, MVC, data, security). Spring Boot adds auto-configuration, starters, an embedded server and production features so apps need almost no setup.

2. What does @SpringBootApplication do? Combines @Configuration, @EnableAutoConfiguration and @ComponentScan.

3. What is dependency injection? Which type is preferred? The container supplies a class's dependencies. Constructor injection is preferred — immutable fields, clear required dependencies, easy testing.

4. @Component vs @Service vs @Repository? All create beans; @Service and @Repository express the layer, and @Repository also translates persistence exceptions.

5. @Controller vs @RestController? @RestController = @Controller + @ResponseBody — return values are written as JSON instead of view names.

6. What is the N+1 query problem? Loading a list then lazily loading a relation for each item causes N extra queries; fix with fetch joins or entity graphs.

7. What does @Transactional do? Runs the method in a DB transaction — commit on success, rollback on runtime exceptions. It works through a proxy, so self-invocation bypasses it.

8. How do you handle exceptions globally? @RestControllerAdvice with @ExceptionHandler methods.

9. CrudRepository vs JpaRepository? JpaRepository extends CrudRepository and PagingAndSortingRepository, adding batch operations, flushing and list-returning methods.

10. What is Spring Boot Actuator? Production endpoints for health, metrics, info and more, used by monitoring tools and load balancers.

14. Cheat Sheet & References

Annotations

@SpringBootApplication                     // main class
@RestController @RequestMapping("/api/x")  // REST controller
@GetMapping("/{id}") @PostMapping @PutMapping @DeleteMapping
@PathVariable @RequestParam @RequestBody @Valid
@Service @Repository @Component @Configuration @Bean
@Transactional @Value("${key}")

JPA

@Entity @Table(name = "notes")
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false) @ManyToOne @OneToMany(mappedBy = "x")
interface Repo extends JpaRepository<Note, Long> {}
List<Note> findByTitleContainingIgnoreCase(String q);
repo.findAll(PageRequest.of(0, 20, Sort.by("id").descending()));

Errors and validation

@RestControllerAdvice @ExceptionHandler(NotFoundException.class)
@NotBlank @Size(min = 3) @Email @Min(1) @Positive
ResponseEntity.status(HttpStatus.CREATED).body(obj);
ResponseEntity.noContent().build();

Properties

# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.jpa.hibernate.ddl-auto=update
spring.profiles.active=dev
management.endpoints.web.exposure.include=health,info

Build and run

./mvnw spring-boot:run
./mvnw test
./mvnw clean package
java -jar target/app.jar --spring.profiles.active=prod

Official documentation