0% found this document useful (0 votes)
10 views29 pages

SpringBoot Interview Guide

The document is a comprehensive interview guide for Spring Boot, covering 28 key topics including IoC, Dependency Injection, REST APIs, JPA/Hibernate, Security, and Microservices. It provides detailed explanations, examples, and best practices for each topic, making it a valuable resource for preparing for technical interviews. Additionally, it contrasts Spring Boot with the Spring Framework, highlighting features like auto-configuration and embedded servers.

Uploaded by

bharathnick0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views29 pages

SpringBoot Interview Guide

The document is a comprehensive interview guide for Spring Boot, covering 28 key topics including IoC, Dependency Injection, REST APIs, JPA/Hibernate, Security, and Microservices. It provides detailed explanations, examples, and best practices for each topic, making it a valuable resource for preparing for technical interviews. Additionally, it contrasts Spring Boot with the Spring Framework, highlighting features like auto-configuration and embedded servers.

Uploaded by

bharathnick0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Spring Boot

Complete Interview Guide


IoC / DI • Annotations • REST APIs • JPA / Hibernate • Security • Testing • Microservices

28 Topics • Deep • Crisp • Interview-Ready

TOC TABLE OF CONTENTS

# Topic

01 Spring Framework Overview — Core Concepts

02 IoC — Inversion of Control

03 Dependency Injection — Types & Examples

04 Spring Bean — Lifecycle & Scopes

05 Spring Boot vs Spring Framework

06 Auto-Configuration & @SpringBootApplication

07 Core Annotations — Complete Reference

08 [Link] / [Link]

09 Profiles — @Profile & [Link]

10 REST API — @RestController, @RequestMapping

11 HTTP Methods & Response Entities

12 Request Handling — @PathVariable, @RequestParam, @RequestBody

13 Exception Handling — @ControllerAdvice, @ExceptionHandler

14 Validation — @Valid, Bean Validation

15 Spring Data JPA — Overview

16 JPA Repositories — CrudRepository, JpaRepository

17 Custom Queries — @Query, JPQL, Native SQL

18 Entity Relationships — @OneToMany, @ManyToMany

19 Transaction Management — @Transactional


Spring Boot — Complete Interview Guide Page 2

# Topic

20 Spring Security — Authentication & Authorization

21 JWT Authentication

22 Spring AOP — Aspect-Oriented Programming

23 Caching — @Cacheable, @CacheEvict

24 Spring Boot Testing — @SpringBootTest, MockMvc

25 Spring Actuator — Health, Metrics, Endpoints

26 Spring Boot DevTools & Configuration

27 Microservices with Spring Boot

28 Spring Boot Quick Reference & Interview Q&A;

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 3

01 Spring Framework Overview — Core Concepts

Module Purpose Key Classes/Annotations

Spring Core IoC container, Dependency Injection ApplicationContext, BeanFactory, @Component

Spring MVC Web layer, REST APIs DispatcherServlet, @Controller, @RestController

Spring Data Database access, repositories JpaRepository, @Entity, @Repository

Spring Security Authentication, Authorization SecurityFilterChain, @PreAuthorize

Spring AOP Cross-cutting concerns @Aspect, @Around, @Before, @After

Spring Boot Auto-config, embedded server @SpringBootApplication, [Link]

Spring Boot vs Spring:


Spring Boot = Spring Framework + Auto-Configuration + Embedded Server + Opinionated Defaults. No XML config needed.

02 IoC — Inversion of Control

IoC = The control of object creation and lifecycle is given to the Spring Container — not the developer. You declare
what you need; Spring provides it.

// WITHOUT IoC — you control object creation


class OrderService {
private PaymentService ps = new PaymentService(); // tight coupling
private EmailService es = new EmailService(); // hard to test/swap
}

// WITH IoC — Spring controls object creation


@Service
class OrderService {
private final PaymentService paymentService; // Spring injects this
private final EmailService emailService;

OrderService(PaymentService ps, EmailService es) {


[Link] = ps;
[Link] = es;
}
}
// Spring creates PaymentService, EmailService, then injects them into OrderService

IoC Container Description Use When

