0% found this document useful (0 votes)
1 views

Spring_Boot

This document provides an introduction to Spring Boot, a framework built on the Spring Framework that simplifies the development of Java applications by reducing boilerplate code and configuration. It covers key features, common annotations, project structure, starter dependencies, configuration management, and database interaction using Spring Data JPA. Additionally, it includes interview questions and answers related to Spring Boot concepts and practices.

Uploaded by

shivamsitu2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Spring_Boot

This document provides an introduction to Spring Boot, a framework built on the Spring Framework that simplifies the development of Java applications by reducing boilerplate code and configuration. It covers key features, common annotations, project structure, starter dependencies, configuration management, and database interaction using Spring Data JPA. Additionally, it includes interview questions and answers related to Spring Boot concepts and practices.

Uploaded by

shivamsitu2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Spring Boot Learning Notes - Topic 1: Introduction to Spring Boot

What is Spring Framework?

 Spring is a popular Java framework for building enterprise-level applications.

 It provides infrastructure support for developing Java applications.

 Core features include Inversion of Control (IoC), Dependency Injection (DI),


and Aspect-Oriented Programming (AOP).

What is Spring Boot?

 Spring Boot is a project built on top of the Spring Framework.

 It simplifies the development of Spring applications by eliminating


boilerplate code and configurations.

Key Features of Spring Boot:

 Auto Configuration

 Embedded Web Servers (Tomcat, Jetty, etc.)

 Opinionated defaults

 Starter dependencies

 Actuator for monitoring

Why Use Spring Boot?

 Quick setup and development

 Eliminates the need for extensive configuration

 Production-ready applications with minimal e ort

 Embedded server simplifies deployment

Code Example: Simple Spring Boot App

