Ace Your Interviews 🎯

Browse our collection of interview questions across various technologies.

Spring BootBeginner

What is Spring Boot and how is it different from the Spring Framework?

Answer

Spring Framework is a comprehensive Java framework for dependency injection, data access, and web MVC — but requires extensive XML/Java configuration. Spring Boot is built on top of Spring and provides auto-configuration (configures Spring automatically based on classpath), embedded server (Tomcat included), and opinionated defaults. You write business logic; Spring Boot handles the plumbing.

Spring BootBeginner

What is @SpringBootApplication and what annotations does it include?

Answer

@SpringBootApplication is a convenience annotation that combines three annotations: @Configuration (marks as configuration class), @EnableAutoConfiguration (enables Spring Boot's auto-configuration), and @ComponentScan (scans the current package and sub-packages for Spring components).

Spring BootBeginner

What is Dependency Injection and why is it important?

Answer

DI is a design pattern where objects receive their dependencies from an external source (Spring's IoC container) rather than creating them internally. Benefits: loose coupling (classes don't depend on concrete implementations), testability (inject mocks), and single responsibility (components focus on their logic, not dependency management).

Spring BootBeginner

What is the difference between @Component, @Service, @Repository, and @Controller?

Answer

All four are specializations of @Component — they all register the class as a Spring bean. @Service marks business logic layer. @Repository marks data access layer (also adds exception translation). @Controller marks web layer (with @ResponseBody added by @RestController). Specialization improves code readability and enables specific behavior (like @Repository's exception translation).

Spring BootBeginner

What is Spring Data JPA and what does JpaRepository provide?

Answer

Spring Data JPA is an abstraction over JPA (Hibernate) that generates repository implementations automatically. JpaRepository provides: findAll(), findById(), save(), deleteById(), count(), and existsById() — plus query derivation from method names (findByEmail(), findByStatusOrderByCreatedAtDesc()) without writing any implementation code.

Spring BootBeginner

What is the difference between @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping?

Answer

They are shortcuts for @RequestMapping(method = RequestMethod.X). @GetMapping for reading data, @PostMapping for creating, @PutMapping for full update (replace), @PatchMapping for partial update, @DeleteMapping for deletion. Using correct HTTP methods is a REST API design convention.

Spring BootBeginner

What is @RequestBody, @PathVariable, and @RequestParam?

Answer

@RequestBody binds the HTTP request body (JSON) to a Java object. @PathVariable extracts values from the URL path (/users/{id} → @PathVariable Long id). @RequestParam extracts values from the query string (/users?page=0 → @RequestParam int page).

Spring BootBeginner

What is Lombok and why is it used in Spring Boot projects?

Answer

Lombok is a Java library that generates boilerplate code at compile time via annotations. @Data generates getters, setters, equals, hashCode, toString. @Builder creates a builder pattern. @NoArgsConstructor and @AllArgsConstructor generate constructors. Reduces Java's verbosity significantly.

Spring BootBeginner

What is application.properties used for?

Answer

It's Spring Boot's externalized configuration file — store server port, database connection details, JPA settings, logging levels, and custom application properties. Different profiles (application-dev.properties, application-prod.properties) allow environment-specific overrides.

Spring BootBeginner

What is Bean Validation and how do you use it in Spring Boot?

Answer

Bean Validation (javax.validation) lets you add constraints to DTO fields: @NotNull, @NotBlank, @Email, @Min, @Max, @Size, @Pattern. Add @Valid to the @RequestBody parameter in your controller to trigger validation. Invalid input throws MethodArgumentNotValidException, caught by @RestControllerAdvice.

Spring BootIntermediate

Explain the difference between constructor injection, setter injection, and field injection. Which is preferred?

Answer

Constructor injection: dependencies passed through the constructor — preferred. Makes dependencies explicit, allows final fields (immutability), works without Spring (testable in isolation). Setter injection: via @Autowired on setters — use for optional dependencies. Field injection: @Autowired directly on fields — avoid. Hides dependencies, prevents final fields, requires Spring context for testing.

Spring BootIntermediate

What is @Transactional and what happens if it's not used?

Answer

@Transactional wraps a method in a database transaction — all operations either commit together or roll back together on exception. Without it, each repository operation auto-commits independently. A transfer method debiting one account and crediting another without @Transactional can debit successfully and then fail the credit, leaving money lost.

Spring BootIntermediate

What is the N+1 query problem and how do you solve it in Spring Data JPA?

Answer

When fetching N entities, each entity triggers an additional query to load its relationship — N+1 total queries. Example: loading 100 orders where each order separately loads its user. Solve with JOIN FETCH in JPQL: @Query('SELECT o FROM Order o JOIN FETCH o.user') — fetches orders and users in one query. Or use @EntityGraph to specify relationships to load eagerly per query.

Spring BootIntermediate

What is the difference between FetchType.LAZY and FetchType.EAGER?

Answer

LAZY: related entity is loaded only when explicitly accessed — a proxy is used initially. EAGER: related entity is loaded in the same query as the parent. LAZY is the default for @OneToMany and @ManyToMany. EAGER is default for @ManyToOne and @OneToOne. Always use LAZY and fetch explicitly with JOIN FETCH when needed to avoid performance issues.

Spring BootIntermediate

How does Spring Security work at a high level?

Answer

Spring Security adds a filter chain before your servlet. Each request passes through configured filters — the most important is the authentication filter (e.g., JwtAuthFilter). If authentication succeeds, the SecurityContext is populated with the user's details and authorities. @PreAuthorize and security rules then check authorities against the request's required permissions.

Spring BootIntermediate

What is @RestControllerAdvice and how does it differ from @ControllerAdvice?

Answer

@ControllerAdvice applies to @Controller classes and requires @ResponseBody on exception handler methods to return JSON. @RestControllerAdvice combines both — it applies to @RestController classes and automatically serializes return values as JSON. @RestControllerAdvice is the standard for REST API global exception handling.

Spring BootIntermediate

How do you implement pagination in Spring Boot?

Answer

Add Pageable parameter to the controller method and repository method. Pass a Pageable instance (PageRequest.of(page, size, Sort)) to the repository. Repository extends JpaRepository<T, ID> and the method returns Page<T>. Page contains content (the actual data), totalElements, totalPages, and current page info.

Spring BootIntermediate

What is the difference between @Query with JPQL and nativeQuery = true?

Answer

JPQL (Java Persistence Query Language) queries operate on entities and fields (database-independent). nativeQuery = true uses actual SQL (table and column names, database-specific syntax). Use JPQL for portability; native queries for complex operations JPQL can't express (window functions, CTEs, complex aggregations).

Spring BootIntermediate

What is Spring Profiles and how do you use them?

Answer

Spring Profiles allow different configurations for different environments. Create application-dev.properties, application-prod.properties. Activate with spring.profiles.active=dev (property), --spring.profiles.active=prod (command line), or SPRING_PROFILES_ACTIVE=prod (environment variable). Beans can also be profile-specific with @Profile('dev').

Spring BootIntermediate

What are DTOs (Data Transfer Objects) and why are you supposed to use them?

Answer

DTOs are plain Java objects that represent the data shape for API requests and responses, separate from JPA entities. They prevent exposing sensitive fields (passwords), avoid JSON serialization issues with JPA relationships, allow API versioning without changing the database model, and improve security by controlling exactly what data is exposed.

Spring BootAdvanced

How would you design a microservices architecture using Spring Boot and Spring Cloud?

Answer

Each business domain becomes a separate Spring Boot service. Spring Cloud Eureka handles service registration and discovery. Spring Cloud Gateway acts as the API gateway — routing, rate limiting, auth. Services communicate synchronously via REST (RestTemplate/WebClient) or asynchronously via Kafka events. Spring Cloud Sleuth adds distributed tracing. Resilience4j provides circuit breakers.

Spring BootAdvanced

What is the difference between optimistic and pessimistic locking in JPA?

Answer

Optimistic locking: assumes conflicts are rare. Uses a @Version field — on update, checks if version matches. If another transaction modified the record, throws OptimisticLockException. Good for high-read, low-conflict scenarios. Pessimistic locking: locks the database row on read (SELECT FOR UPDATE). Prevents concurrent modifications. Use for high-conflict scenarios like inventory deduction or bank balance updates.

Spring BootAdvanced

How do you implement caching in Spring Boot?

Answer

Add spring-boot-starter-cache. Add @EnableCaching to configuration. Annotate service methods: @Cacheable('products') caches the return value, @CacheEvict('products') clears cache on update/delete, @CachePut updates the cache. Configure Redis as the cache provider for distributed caching across multiple instances. Cache is hit before the method executes.

Spring BootAdvanced

What is Flyway and why is it better than ddl-auto=update in production?

Answer

Flyway is a database migration tool. You write versioned SQL scripts (V1__create_users.sql, V2__add_phone_column.sql). Flyway applies them in order, tracks which have run in a schema_version table, and never re-runs completed migrations. ddl-auto=update is unpredictable — it may add columns but won't handle renames, drops, or data migrations safely.

Spring BootAdvanced

How would you implement circuit breakers in a Spring Boot microservices system?

Answer

Use Resilience4j's @CircuitBreaker annotation. Circuit breaker has three states: CLOSED (normal, all requests pass), OPEN (too many failures — requests fail fast with fallback), HALF_OPEN (testing recovery — some requests pass). Configure failure rate threshold (e.g., 50% failure rate opens the circuit) and wait duration before trying again.

Spring BootAdvanced

How do you handle distributed transactions across microservices?

Answer

JPA @Transactional only works within a single database. Across services: use the Saga pattern. Choreography-based Saga: each service publishes domain events to Kafka, other services react and publish their own events. Compensation transactions handle rollback. Orchestration-based Saga: a central orchestrator (e.g., another Spring Boot service) coordinates the workflow.

Spring BootAdvanced

What is Spring WebFlux and when would you use it instead of Spring MVC?

Answer

Spring WebFlux is Spring's reactive web framework — non-blocking, built on Project Reactor (Mono/Flux). Use it when: you need to handle very high concurrency (100k+ connections), you're calling many external services concurrently, or you need streaming data. For typical CRUD APIs, Spring MVC is simpler and sufficient. WebFlux requires a reactive mindset throughout — reactive databases, reactive security.

Spring BootAdvanced

How do you implement multi-tenancy in a Spring Boot application?

Answer

Three strategies:

1

Database-per-tenant: each tenant has a separate database — use AbstractRoutingDataSource to switch datasource based on tenant ID.

2

Schema-per-tenant: one database, separate schemas per tenant — switch schema per request.

3

Row-level isolation: all tenants in one schema, every table has a tenant_id column — use Hibernate filters to auto-filter by tenant.

Spring BootAdvanced

What is TestContainers and how does it improve integration testing?

Answer

TestContainers is a Java library that runs real Docker containers for your tests — a real MySQL, real Redis, real Kafka. This eliminates the gap between H2 (in-memory, not 100% MySQL compatible) and production database behavior. Add @Testcontainers to your test class, declare containers with @Container, and Spring Boot auto-connects to them.

Spring BootAdvanced

How do you profile and optimize a slow Spring Boot application?

Answer

Start with Spring Boot Actuator metrics — identify slow endpoints. Enable Hibernate SQL logging to find N+1 queries (spring.jpa.show-sql=true in dev). Use JProfiler or async-profiler for CPU profiling. Common fixes: add database indexes for query columns, fix N+1 with JOIN FETCH, add @Cacheable for expensive repeated queries, use connection pool tuning (HikariCP), add pagination to unbounded list queries.

Ready for a real challenge?

Master Spring Boot