BeanFactory Basic container, lazy-loaded beans Lightweight apps, minimal footprint

ApplicationContext Full-featured: events, AOP, i18n All Spring/Spring Boot apps (standard)

WebApplicationContext ApplicationContext for web layer Web apps — extends ApplicationContext

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 4

03 Dependency Injection — Types & Examples

DI Type How Recommended? Use Case

Constructor Injection Via constructor parameter YES (preferred) Required deps, immutable, easy to test

Setter Injection Via @Autowired on setter Sometimes Optional deps, can be changed later

Field Injection @Autowired directly on field NO Avoid — hides deps, harder to test

// Constructor Injection (PREFERRED) — deps clear, immutable, testable


@Service
public class UserService {
private final UserRepository userRepo;
private final EmailService emailSvc;

// Single constructor — @Autowired is optional since Spring 4.3


public UserService(UserRepository repo, EmailService email) {
[Link] = repo;
[Link] = email;
}
}

// Field Injection (AVOID) — can't inject without Spring, hard to test


@Service
public class BadService {
@Autowired
private UserRepository userRepo; // hidden dependency, not final
}

// @Qualifier — when multiple beans of same type exist


@Autowired
@Qualifier("mysqlUserRepo")
private UserRepository userRepo;

Interview Rule:
Always use constructor injection. It makes dependencies explicit, allows final fields, and works without Spring in unit tests.

04 Spring Bean — Lifecycle & Scopes

Bean Lifecycle

Step What happens Hook

1. Instantiation Spring creates bean instance Constructor called

2. Populate Properties Dependencies injected @Autowired fields set

3. BeanNameAware Bean gets its name setBeanName()

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 5

Step What happens Hook

4. BeanFactoryAware Bean gets factory ref setBeanFactory()

5. @PostConstruct Custom init logic runs @PostConstruct method

6. In use Bean serves requests Normal usage

7. @PreDestroy Cleanup before shutdown @PreDestroy method

8. Destroy Bean removed from context destroy()

@Component
public class DatabasePool {
@PostConstruct
public void init() {
[Link]("Opening DB connection pool"); // after injection
}

@PreDestroy
public void cleanup() {
[Link]("Closing DB connection pool"); // before shutdown
}
}

Bean Scopes

Scope One instance per... Default? Use Case

singleton Application context YES Stateless services, repositories

prototype Each injection / getBean() No Stateful beans, not thread-safe objects

request HTTP request No (Web) Request-specific data

session HTTP session No (Web) User session data

application ServletContext lifetime No (Web) App-wide shared state

@Component
@Scope("prototype") // new instance every time injected
public class ShoppingCart { private List<Item> items = new ArrayList<>(); }

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext { private String requestId; }

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 6

05 Spring Boot vs Spring Framework

Feature Spring Framework Spring Boot

Configuration Explicit XML or Java config Auto-configuration (opinionated defaults)

Server Deploy WAR to external server Embedded Tomcat/Jetty/Undertow

Dependencies Manage versions manually Starter POMs manage compatible versions

Boilerplate High — lots of setup code Minimal — convention over configuration

Startup Slower (more manual setup) Faster (auto-config)

Production Manual setup for metrics etc. Actuator built-in

06 Auto-Configuration & @SpringBootApplication

@SpringBootApplication // = @Configuration + @EnableAutoConfiguration + @ComponentScan