Step 1: Create a Spring Boot Project (using https://start.spring.io)

 Choose dependencies: Spring Web


Step 2: Main Application Class

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

Step 3: Simple REST Controller

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {

@GetMapping("/hello")

public String sayHello() {

return "Hello, Spring Boot!";

Run the application and visit: http://localhost:8080/hello

Interview Questions with Answers


Q1: What is Spring Boot?

 Spring Boot is a framework that helps developers create stand-alone,


production-ready Spring-based applications easily. It uses auto-
configuration and embedded servers to simplify setup.

Q2: What is the di erence between Spring and Spring Boot?

Feature Spring Framework Spring Boot

Configuration Manual Auto-configuration

Server External Embedded (Tomcat/Jetty)

Setup Time Longer Faster

Learning Curve Steeper Easier

Q3: What does @SpringBootApplication do?

 Combines @Configuration, @EnableAutoConfiguration, and


@ComponentScan.

 Tells Spring Boot to start scanning for components and auto-configure the
app.

Q4: How does Spring Boot make development easier?

 Reduces boilerplate code

 Provides pre-configured starters

 Eliminates external web server setup

 Includes monitoring and health check endpoints via Actuator

Topic 2: Spring Boot Annotations

Spring Boot uses several annotations to simplify the configuration and


development process.

Common Spring Boot Annotations:

1. @SpringBootApplication

 Combines 3 annotations: @Configuration, @EnableAutoConfiguration,


@ComponentScan

 Marks the main class of a Spring Boot application


@SpringBootApplication

public class MyApp {

public static void main(String[] args) {

SpringApplication.run(MyApp.class, args);

2. @RestController

 Marks a class as a controller where every method returns a domain object


instead of a view

 Combines @Controller and @ResponseBody

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello() {

return "Hello World";

3. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

 Used to handle HTTP GET, POST, PUT, and DELETE requests respectively

@GetMapping("/get")

public String getMethod() {

return "GET Request";

@PostMapping("/post")

public String postMethod() {

return "POST Request";

}
4. @Autowired

 Automatically injects dependencies (Beans)

@Service

public class MyService {

public String serve() {

return "Service Logic";

@RestController

public class MyController {

@Autowired

private MyService myService;

@GetMapping("/serve")

public String serve() {

return myService.serve();

Interview Questions with Answers

Q1: What is the use of @SpringBootApplication?

 It marks the main class and enables auto-configuration, component


scanning, and Java config.

Q2: What is the di erence between @Controller and @RestController?

 @Controller returns view pages (e.g., JSP), while @RestController returns


data (like JSON/XML).

Q3: What is @Autowired used for?


 It's used to automatically inject dependencies into a class, removing the
need for explicit instantiation.

Q4: What is the di erence between @GetMapping and @RequestMapping(method


= RequestMethod.GET)?

 @GetMapping is a shorthand annotation for @RequestMapping(method =


RequestMethod.GET).

Topic 3: Spring Boot Project Structure and Starter Dependencies

Project Structure Overview

Typical Maven-based Spring Boot project layout:

my-boot-app/

├── src/

│ └── main/

│ ├── java/

│ │ └── com/example/mybootapp/

│ │ ├── MyBootAppApplication.java

│ │ └── controller/

│ │ └── service/

│ └── resources/

│ ├── application.properties

│ └── static/ (HTML, CSS, JS)

│ └── templates/ (Thymeleaf, Freemarker, etc.)

├── pom.xml

Starter Dependencies

Spring Boot starters are pre-defined dependency descriptors in pom.xml that


simplify project setup.

Common Starters:

 spring-boot-starter-web → For building web applications (RESTful)

 spring-boot-starter-data-jpa → For JPA and database access


 spring-boot-starter-security → For securing the application

 spring-boot-starter-test → For unit and integration testing

 spring-boot-starter-thymeleaf → For server-side HTML rendering

Example: pom.xml snippet

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

Interview Questions with Answers

Q1: What is a Spring Boot starter?

 A starter is a set of convenient dependency descriptors that you can include


in your application. It includes all the dependencies you need for a particular
functionality.

Q2: Why are starter dependencies useful?


 They simplify dependency management and reduce boilerplate
configuration by bundling commonly used libraries together.

Q3: What is the use of application.properties or application.yml?

 These files are used to define application configuration like server port,
database details, logging, etc.

Q4: What is the structure of a typical Spring Boot project?

 src/main/java contains code, src/main/resources holds configuration &


templates, and pom.xml manages dependencies.

Topic 4: Spring Boot Configuration (application.properties & application.yml) +


Profiles

application.properties

 Plain key-value format

 Used to configure server port, DB connections, logging, etc.

server.port=8081

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=secret

application.yml

 YAML format (more structured, readable)

server:

port: 8081

spring:

datasource:

url: jdbc:mysql://localhost:3306/mydb

username: root

password: secret

Profiles in Spring Boot

 Used to configure environments like dev, test, prod


 Profile-specific configuration: application-dev.properties, application-
prod.yml

 Activate a profile:

o via application.properties:

o spring.profiles.active=dev

o via command line:

o java -jar app.jar --spring.profiles.active=prod

Use Case Example

# application-dev.properties

server.port=8081

spring.datasource.username=dev_user

# application-prod.properties

server.port=8080

spring.datasource.username=prod_user

Interview Questions with Answers

Q1: What are application.properties and application.yml used for?

 They store application-level configuration such as DB details, server port,


logging level, etc.

Q2: Which is better, .properties or .yml?

 .yml is more readable for complex configurations, but .properties is simpler


and widely used.

Q3: What are Spring Profiles?

 Profiles allow you to define di erent configurations for di erent


environments like development, testing, and production.

Q4: How can we activate a Spring profile?

 Using spring.profiles.active in config or via command line while starting the


application.
Topic 5: Spring Boot with Database & JPA

Spring Boot makes it easy to interact with databases using Spring Data JPA.

1. Add Dependencies in pom.xml

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>

2. Entity Class Example

import jakarta.persistence.*;

@Entity

public class User {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

private String email;

// getters and setters

3. Repository Interface

import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {

// custom query methods if needed

4. Using the Repository

@RestController

@RequestMapping("/users")

public class UserController {

@Autowired

private UserRepository userRepository;

@PostMapping

public User saveUser(@RequestBody User user) {

return userRepository.save(user);

@GetMapping

public List<User> getAllUsers() {

return userRepository.findAll();

5. application.properties Configuration

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driver-class-name=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.h2.console.enabled=true

Output Example
Visit: http://localhost:8080/h2-console

 JDBC URL: jdbc:h2:mem:testdb

Interview Questions with Answers

Q1: What is Spring Data JPA?

 It's a part of Spring that simplifies data access using JPA. It provides ready-
to-use implementations for most database operations.

Q2: What is a JPA repository?

 An interface that extends JpaRepository or CrudRepository to perform CRUD


operations.

Q3: How do you map a Java class to a DB table?

 Use @Entity and @Table annotations.

Q4: What is the purpose of spring.h2.console.enabled=true?

 It enables the web-based H2 database console for testing and debugging.

Topic 6: Spring Boot - Dependency Injection (DI) & Bean Management

Spring Boot leverages Dependency Injection (DI) and Bean Management from the
core Spring Framework to achieve loose coupling and increase testability.

What is Dependency Injection (DI)?

Dependency Injection is a design pattern where the dependencies (objects a class


needs) are provided by an external source rather than the class creating them.

Types of DI in Spring

Type Description Example Annotation

Constructor DI Inject dependency via constructor @Autowired

Setter DI Inject dependency via setter method @Autowired

Field Injection Inject directly into class field @Autowired


Example: Constructor-Based DI

java

@Service

public class MyService {

public String getData() {

return "Spring Boot DI!";

@RestController

public class MyController {

private final MyService myService;

@Autowired // Constructor-based injection

public MyController(MyService myService) {

this.myService = myService;

@GetMapping("/data")

public String fetchData() {

return myService.getData();

Spring Beans
A bean is an object that is managed by the Spring container. Beans are created,
configured, and managed by Spring's IoC container.

Declaring a Bean

You can declare a bean using:

 @Component

 @Service

 @Repository

 @Controller

 Or manually using @Bean in a configuration class

Example: Manual Bean Declaration

java

@Configuration

public class AppConfig {

@Bean

public MyService myService() {

return new MyService();

Interview Questions with Answers

Q1: What is Dependency Injection?

 DI is a design pattern in which a class receives its dependencies from an external


source rather than creating them itself.

Q2: What are the ways to inject dependencies in Spring?

 Constructor injection, Setter injection, and Field injection.


Q3: What is the di erence between @Component, @Service, and @Repository?

 All are stereotypes to define Spring-managed beans. Semantically:

o @Component is a generic stereotype.

o @Service is used in the service layer.

o @Repository is used in the data access layer and supports exception


translation.

Q4: What is a Spring Bean?

 A Spring Bean is an object that is managed by the Spring IoC container.

Topic 7: Spring Boot - Configuration & Properties Management

Spring Boot provides flexible ways to manage configuration using @Value,


@ConfigurationProperties, and custom configuration classes.

1. Using @Value to Inject Property Values

You can inject values from application.properties using @Value.

Example:

application.properties

properties

app.name=MySpringApp

app.version=1.0.0

Java Class

java

@RestController

public class AppInfoController {

@Value("${app.name}")

private String appName;


@Value("${app.version}")

private String appVersion;

@GetMapping("/info")

public String getAppInfo() {

return appName + " - Version: " + appVersion;

2. Using @ConfigurationProperties

For structured configuration, use @ConfigurationProperties.

Example:

application.properties

properties

app.details.name=SpringBootApp

app.details.version=2.5

app.details.owner=DevUser

Config Class

java

@Component

@ConfigurationProperties(prefix = "app.details")

public class AppDetails {

private String name;

private String version;

private String owner;


// Getters and Setters

Usage in Controller

java

@RestController

public class ConfigController {

@Autowired

private AppDetails appDetails;

@GetMapping("/details")

public String showDetails() {

return appDetails.getName() + " owned by " + appDetails.getOwner();

3. External Configuration Priority

Spring Boot loads properties in the following order (high to low):

1. Command line arguments

2. application.properties or .yml (in /config subdirectory)

3. application.properties or .yml (in root resources/)

4. Environment variables

5. @PropertySource annotated classes

6. Default properties in SpringApplication.setDefaultProperties

4. Binding Complex Types


application.yml

yaml

app:

credentials:

username: admin

password: secret

Java Class

java

@Component

@ConfigurationProperties(prefix = "app.credentials")

public class Credentials {

private String username;

private String password;

// Getters and Setters

Interview Questions with Answers

Q1: How can you read values from application.properties?


Using @Value or @ConfigurationProperties annotations.

Q2: What is the di erence between @Value and @ConfigurationProperties?

Feature @Value @ConfigurationProperties

Use case Simple property injection Structured and grouped configuration

Binding type Manual Automatic with prefix

Recommended for Few values Many related properties


Q3: What is the order of property loading in Spring Boot?
Command-line args > config folder properties > root properties > environment
variables > @PropertySource > defaults.

Q4: How do you load YAML instead of properties?


Rename the config file as application.yml and use structured indentation with keys
and values.

Topic 8: Spring Boot REST APIs – Building CRUD with Spring MVC

Spring Boot makes it super easy to build RESTful web services using Spring MVC. This
topic covers creating a basic CRUD API.

1. REST Basics

 REST stands for Representational State Transfer.

 It uses standard HTTP methods:

o GET → Read data

o POST → Create data

o PUT → Update data

o DELETE → Remove data

2. CRUD API Structure

Operation HTTP Method URL Endpoint Description

Create POST /students Add new student

Read GET /students Get all students

Read GET /students/{id} Get student by ID

Update PUT /students/{id} Update student by ID

Delete DELETE /students/{id} Delete student by ID

3. CRUD API Example with Spring Boot

Model Class
java

@Entity

public class Student {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

private String email;

// Getters & Setters

Repository Interface

java

@Repository

public interface StudentRepository extends JpaRepository<Student, Long> {

Controller Class

java

@RestController

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentRepository repository;


@PostMapping

public Student createStudent(@RequestBody Student student) {

return repository.save(student);

@GetMapping

public List<Student> getAllStudents() {

return repository.findAll();

@GetMapping("/{id}")

public ResponseEntity<Student> getStudentById(@PathVariable Long id) {

return repository.findById(id)

.map(ResponseEntity::ok)

.orElse(ResponseEntity.notFound().build());

@PutMapping("/{id}")

public ResponseEntity<Student> updateStudent(@PathVariable Long id,


@RequestBody Student updated) {

return repository.findById(id).map(student -> {

student.setName(updated.getName());

student.setEmail(updated.getEmail());

return ResponseEntity.ok(repository.save(student));

}).orElse(ResponseEntity.notFound().build());

}
@DeleteMapping("/{id}")

public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {

return repository.findById(id).map(student -> {

repository.delete(student);

return ResponseEntity.noContent().build();

}).orElse(ResponseEntity.notFound().build());

Interview Questions with Answers

Q1: What annotations are used to build REST APIs in Spring Boot?
@RestController, @RequestMapping, @GetMapping, @PostMapping,
@PutMapping, @DeleteMapping

Q2: How does Spring Boot handle JSON data automatically?


Spring Boot uses Jackson to serialize/deserialize JSON.

Q3: What is ResponseEntity used for?


It represents the entire HTTP response (status code, headers, body).

Q4: How do you connect the controller with the database?


Using a repository interface (e.g., JpaRepository) and injecting it in the controller
using @Autowired.

Topic 9: Spring Boot with Spring Data JPA – Repositories & Database Integration

Spring Data JPA simplifies the development of database access layers by abstracting
boilerplate code.

1. What is Spring Data JPA?

 A Spring project that simplifies JPA (Java Persistence API) development.

 Provides repository interfaces to perform CRUD operations without writing


boilerplate SQL/JPQL.

 Internally uses Hibernate as the default ORM implementation.


2. Key Components

Component Description

@Entity Marks a class as a JPA entity

@Id Specifies the primary key

@GeneratedValue Defines auto-generation of primary key

JpaRepository Interface with CRUD and pagination methods

@Repository Optional, used to indicate the class is a repository

3. Spring Boot + JPA Flow

1. Define Entity

2. Create Repository Interface

3. Autowire and Use Repository in Services/Controllers

4. Configure application.properties or application.yml for DB

4. Entity Example

java

@Entity

public class Product {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

private Double price;

// getters and setters


}

5. Repository Example

java

public interface ProductRepository extends JpaRepository<Product, Long> {

List<Product> findByName(String name);

List<Product> findByPriceGreaterThan(Double price);

6. Configuration (application.properties)

properties

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=pass

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

7. Custom Query Methods

Spring Data JPA supports query derivation from method names:

java

List<Product> findByNameContaining(String keyword);

List<Product> findByPriceBetween(Double min, Double max);

You can also use @Query for custom JPQL:

java
@Query("SELECT p FROM Product p WHERE p.name = ?1")

List<Product> searchByName(String name);

Interview Questions with Answers

Q1: What is the purpose of JpaRepository in Spring Data JPA?


It provides CRUD, pagination, and sorting operations on entities.

Q2: What does spring.jpa.hibernate.ddl-auto=update mean?


It auto-updates the schema to match the entity definitions.

Q3: Di erence between CrudRepository and JpaRepository?


JpaRepository extends CrudRepository and adds more features like paging and
sorting.

Q4: Can we use native SQL in Spring Data JPA?


Yes, with @Query(value = "SQL QUERY", nativeQuery = true).

Topic 10: Spring Boot Exception Handling – Global Error Handling with
@ControllerAdvice

Spring Boot provides a powerful way to handle exceptions globally and return custom
error responses.

1. Why Exception Handling?

 Helps in managing unexpected conditions gracefully.

 Improves user experience by providing clear error messages.

 Keeps code clean and maintainable.

2. Key Annotations

Annotation Purpose

@ControllerAdvice Used to handle exceptions globally across the application

@ExceptionHandler Defines method to handle specific exceptions

@ResponseStatus Maps exceptions to HTTP status codes


Annotation Purpose

@RestControllerAdvice A combination of @ControllerAdvice and @ResponseBody

3. Example – Custom Exception

java

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException(String message) {

super(message);

4. Global Exception Handler using @ControllerAdvice

java

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)

public ResponseEntity<String>
handleResourceNotFound(ResourceNotFoundException ex) {

return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

@ExceptionHandler(Exception.class)

public ResponseEntity<String> handleGeneralException(Exception ex) {

return new ResponseEntity<>("Something went wrong!",


HttpStatus.INTERNAL_SERVER_ERROR);
}

5. Using @RestControllerAdvice for JSON responses

java

@RestControllerAdvice

public class ApiExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)

public ResponseEntity<Map<String, Object>>


handleNotFound(ResourceNotFoundException ex) {

Map<String, Object> errorDetails = new HashMap<>();

errorDetails.put("error", ex.getMessage());

errorDetails.put("timestamp", LocalDateTime.now());

return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);

6. Throwing Exception in Controller/Service

java

@GetMapping("/products/{id}")

public Product getProductById(@PathVariable Long id) {

return productRepository.findById(id)

.orElseThrow(() -> new ResourceNotFoundException("Product not found with ID " +


id));

}
Interview Questions with Answers

Q1: What is @ControllerAdvice in Spring Boot?


It allows you to define global exception handling logic in one place.

Q2: How is @RestControllerAdvice di erent from @ControllerAdvice?


It’s a shorthand for @ControllerAdvice + @ResponseBody, used when returning
JSON responses.

Q3: What is the benefit of using @ExceptionHandler?


It provides fine-grained control for handling specific exceptions.

Q4: How do you return custom error JSON messages?


Use @RestControllerAdvice and return a Map<String, Object> or a custom error
response class.

Topic 11: Spring Boot Security Basics – Authentication & Authorization

Spring Security is a powerful and highly customizable authentication and access-


control framework. Spring Boot integrates it easily to secure REST APIs and web apps.

1. Key Concepts

Term Description

Authentication Verifying the identity of a user (e.g., login credentials).

Authorization Granting access to specific resources based on roles.

Principal Currently logged-in user (represented by UserDetails).

2. Spring Boot Security Starter

Add dependency:

xml

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>
</dependency>

3. Default Behavior

 When added, Spring Security:

o Secures all endpoints by default.

o Requires HTTP Basic Auth or form login.

o Generates a default password in the console.

4. Basic Authentication Example

java

@Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication()

.withUser("admin").password("{noop}admin123").roles("ADMIN")

.and()

.withUser("user").password("{noop}user123").roles("USER");

@Override

protected void configure(HttpSecurity http) throws Exception {

http

.authorizeRequests()

.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")

.anyRequest().authenticated()

.and()

.httpBasic();

5. Key Classes/Annotations

Component Description

@EnableWebSecurity Enables Spring Security configuration

Custom security config class (deprecated in Spring


WebSecurityConfigurerAdapter
Security 6)

AuthenticationManager Used for authentication logic

UserDetailsService Custom user authentication from DB

PasswordEncoder Encodes passwords securely (e.g., BCrypt)

6. Secure Endpoints Example

java

@RestController

public class DemoController {

@GetMapping("/admin/dashboard")

public String admin() {

return "Welcome Admin!";

}
@GetMapping("/user/profile")

public String user() {

return "Welcome User!";

7. Password Encoding

java

@Bean

public PasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

8. Custom UserDetailsService

java

@Service

public class MyUserDetailsService implements UserDetailsService {

@Autowired

private UserRepository userRepo;

@Override

public UserDetails loadUserByUsername(String username) throws


UsernameNotFoundException {

User user = userRepo.findByUsername(username);

return new org.springframework.security.core.userdetails.User(

user.getUsername(), user.getPassword(), getAuthorities(user)


);

private Collection<? extends GrantedAuthority> getAuthorities(User user) {

return user.getRoles().stream()

.map(role -> new SimpleGrantedAuthority(role.getName()))

.collect(Collectors.toList());

Interview Questions with Answers

Q1: What is the di erence between Authentication and Authorization?


Authentication verifies identity; Authorization decides what the user is allowed to
access.

Q2: What is the use of @EnableWebSecurity?


It enables Spring Security configuration for custom security rules.

Q3: How do you secure REST endpoints in Spring Boot?


By configuring HttpSecurity in a custom WebSecurityConfigurerAdapter.

Q4: How do you store user credentials securely?


By encoding passwords using PasswordEncoder like BCryptPasswordEncoder.

Topic 12: Spring Boot with Spring Data JPA – Repositories & Queries

Spring Data JPA simplifies data access by abstracting boilerplate code and giving you a
clean repository pattern using interfaces.

1. What is Spring Data JPA?

Spring Data JPA is a part of the Spring Data project. It:

 Reduces boilerplate code for data access.

 Provides automatic implementation of repository interfaces.

 Supports custom queries using JPQL or native SQL.


2. Add JPA & Database Dependencies

For MySQL:

xml

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

3. Application Properties Configuration

properties

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=pass

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

4. Create Entity Class

java
@Entity

public class Student {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

private String course;

5. Create Repository Interface

java

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findByCourse(String course); // Custom finder method

6. Using the Repository

java

@RestController

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentRepository repo;

@PostMapping
public Student save(@RequestBody Student student) {

return repo.save(student);

@GetMapping

public List<Student> all() {

return repo.findAll();

@GetMapping("/course/{course}")

public List<Student> byCourse(@PathVariable String course) {

return repo.findByCourse(course);

7. Custom Queries with @Query

java

@Query("SELECT s FROM Student s WHERE s.name = :name")

List<Student> findByName(@Param("name") String name);

8. Common JPA Query Keywords

Keyword Example Method SQL Equivalent

findBy findByName(String name) WHERE name=?

findByAnd findByNameAndCourse(...) AND

findByOr findByNameOrCourse(...) OR

findByBetween findByAgeBetween(min, max) BETWEEN


Keyword Example Method SQL Equivalent

findByIn findByCourseIn(List<String> c) IN (...)

9. Paging and Sorting

java

Pageable pageable = PageRequest.of(0, 5, Sort.by("name"));

Page<Student> page = repo.findAll(pageable);

Interview Questions with Answers

Q1: What is JpaRepository?


It's a JPA-specific extension of CrudRepository that provides additional methods like
paging and sorting.

Q2: What does @Query do?


Allows custom queries using JPQL or SQL instead of method naming conventions.

Q3: Di erence between findAll() and custom finder?


findAll() returns all records; custom finders apply filtering.

Q4: How do you sort data using Spring Data JPA?


Use Sort.by("field") or pass Pageable with sort options.

Topic 13: Spring Boot RESTful API Development – Controllers & CRUD

Spring Boot makes it easy to build RESTful APIs with full CRUD (Create, Read, Update,
Delete) operations.

1. What is a RESTful API?

A RESTful API:

 Uses HTTP methods like GET, POST, PUT, DELETE.

 Is stateless.

 Works with resources via URIs.


2. Key Annotations

Annotation Purpose

@RestController Marks a class as a REST controller

@RequestMapping Base URL mapping

@GetMapping Maps HTTP GET

@PostMapping Maps HTTP POST

@PutMapping Maps HTTP PUT

@DeleteMapping Maps HTTP DELETE

@PathVariable Bind URL variable

@RequestBody Bind JSON to Java object

3. Example Entity: Student.java

java

@Entity

public class Student {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

private String course;

4. Example Repository

java
public interface StudentRepository extends JpaRepository<Student, Long> { }

5. REST Controller

java

@RestController

@RequestMapping("/api/students")

public class StudentController {

@Autowired

private StudentRepository studentRepo;

@PostMapping

public Student create(@RequestBody Student student) {

return studentRepo.save(student);

@GetMapping

public List<Student> getAll() {

return studentRepo.findAll();

@GetMapping("/{id}")

public ResponseEntity<Student> getById(@PathVariable Long id) {

return studentRepo.findById(id)

.map(ResponseEntity::ok)

.orElse(ResponseEntity.notFound().build());
}

@PutMapping("/{id}")

public ResponseEntity<Student> update(@PathVariable Long id, @RequestBody


Student newStudent) {

return studentRepo.findById(id)

.map(student -> {

student.setName(newStudent.getName());

student.setCourse(newStudent.getCourse());

return ResponseEntity.ok(studentRepo.save(student));

}).orElse(ResponseEntity.notFound().build());

@DeleteMapping("/{id}")

public ResponseEntity<Void> delete(@PathVariable Long id) {

return studentRepo.findById(id)

.map(student -> {

studentRepo.delete(student);

return ResponseEntity.noContent().build();

}).orElse(ResponseEntity.notFound().build());

6. Sample API Endpoints

HTTP Method URL Description

GET /api/students Get all students

GET /api/students/{id} Get by ID


HTTP Method URL Description

POST /api/students Create student

PUT /api/students/{id} Update student

DELETE /api/students/{id} Delete student

Interview Questions with Answers

Q1: What is the purpose of @RestController?


It’s a combination of @Controller and @ResponseBody, used for REST APIs.

Q2: How do you bind JSON data to Java objects?


Using @RequestBody.

Q3: How to return proper HTTP responses?


Use ResponseEntity for status codes and body.

Q4: Di erence between @RequestParam and @PathVariable?


@RequestParam is for query parameters; @PathVariable is for URI path values.

Topic 14: Spring Boot – Validation and Exception Handling

Validation ensures data integrity, and proper exception handling improves API reliability.

1. Spring Boot Validation with javax.validation

Spring Boot supports validation using annotations like:

Annotation Description

@NotNull Field must not be null

@NotEmpty Field must not be empty

@Size(min, max) Field size must be within limits

@Email Must be a valid email address

@Min, @Max Numeric range

Add dependency if not already present:

xml
<!-- Maven -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-validation</artifactId>

</dependency>

2. Applying Validation in DTO or Entity

java

public class StudentDTO {

@NotEmpty(message = "Name is required")

private String name;

@Email(message = "Invalid email format")

private String email;

@Min(value = 18, message = "Minimum age is 18")

private int age;

3. Controller with Validation

java

@PostMapping("/students")

public ResponseEntity<?> createStudent(@Valid @RequestBody StudentDTO


studentDTO, BindingResult result) {
if (result.hasErrors()) {

List<String> errors = result.getFieldErrors()

.stream()

.map(DefaultMessageSourceResolvable::getDefaultMessage)

.collect(Collectors.toList());

return ResponseEntity.badRequest().body(errors);

// Save logic here

return ResponseEntity.ok("Student created");

4. Global Exception Handling with @ControllerAdvice

java

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)

public ResponseEntity<Map<String, String>>


handleValidationExceptions(MethodArgumentNotValidException ex) {

Map<String, String> errors = new HashMap<>();

ex.getBindingResult().getFieldErrors().forEach(error ->

errors.put(error.getField(), error.getDefaultMessage()));

return ResponseEntity.badRequest().body(errors);

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String>
handleResourceNotFound(ResourceNotFoundException ex) {

return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());

5. Custom Exception Example

java

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException(String message) {

super(message);

Interview Questions with Answers

Q1: How do you handle input validation in Spring Boot?


By using javax.validation annotations and @Valid in controller methods.

Q2: What is @ControllerAdvice used for?


It allows centralized exception handling for multiple controllers.

Q3: What is MethodArgumentNotValidException?


It's thrown when validation on an argument annotated with @Valid fails.

Q4: What is the role of BindingResult?


It holds validation results and helps you check and return custom error messages.

Topic 15: Spring Boot – AOP (Aspect-Oriented Programming)

AOP helps separate cross-cutting concerns like logging, security, or transaction


management from business logic.

1. What is AOP?
 AOP allows modularizing concerns that cut across multiple classes or
methods.

 Common examples: logging, security, transactions.

2. Key AOP Terminologies

Term Description

Aspect A class that contains cross-cutting concerns (logging, etc.)

Advice Code that runs at a join point (before, after, around)

Join Point A point in program execution (e.g., method call)

Pointcut Expression that matches join points

Weaving Linking aspect with main code (done at runtime in Spring)

3. AOP Annotations in Spring

Annotation Purpose

@Aspect Marks a class as an aspect

@Before Advice before method execution

@After Advice after method execution

@AfterReturning After method returns normally

@AfterThrowing After method throws an exception

@Around Around advice (before & after together)

4. Maven Dependency (if not already included)

xml

<dependency>

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>

</dependency>

5. Example: Logging Aspect

java

@Aspect

@Component

public class LoggingAspect {

@Before("execution(* com.myapp.service.*.*(..))")

public void logBeforeMethod(JoinPoint joinPoint) {

System.out.println("Executing: " + joinPoint.getSignature());

@AfterReturning(pointcut = "execution(* com.myapp.service.*.*(..))", returning =


"result")

public void logAfterReturning(JoinPoint joinPoint, Object result) {

System.out.println("Returned from: " + joinPoint.getSignature() + " with result: " +


result);

6. Enable AOP (if needed)

java

@SpringBootApplication

@EnableAspectJAutoProxy
public class MyApp {

public static void main(String[] args) {

SpringApplication.run(MyApp.class, args);

Interview Questions with Answers

Q1: What is AOP in Spring Boot?


AOP is used to separate cross-cutting concerns from business logic using aspects.

Q2: What is the di erence between @Before and @Around?


@Before runs before a method, while @Around can control the entire method
execution (before and after).

Q3: How do you declare a Pointcut expression?


Using execution(...), e.g., execution(* com.app.service.*.*(..)).

Q4: What is weaving?


The process of linking aspect code with main code at runtime or compile time.

Topic 16: Spring Boot – Spring Data JPA & Hibernate

Spring Data JPA simplifies the implementation of data access layers using JPA and
Hibernate under the hood.

1. What is Spring Data JPA?

 A part of the Spring Data project.

 Helps reduce boilerplate code for database operations.

 Uses Hibernate (a JPA implementation) by default.

2. Dependencies

xml

<dependency>
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId> <!-- For in-memory DB -->

</dependency>

3. Application Properties Configuration

properties

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.hibernate.ddl-auto=update

4. Entity Class

java

@Entity

public class User {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;


private String email;

// getters & setters

5. Repository Interface

java

public interface UserRepository extends JpaRepository<User, Long> {

List<User> findByName(String name);

Spring automatically provides CRUD methods:

 save()

 findById()

 findAll()

 deleteById()

 count()

6. Using Repository in Service

java

@Service

public class UserService {

@Autowired

private UserRepository userRepo;

public List<User> getAllUsers() {

return userRepo.findAll();
}

7. Custom Query Example

java

@Query("SELECT u FROM User u WHERE u.email = ?1")

User getUserByEmail(String email);

Interview Questions with Answers

Q1: What is the di erence between JPA and Hibernate?


JPA is a specification; Hibernate is a concrete implementation of JPA.

Q2: What is the use of @Entity annotation?


Marks a class as a JPA entity (a table in the DB).

Q3: What does spring.jpa.hibernate.ddl-auto do?


It defines how the schema is initialized (create, update, validate, none).

Q4: What is JpaRepository?


An interface in Spring Data JPA that provides CRUD and pagination methods.

Q5: Can we write custom queries?


Yes, using the @Query annotation or Spring Data query method naming
conventions.

Topic 17: Spring Boot – Exception Handling (Global & Custom)

Exception handling ensures that your application handles unexpected situations


gracefully and sends meaningful responses to the client.

1. Types of Exception Handling in Spring Boot

1. Local Exception Handling – try-catch blocks.

2. Global Exception Handling – using @ControllerAdvice.

3. Custom Exception Classes – define your own exceptions.


2. Create a Custom Exception

java

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException(String message) {

super(message);

3. Throw Custom Exception in Service/Controller

java

public User getUserById(Long id) {

return userRepo.findById(id)

.orElseThrow(() -> new ResourceNotFoundException("User not found with ID: " + id));

4. Global Exception Handler using @ControllerAdvice

java

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)

public ResponseEntity<?> handleResourceNotFound(ResourceNotFoundException


ex) {

Map<String, String> error = new HashMap<>();


error.put("error", ex.getMessage());

return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);

@ExceptionHandler(Exception.class)

public ResponseEntity<?> handleGlobalException(Exception ex) {

Map<String, String> error = new HashMap<>();

error.put("error", "Internal server error");

return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

5. Response Structure (Optional – Create an ErrorDetails Class)

java

public class ErrorDetails {

private String message;

private Date timestamp;

// constructor, getters, setters

Interview Questions with Answers

Q1: What is the role of @ControllerAdvice in Spring Boot?


It's used for global exception handling across the whole application.

Q2: What is @ExceptionHandler?


It defines which method should handle a specific exception.
Q3: How do you create custom exceptions in Spring Boot?
By extending RuntimeException or Exception class and annotating handlers using
@ExceptionHandler.

Q4: What is the advantage of centralized exception handling?


Reduces boilerplate code and maintains consistency in error responses.

Topic 18: Spring Boot – Logging with SLF4J & Logback

Logging is essential for monitoring and debugging applications. Spring Boot uses SLF4J
with Logback as the default logging framework.

1. What is SLF4J?

 SLF4J stands for Simple Logging Facade for Java.

 It’s an abstraction layer for various logging frameworks (like Logback, Log4J,
java.util.logging).

2. Logback – Default Logging Framework

Spring Boot uses Logback as its default logging implementation behind SLF4J.

3. Logging Levels (from least to most severe)

Level Description

TRACE Most detailed information

DEBUG Debugging information

INFO General information

WARN Warning messages

ERROR Error messages

4. How to Use Logger in Spring Boot

java
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.web.bind.annotation.*;

@RestController

public class MyController {

Logger logger = LoggerFactory.getLogger(MyController.class);

@GetMapping("/test")

public String testLogging() {

logger.info("INFO message");

logger.debug("DEBUG message");

logger.error("ERROR message");

return "Check the logs!";

5. Configuring Logging in application.properties

properties

logging.level.root=INFO

logging.level.com.yourpackage=DEBUG

logging.file.name=app.log

logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

6. Use External Logback Configuration (Optional)

Create a file: logback-spring.xml

xml
<configuration>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

<encoder>

<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -


%msg%n</pattern>

</encoder>

</appender>

<root level="info">

<appender-ref ref="STDOUT" />

</root>

</configuration>

Interview Questions with Answers

Q1: What is SLF4J in Spring Boot?


It's a logging facade that allows developers to plug in di erent logging frameworks.

Q2: What is the default logging framework in Spring Boot?


Logback

Q3: How do you change the log level for a specific package?
Use logging.level.com.example=DEBUG in application.properties.

Q4: How do you write logs to a file in Spring Boot?


Add logging.file.name=app.log in application.properties.

Topic 19: Spring Boot – Integrating Spring Security

Spring Security is a powerful and customizable authentication and access-control


framework. It is the de facto standard for securing Spring-based applications.

1. What is Spring Security?

 A framework that provides authentication, authorization, and protection


against common attacks (like CSRF, session fixation, etc.).
 Comes pre-integrated with Spring Boot.

2. Adding Spring Security Dependency

xml

<!-- Maven -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

3. Default Behavior After Adding Dependency

 All endpoints are secured.

 Default login page is enabled.

 Default credentials:

o Username: user

o Password: auto-generated (check console on startup).

4. Custom Security Configuration

java

import org.springframework.context.annotation.Bean;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.web.SecurityFilterChain;

import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@EnableWebSecurity
public class SecurityConfig {

@Bean

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http

.authorizeHttpRequests(auth -> auth

.requestMatchers("/public/**").permitAll()

.anyRequest().authenticated())

.formLogin();

return http.build();

5. In-Memory Authentication

java

import org.springframework.security.core.userdetails.User;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Bean

public InMemoryUserDetailsManager userDetailsService() {

UserDetails user = User.withDefaultPasswordEncoder()

.username("admin")

.password("password")

.roles("ADMIN")

.build();

return new InMemoryUserDetailsManager(user);


}

6. Common Security Annotations

Annotation Purpose

@EnableWebSecurity Enables Spring Security

@PreAuthorize Method-level security (uses SpEL)

@Secured Role-based access control

Common Attacks Prevented by Spring Security

 CSRF (Cross Site Request Forgery)

 Session Fixation

 Clickjacking

 XSS (Cross Site Scripting)

Interview Questions with Answers

Q1: What is Spring Security?


It’s a Spring-based framework that handles authentication, authorization, and
security.

Q2: What happens when you add Spring Security to your Spring Boot app?
All endpoints become secured, and a default login form is shown.

Q3: How do you allow public access to certain endpoints?


Using .requestMatchers("/public/**").permitAll() in HttpSecurity.

Q4: What is the use of @EnableWebSecurity?


It enables Spring Security's web security support.

Q5: How do you create an in-memory user in Spring Security?


Use InMemoryUserDetailsManager and User.withDefaultPasswordEncoder().

Topic 20: Spring Boot – Monitoring with Actuator

Spring Boot Actuator helps you monitor and manage your application in production by
exposing several built-in endpoints related to health, metrics, environment, and more.
1. Adding the Actuator Dependency

xml

<!-- Maven -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

2. Enabling Actuator Endpoints

You can enable specific endpoints in application.properties:

properties

management.endpoints.web.exposure.include=health,info,metrics

Or to expose all:

properties

management.endpoints.web.exposure.include=*

3. Common Actuator Endpoints

Endpoint Purpose

/actuator/health Shows app health status

/actuator/info Displays custom app info

/actuator/metrics Shows application metrics (CPU, memory)

/actuator/env Displays environment properties


Endpoint Purpose

/actuator/beans Shows all Spring beans

4. Customizing Health Info

java

@Bean

public HealthIndicator customHealthIndicator() {

return () -> Health.up().withDetail("custom", "All good").build();

5. Adding Info in application.properties

properties

management.endpoints.web.exposure.include=info

info.app.name=My Spring Boot App

info.app.version=1.0.0

6. Securing Actuator Endpoints

 You can secure actuator endpoints using Spring Security:

properties

management.endpoints.web.exposure.include=health,info

management.endpoint.health.roles=ADMIN

🛠 Example with Spring Security

java
http

.authorizeHttpRequests()

.requestMatchers("/actuator/**").hasRole("ADMIN")

.anyRequest().authenticated();

Interview Questions with Answers

Q1: What is Spring Boot Actuator?


It provides production-ready features like health checks, metrics, and monitoring.

Q2: How do you enable all Actuator endpoints?


management.endpoints.web.exposure.include=*

Q3: How do you show custom info in the /info endpoint?


Add info.* properties in application.properties.

Q4: How do you customize the /health endpoint?


Implement HealthIndicator bean.

Q5: How can you secure the Actuator endpoints?


Use Spring Security and restrict access using roles.

Topic 21: Spring Boot – Building RESTful Web Services (CRUD APIs)

Spring Boot simplifies the development of RESTful APIs by using annotations and
automatic configurations.

1. Key Annotations for REST APIs

Annotation Description

@RestController Combines @Controller + @ResponseBody

@RequestMapping Maps URLs to controller methods

@GetMapping Handles HTTP GET requests

@PostMapping Handles HTTP POST requests

@PutMapping Handles HTTP PUT requests


Annotation Description

@DeleteMapping Handles HTTP DELETE requests

@PathVariable Binds URI template variables

@RequestParam Extracts query parameters

@RequestBody Binds request JSON to Java object

@ResponseBody Returns data as JSON/XML

2. Example: Basic CRUD API for Student

Model

java

public class Student {

private Long id;

private String name;

private String email;

Controller

java

@RestController

@RequestMapping("/students")

public class StudentController {

private List<Student> students = new ArrayList<>();

@GetMapping

public List<Student> getAllStudents() {


return students;

@PostMapping

public String addStudent(@RequestBody Student student) {

students.add(student);

return "Student added!";

@GetMapping("/{id}")

public Student getStudent(@PathVariable Long id) {

return students.stream()

.filter(s -> s.getId().equals(id))

.findFirst()

.orElse(null);

@PutMapping("/{id}")

public String updateStudent(@PathVariable Long id, @RequestBody Student


updatedStudent) {

for (Student s : students) {

if (s.getId().equals(id)) {

s.setName(updatedStudent.getName());

s.setEmail(updatedStudent.getEmail());

return "Updated successfully!";

return "Student not found!";


}

@DeleteMapping("/{id}")

public String deleteStudent(@PathVariable Long id) {

students.removeIf(s -> s.getId().equals(id));

return "Deleted successfully!";

3. Best Practices

 Use @Service for business logic

 Use @Repository for DB access (e.g., using JPA)

 Use DTOs for request/response

 Return ResponseEntity<T> for better control over status codes

Interview Questions with Answers

Q1: How do you expose a REST API in Spring Boot?


Use @RestController and request mapping annotations like @GetMapping,
@PostMapping, etc.

Q2: What is the use of @RequestBody?


It binds the incoming JSON payload to a Java object.

Q3: How do you return proper HTTP status codes?


By using ResponseEntity<T>.

Q4: What’s the role of @PathVariable vs @RequestParam?


@PathVariable maps URL path variables, @RequestParam maps query parameters.

Q5: How do you handle exceptions in REST APIs?


Use @ControllerAdvice with @ExceptionHandler.

Topic 22: Spring Boot – REST Exception Handling


Exception handling ensures that your REST API responds with meaningful and
standardized error messages when something goes wrong.

1. Why Exception Handling?

 Improves API usability and debugging

 Prevents exposing internal stack traces

 Returns meaningful HTTP status codes and messages

2. Common Exception Types

Exception Description

EntityNotFoundException When resource not found

MethodArgumentNotValidException Validation errors in request body

HttpRequestMethodNotSupportedException Wrong HTTP method used

3. Using @ControllerAdvice for Global Handling

java

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)

public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {

return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

@ExceptionHandler(Exception.class)

public ResponseEntity<String> handleAll(Exception ex) {


return new ResponseEntity<>("An error occurred: " + ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);

4. Custom Exception Class

java

public class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException(String message) {

super(message);

5. Return Custom JSON Error Response

java

public class ErrorResponse {

private String message;

private LocalDateTime timestamp;

private String details;

// Constructor, getters, setters

java

@ExceptionHandler(ResourceNotFoundException.class)

public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException


ex) {
ErrorResponse error = new ErrorResponse(

ex.getMessage(),

LocalDateTime.now(),

"Resource not available"

);

return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);

Interview Questions with Answers

Q1: What is @ControllerAdvice in Spring Boot?


It's a centralized exception handler for all controllers.

Q2: How do you handle specific exceptions?


Use @ExceptionHandler(ExceptionType.class) inside a class annotated with
@ControllerAdvice.

Q3: How do you send custom error messages?


Create a custom response object and return it with ResponseEntity.

Q4: What's the di erence between @RestControllerAdvice and


@ControllerAdvice?
@RestControllerAdvice = @ControllerAdvice + @ResponseBody.

Topic 23: Spring Boot – Validation using Hibernate Validator

Hibernate Validator is the reference implementation of the Bean Validation API (JSR
380) used in Spring Boot for validating user input.

1. Add Validation Dependency (if not already included)

xml

<!-- Spring Boot Starter Web includes it by default -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2. Using Annotations in DTOs or Entities

java

public class UserDTO {

@NotBlank(message = "Username is mandatory")

private String username;

@Email(message = "Email should be valid")

private String email;

@Min(value = 18, message = "Age should be at least 18")

private int age;

// Getters and Setters

3. Enable Validation in Controller

java

@RestController

@RequestMapping("/users")

public class UserController {

@PostMapping

public ResponseEntity<String> createUser(@Valid @RequestBody UserDTO user) {


return ResponseEntity.ok("User created successfully");

4. Handle Validation Errors

java

@ControllerAdvice

public class ValidationExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)

public ResponseEntity<Map<String, String>>


handleValidationErrors(MethodArgumentNotValidException ex) {

Map<String, String> errors = new HashMap<>();

ex.getBindingResult().getFieldErrors().forEach(error ->

errors.put(error.getField(), error.getDefaultMessage())

);

return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);

5. Common Validation Annotations

Annotation Description

@NotNull Field must not be null

@NotBlank Not null and not empty string

@Email Must be a valid email address

@Size(min, max) Length or size constraints


Annotation Description

@Min, @Max Minimum or maximum value

@Pattern Regex pattern validation

Interview Questions with Answers

Q1: What is the purpose of @Valid in Spring Boot?


It triggers validation on the object before method execution.

Q2: What happens if validation fails?


A MethodArgumentNotValidException is thrown, which can be handled globally.

Q3: Can validation be done on path variables or request parameters?


Yes, using @Validated at class level with annotations like @Min, @Pattern.

Q4: What's the di erence between @NotBlank and @NotNull?


@NotNull only checks for null. @NotBlank checks for null + non-empty + non-
whitespace.

Topic 24: Spring Boot – Using Lombok

Lombok is a Java library that helps reduce boilerplate code like getters, setters,
constructors, toString(), etc., by using annotations.

1. Add Lombok Dependency

For Maven:

xml

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<version>1.18.30</version> <!-- Check for latest version -->

<scope>provided</scope>

</dependency>

Make sure annotation processing is enabled in your IDE (e.g., IntelliJ or Eclipse).
2. Common Lombok Annotations

Annotation Purpose

@Getter, @Setter Auto-generate getter/setter

@ToString Generate toString() method

@NoArgsConstructor Generate no-arg constructor

@AllArgsConstructor All-arg constructor

@RequiredArgsConstructor Constructor with final fields

Combines @Getter, @Setter, @ToString,


@Data
@EqualsAndHashCode, @RequiredArgsConstructor

@Builder Implements Builder pattern

@Slf4j Logger setup (log.info(...))

3. Example

java

import lombok.*;

@Data

@NoArgsConstructor

@AllArgsConstructor

@Builder

public class User {

private Long id;

private String name;

private String email;

}
Now you don’t need to write any constructors, getters, setters, or toString() manually.

4. Logging Example

java

import lombok.extern.slf4j.Slf4j;

@Slf4j

@RestController

public class MyController {

@GetMapping("/")

public String hello() {

log.info("Hello endpoint hit");

return "Hello Lombok!";

Interview Questions

Q1: What is Lombok and why use it?


Lombok is a Java library that reduces boilerplate code in Java classes using
annotations.

Q2: Does Lombok work at runtime or compile-time?


Lombok operates at compile-time, generating bytecode before compilation
completes.

Q3: What does @Data include?


It includes @Getter, @Setter, @ToString, @EqualsAndHashCode, and
@RequiredArgsConstructor.

Q4: Is Lombok mandatory in Spring Boot projects?


No, it's optional but widely used to simplify code.
Topic 25: Spring Boot – Actuator (Monitoring & Management)

Spring Boot Actuator provides production-ready features to help monitor and manage
your application — like checking health, metrics, environment properties, etc.

1. Add Actuator Dependency

xml

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

2. Enable Endpoints in application.properties

properties

management.endpoints.web.exposure.include=*

# To include specific ones only:

# management.endpoints.web.exposure.include=health,info

3. Common Actuator Endpoints

Endpoint Purpose

/actuator/health Shows application health status

/actuator/info Displays custom application info

/actuator/metrics Exposes various metrics (memory, CPU)

/actuator/env Shows environment properties

/actuator/beans Shows all Spring beans

/actuator/mappings Shows request mappings


4. Customizing /info Endpoint

properties

management.endpoints.web.exposure.include=info

info.app.name=MySpringApp

info.app.version=1.0.0

Use @ConfigurationProperties or @Value for dynamic info.

5. Securing Actuator Endpoints

You can use Spring Security to restrict access:

properties

management.endpoints.web.exposure.include=health,info

management.endpoint.health.show-details=when_authorized

Interview Questions

Q1: What is Spring Boot Actuator?


A module that exposes internal application info for monitoring and management.

Q2: Is Actuator production-safe?


Yes, but always secure sensitive endpoints using authentication or limited exposure.

Q3: How to expose custom data in /info?


Set values in application.properties or use custom configuration beans.

Q4: Can we create custom actuator endpoints?


Yes, by using @Endpoint or @RestController.

Topic 26: Spring Boot – Monitoring with Prometheus & Grafana

This topic focuses on integrating Prometheus (a metrics collector) and Grafana (a


visualization tool) with Spring Boot apps using Actuator and Micrometer.
1. Add Micrometer Prometheus Dependency

xml

<dependency>

<groupId>io.micrometer</groupId>

<artifactId>micrometer-registry-prometheus</artifactId>

</dependency>

Also include:

xml

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

2. Configure application.properties

properties

management.endpoints.web.exposure.include=*

management.endpoint.prometheus.enabled=true

management.metrics.export.prometheus.enabled=true

This enables /actuator/prometheus endpoint which Prometheus can scrape.

3. Prometheus Setup

 Install Prometheus

 Configure prometheus.yml:

yaml
scrape_configs:

- job_name: 'spring-boot-app'

metrics_path: '/actuator/prometheus'

static_configs:

- targets: ['localhost:8080']

 Start Prometheus and open http://localhost:9090

4. Grafana Setup

 Install Grafana

 Add Prometheus as a data source

 Create dashboards using:

o CPU usage

o Memory consumption

o Custom metrics (@Timed, @Counted, etc.)

5. Custom Metrics with Micrometer

java

@Autowired

MeterRegistry meterRegistry;

@PostConstruct

public void init() {

meterRegistry.counter("my.custom.counter").increment();

Interview Questions
Q1: What is Micrometer?
Micrometer is a metrics collection library backed by various monitoring tools like
Prometheus, Datadog, etc.

Q2: How do you expose metrics to Prometheus in Spring Boot?


Use Actuator + Micrometer and expose /actuator/prometheus.

Q3: How can we track custom business metrics?


Inject MeterRegistry and use .counter(), .timer() etc.

Topic 27: Spring Boot – Logging & Log Management

Logging is crucial for debugging, monitoring, and auditing application behavior. Spring
Boot provides built-in support for popular logging frameworks.

1. Default Logging Framework

 Spring Boot uses Logback by default.

 Supports: Logback, Log4j2, Java Util Logging (JUL), etc.

2. Logging Levels (from most to least severe)

 ERROR

 WARN

 INFO

 DEBUG

 TRACE

Configure in application.properties:

properties

logging.level.root=INFO

logging.level.com.yourpackage=DEBUG

3. Log File Output

By default, logs print to the console. To log to a file:


properties

logging.file.name=app.log

logging.file.path=/var/logs

This creates /var/logs/app.log

4. Custom Log Pattern

properties

logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

You can also configure logback-spring.xml for full customization.

5. External Log Management Tools

 ELK Stack (Elasticsearch + Logstash + Kibana)

 Fluentd + Loki + Grafana

 Graylog

 These tools help centralize and analyze logs from multiple microservices.

6. Logging in Code

java

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

@RestController

public class MyController {

Logger logger = LoggerFactory.getLogger(MyController.class);


@GetMapping("/log")

public String logExample() {

logger.info("This is an info message.");

logger.debug("This is a debug message.");

return "Check logs!";

Interview Questions

Q1: What logging framework does Spring Boot use by default?


Logback.

Q2: How do you log messages in a Spring Boot class?


Use SLF4J Logger and LoggerFactory.

Q3: How can you change the logging level for a package?
Use logging.level.<package>=LEVEL in application.properties.

Topic 28: Spring Boot – AOP (Aspect-Oriented Programming)

Aspect-Oriented Programming (AOP) allows you to isolate cross-cutting concerns like


logging, security, and transaction management from business logic.

1. What is AOP?

 AOP helps in separating cross-cutting concerns from the main business logic.

 These are aspects that a ect multiple parts of the application (e.g., logging,
security).

2. AOP Terminology

Term Description

Aspect A module that encapsulates cross-cutting logic

Join Point A point during execution (like a method call)


Term Description

Advice Code that runs at a join point (e.g., before or after a method)

Pointcut Expression that matches join points

Weaving Linking aspects with application code

3. Types of Advice

 @Before: Runs before the method execution

 @After: Runs after the method finishes (whether it fails or not)

 @AfterReturning: Runs after method returns a result

 @AfterThrowing: Runs after a method throws an exception

 @Around: Runs before and after the method (can modify behavior)

4. Basic Example

java

@Aspect

@Component

public class LoggingAspect {

@Before("execution(* com.example.service.*.*(..))")

public void logBefore(JoinPoint joinPoint) {

System.out.println("Calling method: " + joinPoint.getSignature().getName());

 @Aspect marks the class as an aspect.

 execution(* com.example.service.*.*(..)) is a pointcut expression that applies to


all methods in the service package.
5. Enable AOP in Spring Boot

Spring Boot already includes Spring AOP. Just annotate configuration class with:

java

@EnableAspectJAutoProxy

6. Use Cases of AOP

 Logging

 Transaction Management

 Security

 Caching

 Performance monitoring

Interview Questions

Q1: What is AOP in Spring Boot?


A programming technique to separate cross-cutting concerns using Aspects.

Q2: How is AOP implemented in Spring Boot?


Using @Aspect and AOP proxies.

Q3: What is the use of @Around advice?


Allows you to control method execution before and after the join point.

Topic 29: Spring Boot – Internationalization (i18n)

Internationalization (i18n) is the process of designing your application so that it can be


adapted to di erent languages and regions without engineering changes.

1. What is i18n?

 i18n stands for Internationalization (first letter i, last letter n, and 18 letters in
between).

 Allows your application to support multiple languages.


 Useful in global applications where users belong to di erent locales.

2. Steps to Enable i18n in Spring Boot

Step 1: Add Message Properties Files

plaintext

src/main/resources/messages.properties // default

src/main/resources/messages_fr.properties // French

src/main/resources/messages_hi.properties // Hindi

Example:

properties

# messages.properties

greeting=Hello

# messages_fr.properties

greeting=Bonjour

# messages_hi.properties

greeting=नम े

Step 2: Configure a LocaleResolver Bean

java

@Bean

public LocaleResolver localeResolver() {

SessionLocaleResolver slr = new SessionLocaleResolver();

slr.setDefaultLocale(Locale.ENGLISH);

return slr;
}

Step 3: Add Locale Change Interceptor

java

@Bean

public LocaleChangeInterceptor localeChangeInterceptor() {

LocaleChangeInterceptor lci = new LocaleChangeInterceptor();

lci.setParamName("lang");

return lci;

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(localeChangeInterceptor());

3. How to Use MessageSource

java

@Autowired

private MessageSource messageSource;

public String getGreeting(Locale locale) {

return messageSource.getMessage("greeting", null, locale);

 Spring will automatically pick the correct message file based on the locale.

4. Set Language via URL


 Example:
http://localhost:8080/greet?lang=fr → Bonjour
http://localhost:8080/greet?lang=hi → नम े

Interview Questions

Q1: What is Internationalization in Spring Boot?


It's a way to adapt your application to di erent languages/locales.

Q2: What annotation or bean is required for i18n?


LocaleResolver, MessageSource, and LocaleChangeInterceptor.

Q3: How do you switch languages dynamically?


By passing the lang parameter in the URL.

like a summary PDF of all 30 topics, or maybe want to revise any specific topic

You might also like