public class MyApp {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Annotation inside @SpringBootApplication


Purpose

@Configuration Marks this class as a source of bean definitions

@EnableAutoConfiguration Tells Spring Boot to auto-configure based on classpath (e.g. if H2 on classpath, configure in-memory DB

@ComponentScan Scans current package and sub-packages for @Component, @Service, @Repository, @Controller

Auto-configuration works via @ConditionalOn* annotations — beans only created when conditions met:

@Configuration
@ConditionalOnClass([Link]) // only if DataSource on classpath
@ConditionalOnMissingBean([Link]) // only if no DataSource bean defined yet
public class DataSourceAutoConfiguration {
@Bean
public DataSource dataSource() { return createDefaultDataSource(); }
}

// Disable specific auto-config if you want to take control


@SpringBootApplication(exclude = {[Link]})
public class MyApp { }

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 7

07 Core Annotations — Complete Reference

Stereotype Annotations (tell Spring to manage the class)


Annotation Extends Use For Enables

@Component — Generic Spring bean Component scan detection

@Service @Component Business logic layer Same as @Component + clarity

@Repository @Component Data access layer Exception translation (DataAccessException)

@Controller @Component MVC web controller Returns view names

@RestController @Controller+@ResponseBody
REST API endpoints Returns JSON/XML directly

Configuration Annotations
Annotation Purpose Example

@Configuration Mark class as config (source of @Bean methods)


@Configuration class AppConfig

@Bean Declare a method that returns a Spring bean @Bean public DataSource ds()

@Primary When multiple beans of same type exist, this is default


@Primary @Bean DataSource ds()

@Qualifier("name") Select specific bean when multiple exist @Autowired @Qualifier("myDs")

@Value("${prop}") Inject a value from properties file @Value("${[Link]}")

@PropertySource Load external .properties file @PropertySource("classpath:[Link]")

@Import Import other @Configuration classes @Import([Link])

@Lazy Don't create bean until first use @Lazy @Component MyBean

Conditional Annotations
Annotation Creates bean only when...

@ConditionalOnClass([Link]) Class X is on the classpath

@ConditionalOnMissingBean([Link]) No bean of type X is already defined

@ConditionalOnProperty("prop") Property 'prop' is set (and optionally has value)

@ConditionalOnWebApplication Running in a web application context

@Profile("dev") Active profile matches 'dev'

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 8

08 [Link] / [Link]

# [Link]
[Link]=8080
[Link]=my-app

# Database
[Link]=jdbc:postgresql://localhost:5432/mydb
[Link]=postgres
[Link]=secret
[Link]-class-name=[Link]

# JPA
[Link]-auto=update
[Link]-sql=true
[Link].format_sql=true

# Logging
[Link]=INFO
[Link]=DEBUG

# Custom property
[Link]=mySecretKey
[Link]=86400000

# Read custom properties with @Value


@Value("${[Link]}")
private String jwtSecret;

# Or bind to a class with @ConfigurationProperties


@Configuration
@ConfigurationProperties(prefix = "[Link]")
public class JwtProperties {
private String secret;
private long expiration;
// getters + setters
}

Property Values Effect

[Link]-auto none / validate / update / create / create-drop


Controls schema generation

[Link] dev / prod / test Activates a profile

[Link] Integer (default 8080) Embedded server port

[Link]-sql true / false Logs SQL to console

09 Profiles — @Profile & [Link]

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 9

// Profile-specific beans
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public DataSource dataSource() { return new H2DataSource(); } // in-memory
}

@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public DataSource dataSource() { return new PostgreSQLDataSource(); }
}

// Profile-specific properties files


// [Link] — active when profile=dev
// [Link] — active when profile=prod

// Activate profile:
// 1. [Link]: [Link]=dev
// 2. Command line: --[Link]=prod
// 3. Environment variable: SPRING_PROFILES_ACTIVE=prod
// 4. In tests: @ActiveProfiles("test")

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 10

10 REST API — @RestController & @RequestMapping

@RestController // = @Controller + @ResponseBody


@RequestMapping("/api/users") // base path for all methods
public class UserController {

private final UserService userService;

UserController(UserService userService) {
[Link] = userService;
}

@GetMapping // GET /api/users


public List<User> getAll() {
return [Link]();
}

@GetMapping("/{id}") // GET /api/users/{id}


public ResponseEntity<User> getById(@PathVariable Long id) {
return [Link](id)
.map(ResponseEntity::ok)
.orElse([Link]().build());
}

@PostMapping // POST /api/users


@ResponseStatus([Link])
public User create(@Valid @RequestBody CreateUserRequest req) {
return [Link](req);
}

@PutMapping("/{id}") // PUT /api/users/{id}


public User update(@PathVariable Long id, @RequestBody UpdateUserRequest req) {
return [Link](id, req);
}

@DeleteMapping("/{id}") // DELETE /api/users/{id}


@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
[Link](id);
}
}

11 HTTP Methods & ResponseEntity

Annotation HTTP Method Typical Response StatusUse Case

@GetMapping GET 200 OK Retrieve resource(s)

@PostMapping POST 201 Created Create new resource

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 11

Annotation HTTP Method Typical Response StatusUse Case

@PutMapping PUT 200 OK Replace entire resource

@PatchMapping PATCH 200 OK Partial update

@DeleteMapping DELETE 204 No Content Delete resource

// ResponseEntity — full control over status, headers, body


[Link](body) // 200 OK with body
[Link](uri).body(obj) // 201 Created
[Link]().build() // 204 No Content
[Link]().build() // 404 Not Found
[Link]().body(errorMsg) // 400 Bad Request
[Link]([Link]).body(msg) // custom status

// With location header on create


@PostMapping
public ResponseEntity<User> create(@RequestBody User user) {
User saved = [Link](user);
URI location = [Link]()
.path("/{id}").buildAndExpand([Link]()).toUri();
return [Link](location).body(saved);
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 12

12 Request Handling — @PathVariable, @RequestParam, @RequestBody

Annotation Source Example URL Example Code

@PathVariable URL path segment /users/42 @PathVariable Long id

@RequestParam Query string /users?page=2&size=10 @RequestParam(defaultValue="0") int page

@RequestBody Request body (JSON) POST /users {"name":"..."} @RequestBody @Valid CreateUserReq req

@RequestHeader HTTP header Authorization: Bearer ... @RequestHeader String authorization

@CookieValue Cookie Cookie: session=abc @CookieValue String session

// Full example with multiple parameter types


@GetMapping("/users/{id}/orders")
public Page<Order> getUserOrders(
@PathVariable Long id,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String status,
@RequestHeader("Authorization") String token
) {
return [Link](id, status, page, size);
}

13 Exception Handling — @ControllerAdvice & @ExceptionHandler

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 13

// Custom exception
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) { super(message); }
}

// Global exception handler — applies to ALL controllers


@RestControllerAdvice // = @ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
return new ErrorResponse(404, [Link]());
}

@ExceptionHandler([Link])
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidation(MethodArgumentNotValidException ex) {
List<String> errors = [Link]().getFieldErrors()
.stream().map(FieldError::getDefaultMessage).toList();
return new ErrorResponse(400, "Validation failed", errors);
}

@ExceptionHandler([Link])
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleGeneral(Exception ex) {
return new ErrorResponse(500, "Internal server error");
}
}

record ErrorResponse(int status, String message, List<String> errors) {


ErrorResponse(int s, String m) { this(s, m, [Link]()); }
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 14

14 Validation — @Valid & Bean Validation

Annotation Validates Example

@NotNull Value is not null @NotNull String name

@NotBlank String is not null, not empty, not only spaces


@NotBlank String email

@NotEmpty Not null and not empty (works for collections)


@NotEmpty List<Item> items

@Size(min,max) String/collection size @Size(min=2,max=50) String name

@Min / @Max Number range @Min(0) @Max(120) int age

@Email Valid email format @Email String email

@Pattern(regexp) Regex match @Pattern(regexp="^\\d{10}$") String phone

@Positive Number > 0 @Positive double price

@Future Date in future @Future LocalDate expiry

@Past Date in past @Past LocalDate dob

// DTO with validation annotations


public record CreateUserRequest(
@NotBlank(message = "Name is required")
@Size(min = 2, max = 50)
String name,

@NotBlank @Email(message = "Invalid email")


String email,

@NotNull @Min(18) @Max(120)


Integer age
) {}

// Controller — trigger validation with @Valid


@PostMapping
public User create(@Valid @RequestBody CreateUserRequest req) {
// If validation fails, MethodArgumentNotValidException is thrown
return [Link](req);
}

15 Spring Data JPA — Overview

Spring Data JPA = Spring Data + Hibernate + JPA. Removes boilerplate DAO code. Repositories auto-implement
common DB operations.

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 15

// Entity class
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = [Link])
private Long id;

@Column(nullable = false, length = 100)


private String name;

@Column(unique = true, nullable = false)


private String email;

@CreationTimestamp
private LocalDateTime createdAt;

@UpdateTimestamp
private LocalDateTime updatedAt;

// Getters, setters or Lombok @Data


}

@GenerationType Description Best For

IDENTITY DB auto-increment (e.g. MySQL AUTO_INCREMENT)


MySQL, PostgreSQL serial

SEQUENCE DB sequence object PostgreSQL (recommended)

UUID Java UUID as PK Distributed systems

AUTO Hibernate decides based on dialect Simple cases

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 16

16 JPA Repositories — CrudRepository & JpaRepository

Interface Extends Provides Use When

Repository<T,ID> — Nothing (marker) Custom methods only

CrudRepository<T,ID> Repository save, findById, findAll, count, delete Basic CRUD

JpaRepository<T,ID> CrudRepository + flush, saveAll, findAll(Sort), paginationMost Spring Boot apps

PagingAndSortingRepository CrudRepository + findAll(Pageable), findAll(Sort) Need pagination

@Repository // optional when extending JpaRepository — Spring detects it


public interface UserRepository extends JpaRepository<User, Long> {

// Derived queries — Spring generates SQL from method name


Optional<User> findByEmail(String email);
List<User> findByAgeGreaterThan(int age);
List<User> findByNameContainingIgnoreCase(String name);
boolean existsByEmail(String email);
long countByAgeGreaterThan(int age);
void deleteByEmail(String email);

// Multiple conditions
List<User> findByNameAndActive(String name, boolean active);
List<User> findByAgeOrderBySalaryDesc(int age);

// Pagination
Page<User> findByActive(boolean active, Pageable pageable);
}

// Usage:
Page<User> page = [Link](true,
[Link](0, 10, [Link]("name").ascending()));
List<User> content = [Link]();
long total = [Link]();

17 Custom Queries — @Query, JPQL, Native SQL

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 17

public interface UserRepository extends JpaRepository<User, Long> {

// JPQL (Java Persistence Query Language) — uses entity/field names


@Query("SELECT u FROM User u WHERE [Link] = :email")
Optional<User> findByEmailJpql(@Param("email") String email);

// JPQL with JOIN


@Query("SELECT u FROM User u JOIN [Link] o WHERE [Link] = :status")
List<User> findUsersWithOrderStatus(@Param("status") String status);

// Native SQL — uses actual table/column names


@Query(value = "SELECT * FROM users WHERE created_at > :date",
nativeQuery = true)
List<User> findCreatedAfter(@Param("date") LocalDateTime date);

// Modifying query (UPDATE/DELETE) — must have @Modifying + @Transactional


@Modifying
@Transactional
@Query("UPDATE User u SET [Link] = false WHERE [Link] < :date")
int deactivateInactiveUsers(@Param("date") LocalDateTime date);

// Named positional parameters (?1, ?2)


@Query("SELECT u FROM User u WHERE [Link] = ?1 OR [Link] = ?2")
List<User> findByNameOrEmail(String name, String email);
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 18

18 Entity Relationships — @OneToMany, @ManyToMany

// One-to-Many: User HAS many Orders


@Entity
public class User {
@Id @GeneratedValue(strategy = [Link])
private Long id;

@OneToMany(mappedBy = "user", cascade = [Link], fetch = [Link])


private List<Order> orders = new ArrayList<>();
}

@Entity
public class Order {
@Id @GeneratedValue(strategy = [Link])
private Long id;

@ManyToOne(fetch = [Link])
@JoinColumn(name = "user_id") // FK column in orders table
private User user;
}

// Many-to-Many: User HAS MANY Roles, Role HAS MANY Users


@Entity
public class User {
@ManyToMany(fetch = [Link])
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
}

FetchType Default for Behaviour Use When

EAGER @ManyToOne, @OneToOne Load related entity immediately with parent Small, always-needed data

LAZY @OneToMany, @ManyToMany Load related data only when accessed Large collections, optional data

N+1 Problem:
LAZY loading in a loop causes N additional queries. Fix: use JOIN FETCH in @Query or @EntityGraph to load eagerly in one query.

19 Transaction Management — @Transactional

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 19

@Service
public class TransferService {

@Transactional // entire method in one transaction


public void transfer(Long fromId, Long toId, BigDecimal amount) {
Account from = [Link](fromId).orElseThrow();
Account to = [Link](toId).orElseThrow();
[Link](amount);
[Link](amount);
// If any exception here → both debit AND credit ROLLED BACK
}

@Transactional(readOnly = true) // optimization for read-only ops


public List<Account> findAll() { return [Link](); }
}

@Transactional Property Options Default Description

propagation REQUIRED, REQUIRES_NEW, NESTED, SUPPORTS,REQUIRED


NOT_SUPPORTED, NEVER,
How transaction
MANDATORY
relates to caller's tra

isolation DEFAULT, READ_UNCOMMITTED, READ_COMMITTED,


DEFAULT
REPEATABLE_READ,
Isolation
SERIALIZABLE
level from ACID

readOnly true / false false Hint to optimize read-only ops — no d

rollbackFor [Link], etc. RuntimeException Which exceptions trigger rollback

noRollbackFor [Link], etc. — Exceptions that should NOT rollback

Propagation Meaning

REQUIRED (default) Join existing transaction, or create new if none

REQUIRES_NEW Always start a new transaction, suspend current

NESTED Start nested transaction; rollback only nested if nested fails

SUPPORTS Join if exists, run non-transactional if none

NOT_SUPPORTED Always run non-transactional, suspend current

NEVER Must not run in transaction — throw if one exists

MANDATORY Must run in existing transaction — throw if none

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 20

20 Spring Security — Authentication & Authorization

Spring Security uses a filter chain. Every HTTP request passes through filters before reaching your controller.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> [Link]()) // disable for REST APIs
.sessionManagement(sm ->
[Link]([Link]))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll() // public endpoints
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers([Link], "/api/**").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated() // all others need auth
)
.addFilterBefore(jwtFilter, [Link]);
return [Link]();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // ALWAYS hash passwords
}

@Bean
public AuthenticationManager authManager(AuthenticationConfiguration config)
throws Exception { return [Link](); }
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 21

// UserDetailsService — tell Spring Security how to load a user


@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired UserRepository userRepo;

@Override
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
User user = [Link](email)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
return [Link]
.withUsername([Link]())
.password([Link]())
.roles([Link]())
.build();
}
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 22

21 JWT Authentication — Full Flow

Step Action

1. Login POST /auth/login with username+password

2. Authenticate Spring Security authenticates, calls UserDetailsService

3. Generate JWT Create token with claims (userId, roles, expiry), sign with secret

4. Return token Send JWT in response body

5. Subsequent requests
Client sends JWT in Authorization: Bearer <token> header

6. JWT Filter Filter intercepts, validates token, loads user, sets SecurityContext

7. Controller SecurityContext has authenticated user — request proceeds

// JWT Filter — runs before every request


@Component
public class JwtAuthFilter extends OncePerRequestFilter {
@Autowired JwtUtil jwtUtil;
@Autowired UserDetailsService userDetailsService;

@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String header = [Link]("Authorization");
if(header != null && [Link]("Bearer ")) {
String token = [Link](7);
String username = [Link](token);
if(username != null && [Link]().getAuthentication() == null) {
UserDetails userDetails = [Link](username);
if([Link](token, userDetails)) {
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(
userDetails, null, [Link]());
[Link]().setAuthentication(authToken);
}
}
}
[Link](req, res);
}
}

22 Spring AOP — Aspect-Oriented Programming

AOP separates cross-cutting concerns (logging, security, transactions) from business logic. Spring uses proxies.

Term Meaning Example

Aspect Class encapsulating cross-cutting concern LoggingAspect, SecurityAspect

Advice The actual code that runs @Before, @After, @Around

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 23

Term Meaning Example

Pointcut Expression defining where advice applies execution(* [Link].*.*(..))

JoinPoint Specific method execution being intercepted methodName(), getArgs()

Weaving Process of applying aspects to target objects Compile-time or runtime (Spring uses runtime)

@Aspect
@Component
public class LoggingAspect {

// Pointcut: all methods in service package


@Pointcut("execution(* [Link].*.*(..) )")
public void serviceLayer() {}

@Before("serviceLayer()")
public void logBefore(JoinPoint jp) {
[Link]("Calling: " + [Link]().getName());
}

@AfterReturning(pointcut="serviceLayer()", returning="result")
public void logAfter(JoinPoint jp, Object result) {
[Link]("Returned: " + result);
}

// @Around — most powerful: controls method execution


@Around("@annotation([Link])")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
long start = [Link]();
Object result = [Link](); // call actual method
long duration = [Link]() - start;
[Link]([Link]() + " took " + duration + "ms");
return result;
}
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 24

23 Caching — @Cacheable, @CacheEvict

// Enable caching in main class or config


@SpringBootApplication
@EnableCaching
public class MyApp { }

@Service
public class ProductService {

// Cache result — next call with same id returns cached value


@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
return [Link](id).orElseThrow(); // DB hit only on cache miss
}

// Evict on update — remove stale cache entry


@CacheEvict(value = "products", key = "#[Link]")
public Product update(Product product) {
return [Link](product);
}

// Evict entire cache


@CacheEvict(value = "products", allEntries = true)
public void clearAll() { }

// Update cache with new value


@CachePut(value = "products", key = "#[Link]")
public Product save(Product p) { return [Link](p); }
}

# [Link] — use Redis for distributed caching


[Link]=redis
[Link]=localhost
[Link]=6379

24 Spring Boot Testing — @SpringBootTest & MockMvc

Annotation Loads Use For

@SpringBootTest Full application context Integration tests — real components

@WebMvcTest(Controller) Only web layer (controllers, filters) Controller unit tests — no service/DB

@DataJpaTest Only JPA layer (H2 by default) Repository tests — no web layer

@MockBean Replace real bean with mock Isolate class under test

@Autowired MockMvc Mock HTTP client Test controllers without running server

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 25

// Controller test with MockMvc


@WebMvcTest([Link])
class UserControllerTest {

@Autowired MockMvc mockMvc;


@MockBean UserService userService; // mock the service

@Test
void getUser_returnsUser() throws Exception {
User user = new User(1L, "Bharath", "b@[Link]");
when([Link](1L)).thenReturn([Link](user));

[Link](get("/api/users/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Bharath"))
.andExpect(jsonPath("$.email").value("b@[Link]"));
}

@Test
void createUser_invalidEmail_returns400() throws Exception {
String body = "{\"name\":\"X\",\"email\":\"invalid\"}";
[Link](post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(body))
.andExpect(status().isBadRequest());
}
}

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 26

25 Spring Boot Actuator — Health, Metrics, Endpoints

Actuator exposes operational endpoints for monitoring and management. Add spring-boot-starter-actuator
dependency.

Endpoint HTTP Description

/actuator/health GET App health status — UP/DOWN. Shows DB, disk, custom indicators

/actuator/info GET Custom app info (version, description from [Link])

/actuator/metrics GET All available metrics (memory, CPU, HTTP requests, JVM)

/actuator/metrics/{name} GET Specific metric e.g. /metrics/[Link]

/actuator/env GET Environment properties

/actuator/beans GET All Spring beans in context

/actuator/mappings GET All @RequestMapping routes

/actuator/loggers GET/POST View/change log levels at runtime

/actuator/shutdown POST Graceful shutdown (disabled by default)

# [Link]
[Link]=health,info,metrics
[Link]-details=always
[Link]=true
[Link]=My Spring App
[Link]=1.0.0

26 Spring Boot DevTools & Configuration Tips

Feature Description How to Use

DevTools Auto-restart on code change, LiveReload Add spring-boot-devtools dependency

@ConfigurationProperties Type-safe config binding to POJO @ConfigurationProperties(prefix="app")

Externalized Config Override props via env vars or CLI SPRING_DATASOURCE_URL=... or --[Link]=...

Banner Custom startup banner Place [Link] in src/main/resources

Embedded Server Default: Tomcat. Switch to Jetty or Undertow Exclude tomcat, add jetty/undertow starter

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 27

# Config priority order (highest to lowest):


# 1. Command-line arguments: --[Link]=9090
# 2. OS environment variables: SERVER_PORT=9090
# 3. application-{profile}.properties
# 4. [Link]
# 5. Default values in code

# Commonly used starters:


# spring-boot-starter-web → REST APIs (Tomcat + Spring MVC)
# spring-boot-starter-data-jpa → JPA + Hibernate
# spring-boot-starter-security → Spring Security
# spring-boot-starter-test → JUnit 5 + Mockito + MockMvc
# spring-boot-starter-actuator → Health, Metrics
# spring-boot-starter-cache → Caching abstraction
# spring-boot-starter-validation → Bean Validation

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 28

27 Microservices with Spring Boot

Component Spring Tool Purpose

Service Discovery Eureka Server (Spring Cloud Netflix) Services register and find each other by name

API Gateway Spring Cloud Gateway Single entry point, routing, rate limiting, auth

Load Balancing Spring Cloud LoadBalancer Distribute requests across instances

Config Server Spring Cloud Config Centralized configuration for all services

Circuit Breaker Resilience4j Prevent cascade failures when services fail

Distributed Tracing Micrometer + Zipkin/Jaeger Trace requests across services

Message Queue Spring Kafka / RabbitMQ (AMQP) Async communication between services

Service Mesh Spring Cloud Gateway + filters Advanced traffic management

// RestTemplate — synchronous HTTP client (older)


RestTemplate rt = new RestTemplate();
User user = [Link]("[Link] [Link]);

// WebClient — reactive, non-blocking (modern, preferred)


WebClient client = [Link]("[Link]
User user = [Link]().uri("/users/{id}", 1L)
.retrieve()
.bodyToMono([Link])
.block();

// OpenFeign — declarative REST client (cleanest)


@FeignClient(name = "user-service")
public interface UserServiceClient {
@GetMapping("/users/{id}")
User findById(@PathVariable Long id);
}

// Circuit Breaker with Resilience4j


@CircuitBreaker(name = "userService", fallbackMethod = "fallbackUser")
public User getUser(Long id) {
return [Link](id);
}
public User fallbackUser(Long id, Exception ex) {
return new User(id, "Unknown", "N/A"); // fallback response
}

28 Spring Boot Quick Reference & Interview Q&A

Most-Asked Interview Questions


Question Answer

What is IoC? Control of object creation delegated to Spring container — developer declares needs, Spring provid

What is Dependency Injection? Pattern where dependencies are provided from outside rather than created inside the class.

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices


Spring Boot — Complete Interview Guide Page 29

Question Answer

Constructor vs Field injection? Constructor: explicit, final, testable (PREFERRED). Field: hidden deps, not final, needs Spring to te

What does @SpringBootApplication do? Combines @Configuration + @EnableAutoConfiguration + @ComponentScan. Starts auto-config a

How does auto-configuration work? Spring Boot checks classpath, applies @ConditionalOn* beans from spring-boot-autoconfigure jars

What is a Spring Bean? Any object managed by Spring IoC container. Created, configured, and destroyed by Spring.

Singleton vs Prototype scope? Singleton: one shared instance (default). Prototype: new instance every injection.

What is @Transactional? Wraps method in DB transaction. Auto-rollback on RuntimeException. Use readOnly=true for reads

@RestController vs @Controller? @Controller returns view names. @RestController = @Controller + @ResponseBody — returns JS

How to handle exceptions globally? @RestControllerAdvice class with @ExceptionHandler methods for each exception type.

What is N+1 problem? Lazy loading in a loop causes 1 query for parent + N queries for N children. Fix: JOIN FETCH.

What is Spring AOP? Separate cross-cutting concerns (logging, security) using Aspects. Spring uses runtime proxy-base

What is Spring Actuator? Provides /actuator/health, /metrics, /info endpoints for monitoring running application.

Difference between @Component, @Service, @Repository?


All register as beans. @Repository adds DB exception translation. @Service is semantic. @Compo

Spring Boot Complete Interview Guide • 28 Topics • Deep • Crisp • Interview-Ready

IoC • DI • Annotations • REST • JPA • Security • Testing • Actuator • Microservices

You might also like