InterviewTreedInterviewTreed

InterviewTreed Question Bank

Java & Spring Boot Interview Questions and Answers

Prepare for Java and Spring Boot interviews, covering core Java, object-oriented programming, collections, concurrency, JVM internals, Spring Framework, Spring Boot, REST APIs, Hibernate, security, and microservices.

Total Questions

125

Beginner

27

Intermediate

52

Advanced

46

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Fundamentals

What is Spring Boot?

Spring Boot streamlines Spring application setup with auto-configuration, starter dependencies, and executable packaging

Answer

Spring Boot streamlines Spring application setup with auto-configuration, starter dependencies, and executable packaging. It builds on Spring Framework rather than replacing it.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@SpringBootApplication
class App { public static void main(String[] a) { SpringApplication.run(App.class, a); } }

Key Points

  • Reduces setup boilerplate
  • Defaults remain customizable
Q2Fundamentals

Spring Framework vs Spring Boot

Spring Framework provides core features such as dependency injection and MVC

Answer

Spring Framework provides core features such as dependency injection and MVC. Spring Boot adds conventions, starters, auto-configuration, and packaging to simplify application creation and operation.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Spring Framework + explicit setup → Spring Boot conventions + auto-configuration

Key Points

  • Boot builds on Spring
  • Boot does not remove the underlying framework
Q3Fundamentals

What does @SpringBootApplication combine?

It combines @Configuration, @EnableAutoConfiguration, and @ComponentScan to configure beans, apply conditional defaults, and discover components

Answer

It combines @Configuration, @EnableAutoConfiguration, and @ComponentScan to configure beans, apply conditional defaults, and discover components.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@SpringBootApplication
// Configuration + EnableAutoConfiguration + ComponentScan

Key Points

  • Keep the main class in a root package
  • Check component scan boundaries
Q4Fundamentals

How do you start a Spring Boot application?

The main method calls SpringApplication.run, which creates the application context, loads configuration, creates beans, and starts configured infrastructure such as the web server

Answer

The main method calls SpringApplication.run, which creates the application context, loads configuration, creates beans, and starts configured infrastructure such as the web server.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

public static void main(String[] args) {
  SpringApplication.run(App.class, args);
}

Key Points

  • Startup failures often indicate bean or configuration issues
  • Use logs to diagnose context creation
Q5Core Spring

What is dependency injection?

Dependency injection supplies an object's collaborators from outside rather than having the object construct them

Answer

Dependency injection supplies an object's collaborators from outside rather than having the object construct them. Spring's container wires managed beans, reducing coupling and simplifying tests.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Service
class OrderService {
  private final OrderRepository repo;
  OrderService(OrderRepository repo) { this.repo = repo; }
}

Key Points

  • Prefer constructor injection
  • Dependencies are explicit
Q6Core Spring

What is the IoC container?

The Inversion of Control container creates and manages Spring beans, resolves their dependencies, applies lifecycle callbacks, and can add proxy-based services such as transactions

Answer

The Inversion of Control container creates and manages Spring beans, resolves their dependencies, applies lifecycle callbacks, and can add proxy-based services such as transactions.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Configuration → ApplicationContext → create beans → wire dependencies

Key Points

  • ApplicationContext is commonly used
  • Bean scope affects instance lifecycle
Q7Core Spring

@Component vs @Service vs @Repository

These annotations register classes as components

Answer

These annotations register classes as components. @Component is generic, @Service marks business-layer intent, and @Repository marks persistence-layer intent and supports exception translation in relevant cases.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Component class Mapper {}
@Service class BillingService {}
@Repository class BillingRepository {}

Key Points

  • They communicate architectural roles
  • They do not automatically add transactions
Q8Core Spring

What is a Spring bean?

A bean is an object managed by the Spring container

Answer

A bean is an object managed by the Spring container. Beans can be discovered with component scanning or declared through @Bean methods in configuration classes.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Configuration class Config {
  @Bean Clock clock() { return Clock.systemUTC(); }
}

Key Points

  • Use beans for application-managed collaborators
  • Avoid unnecessary global mutable state
Q9Core Spring

What are common bean scopes?

Singleton is the default scope: one instance per bean definition per container

Answer

Singleton is the default scope: one instance per bean definition per container. Prototype creates a new instance when requested; web scopes can bind instances to requests or sessions.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Key Points

  • Singleton does not mean one per JVM
  • Avoid request-specific mutable fields in singleton beans
Q10Core Spring

Why prefer constructor injection?

Constructor injection makes required dependencies visible, enables final fields, and lets tests instantiate a class without starting Spring

Answer

Constructor injection makes required dependencies visible, enables final fields, and lets tests instantiate a class without starting Spring. It also exposes overly complex constructors as a design signal.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

OrderService(OrderRepository repo, PaymentGateway gateway) { ... }

Key Points

  • Use optional dependencies only when truly optional
  • Avoid field injection for required collaborators
Q11Setup and configuration

What are Spring Boot starters?

Starters group compatible dependencies for a capability, such as web development or JPA persistence

Answer

Starters group compatible dependencies for a capability, such as web development or JPA persistence. Boot dependency management helps align versions and reduce manual dependency selection.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

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

Key Points

  • Inspect dependency trees for conflicts
  • Choose only needed starters
Q12Setup and configuration

What is auto-configuration?

Auto-configuration conditionally configures common components based on the classpath, properties, and existing beans

Answer

Auto-configuration conditionally configures common components based on the classpath, properties, and existing beans. It usually backs off when application-defined beans satisfy the relevant conditions.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Classpath + properties + existing beans → conditional configuration

Key Points

  • Defaults can be overridden
  • Use debug condition reports when diagnosing
Q13Setup and configuration

What is an embedded server?

An embedded server lets an executable Spring Boot application start its web server itself, commonly allowing deployment as a JAR instead of deploying a WAR to a separately managed servlet container

Answer

An embedded server lets an executable Spring Boot application start its web server itself, commonly allowing deployment as a JAR instead of deploying a WAR to a separately managed servlet container.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

java -jar app.jar --server.port=8081

Key Points

  • Tomcat is common with the servlet web starter
  • Production still needs operational controls
Q14Setup and configuration

application.properties vs application.yml

Both formats externalize configuration

Answer

Both formats externalize configuration. Properties use flat key-value entries; YAML expresses hierarchy with indentation. Choose one consistently and validate exact property names for the Boot version.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

server.port=8081
# YAML equivalent:
# server:
#   port: 8081

Key Points

  • YAML indentation matters
  • Do not commit secrets
Q15Setup and configuration

What are Spring profiles?

Profiles select environment-specific beans or configuration, such as local, test, and production

Answer

Profiles select environment-specific beans or configuration, such as local, test, and production. Activate profiles through supported configuration, environment variables, or command-line options.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

application.yml; application-dev.yml; application-prod.yml

Key Points

  • Keep environment differences explicit
  • Profiles alone do not secure secrets
Q16Setup and configuration

How does @ConfigurationProperties work?

It binds a group of external configuration values into a typed Java object, making configuration easier to validate, document, and test than scattered string expressions

Answer

It binds a group of external configuration values into a typed Java object, making configuration easier to validate, document, and test than scattered string expressions.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@ConfigurationProperties(prefix="checkout")
public record CheckoutProperties(int maxItems) {}

Key Points

  • Use a clear prefix
  • Add validation for required settings
Q17Setup and configuration

What does @Value do?

@Value injects a property or expression into a bean

Answer

@Value injects a property or expression into a bean. It is useful for a small number of settings, while @ConfigurationProperties is often better for related configuration groups.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Value("${app.page-size:20}") private int pageSize;

Key Points

  • Defaults can be specified
  • Avoid scattering many settings across classes
Q18REST APIs

What is @RestController?

@RestController combines controller registration with response-body behavior, so handler return values are serialized to the HTTP response, commonly as JSON

Answer

@RestController combines controller registration with response-body behavior, so handler return values are serialized to the HTTP response, commonly as JSON.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@RestController
@RequestMapping("/api/hello")
class HelloController {
 @GetMapping String hello() { return "Hello"; }
}

Key Points

  • Use DTOs for public API responses
  • Choose appropriate status codes
Q19REST APIs

@RequestMapping vs @GetMapping

@RequestMapping can define paths and HTTP constraints generally

Answer

@RequestMapping can define paths and HTTP constraints generally. Shortcut annotations such as @GetMapping and @PostMapping express common HTTP methods more clearly.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@RequestMapping("/api/products")
@GetMapping("/{id}") ProductDto get(@PathVariable long id) { ... }

Key Points

  • Use class mappings for shared prefixes
  • Avoid ambiguous route patterns
Q20REST APIs

@PathVariable vs @RequestParam

@PathVariable binds a value in the URL path, commonly a resource identifier

Answer

@PathVariable binds a value in the URL path, commonly a resource identifier. @RequestParam binds a query parameter, often used for filters, sorting, and pagination.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@GetMapping("/products/{id}")
ProductDto get(@PathVariable long id) { ... }
@GetMapping("/products")
List<ProductDto> list(@RequestParam int page) { ... }

Key Points

  • Path identifies a resource
  • Query parameters commonly refine a collection
Q21REST APIs

What does @RequestBody do?

@RequestBody deserializes the HTTP request body into a Java object using an HTTP message converter

Answer

@RequestBody deserializes the HTTP request body into a Java object using an HTTP message converter. JSON is commonly handled by Jackson in a standard web setup.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

record CreateProductRequest(String name, BigDecimal price) {}
@PostMapping("/products")
ProductDto create(@Valid @RequestBody CreateProductRequest req) { ... }

Key Points

  • Validate input DTOs
  • Malformed JSON is a client error
Q22REST APIs

Why use DTOs?

DTOs define the data exchanged across an API boundary

Answer

DTOs define the data exchanged across an API boundary. They decouple the public contract from database entities, prevent accidental field exposure, and allow request-specific validation.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

record UserResponse(Long id, String displayName) {}

Key Points

  • Separate request and response models where useful
  • Do not expose sensitive entity fields
Q23REST APIs

Which HTTP status codes matter in REST?

200 means success, 201 commonly means created, 204 means success with no body, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, and 500 unexpected server error

Answer

200 means success, 201 commonly means created, 204 means success with no body, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, and 500 unexpected server error.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

GET /products/3 → 200
POST /products → 201
DELETE /products/3 → 204

Key Points

  • Status codes are part of the contract
  • Do not expose stack traces
Q24Validation and errors

How do you validate request data?

Bean Validation constraints can be placed on DTO fields and triggered with @Valid at the controller boundary

Answer

Bean Validation constraints can be placed on DTO fields and triggered with @Valid at the controller boundary. Convert validation failures into a stable client-facing error response.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

record UserRequest(@NotBlank String name, @Email String email) {}

Key Points

  • Validation is not authorization
  • Return useful field errors without leaking sensitive values
Q25Setup and configuration

What is the difference between Maven and Gradle?

Maven uses a convention-oriented XML build model; Gradle uses a programmable Groovy or Kotlin DSL

Answer

Maven uses a convention-oriented XML build model; Gradle uses a programmable Groovy or Kotlin DSL. Both compile, test, and package Spring Boot projects.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

./mvnw clean test
./gradlew clean test

Key Points

  • Use the project wrapper in CI
  • Keep dependency versions consistent
Q26Setup and configuration

What is Spring Boot DevTools?

DevTools improves local feedback through features such as automatic restart after classpath changes and optional LiveReload

Answer

DevTools improves local feedback through features such as automatic restart after classpath changes and optional LiveReload. It is intended for development rather than production.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

spring-boot-devtools (optional development dependency)

Key Points

  • Keep it out of production runtime
  • It does not replace tests
Q109Language Basics

What is the difference between == and equals()?

What is the difference between == and equals()?

Answer

For primitives, == compares values. For object references, == compares identity, while equals() compares logical equality when the class implements it appropriately.

Syntax

a == b; a.equals(b)

Example

Compare String values with equals rather than reference identity.

Code example

String a = new String("java");
String b = new String("java");
boolean sameValue = a.equals(b); // true

Diagram

references -> == identity
references -> equals() logical comparison

Key Points

  • Use Objects.equals(a, b) when either reference may be null.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q27Architecture

Explain controller-service-repository layers.

The controller handles HTTP concerns, the service coordinates business rules and transactions, and the repository handles persistence

Answer

The controller handles HTTP concerns, the service coordinates business rules and transactions, and the repository handles persistence. This separation supports reuse and focused testing.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

HTTP → Controller → Service → Repository → Database
HTTP ← Controller ← Service ← Repository result

Key Points

  • Keep controllers thin
  • Put use-case logic in services
Q28Persistence

What is Spring Data JPA?

Spring Data JPA generates repository implementations from interfaces and supports derived queries, JPQL, paging, and sorting

Answer

Spring Data JPA generates repository implementations from interfaces and supports derived queries, JPQL, paging, and sorting. JPA is the specification; Hibernate is a common provider.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

interface ProductRepository extends JpaRepository<Product, Long> {
 List<Product> findByCategory(String category);
}

Key Points

  • Understand JPA and provider differences
  • Test query performance
Q29Persistence

How do you define a JPA entity?

An entity maps a Java class to persistent data and declares an identifier and mapping metadata

Answer

An entity maps a Java class to persistent data and declares an identifier and mapping metadata. Choose access strategy and relationship loading deliberately.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Entity @Table(name="products")
class Product {
 @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;
 @Column(nullable=false) private String name;
}

Key Points

  • Model relationships carefully
  • Use DTOs at API boundaries
Q30Persistence

How do derived query methods work?

Spring Data parses supported repository method names into queries based on entity properties

Answer

Spring Data parses supported repository method names into queries based on entity properties. Complex conditions may be clearer with @Query or specifications.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

List<Product> findByCategoryAndActiveTrueOrderByNameAsc(String category);

Key Points

  • Property names must match the model
  • Use paging for large results
Q31Persistence

JPQL vs native SQL

JPQL queries entity names and mapped properties; native SQL queries database tables and columns

Answer

JPQL queries entity names and mapped properties; native SQL queries database tables and columns. JPQL is generally more portable, while native SQL can use database-specific features.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Query("select p from Product p where p.category = :category")
List<Product> findCategory(@Param("category") String category);

Key Points

  • JPQL is entity-oriented
  • Test native queries against the production database
Q32Transactions

How does @Transactional work?

Spring transaction infrastructure surrounds eligible method calls and commits or rolls back according to transaction-manager rules

Answer

Spring transaction infrastructure surrounds eligible method calls and commits or rolls back according to transaction-manager rules. By default, unchecked exceptions typically trigger rollback, while checked exceptions usually do not.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Transactional
public void transfer(long from, long to, BigDecimal amount) { ... }

Key Points

  • Proxy boundaries matter
  • Keep transactions short
  • Know rollback rules
Q33Transactions

Explain transaction propagation.

REQUIRED joins or creates a transaction; REQUIRES_NEW suspends an existing transaction and starts a separate one

Answer

REQUIRED joins or creates a transaction; REQUIRES_NEW suspends an existing transaction and starts a separate one. Other modes define whether a method joins or requires transactional context.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Transactional(propagation = Propagation.REQUIRES_NEW)
void writeAudit(AuditEvent event) { ... }

Key Points

  • Choose based on consistency needs
  • REQUIRES_NEW may need another connection
Q34Persistence

What is the N+1 query problem?

N+1 occurs when loading a list of parent rows triggers extra queries for each related entity

Answer

N+1 occurs when loading a list of parent rows triggers extra queries for each related entity. Use fetch joins, entity graphs, batch fetching, or DTO projections after confirming the query pattern.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Query("select o from Order o join fetch o.customer where o.id=:id")
Optional<Order> findWithCustomer(@Param("id") Long id);

Key Points

  • Inspect SQL and metrics
  • Avoid globally eager-loading everything
  • Take care with pagination and collection fetch joins
Q35Persistence

Lazy vs eager loading

Lazy loading defers relationship fetching until access; eager loading requests related data as part of entity loading

Answer

Lazy loading defers relationship fetching until access; eager loading requests related data as part of entity loading. Actual SQL depends on the provider and query fetch plan.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@ManyToOne(fetch = FetchType.LAZY)
private Customer customer;

Key Points

  • Lazy access may fail outside persistence context
  • Eager loading can over-fetch
  • Use explicit fetch plans
Q36Persistence

How do pagination and sorting work?

Spring Data accepts Pageable and can return Page or Slice

Answer

Spring Data accepts Pageable and can return Page or Slice. Page typically includes total-count metadata; Slice can avoid a count query when only checking for more results is needed.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Pageable p = PageRequest.of(0, 20, Sort.by("name").ascending());
Page<Product> products = repository.findAll(p);

Key Points

  • Cap page size
  • Use stable sorting
  • Consider keyset pagination at scale
Q37Validation and errors

How do you implement global exception handling?

@RestControllerAdvice centralizes exception mapping

Answer

@RestControllerAdvice centralizes exception mapping. Handle expected domain and validation failures explicitly and return a consistent error contract without leaking internal details.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@RestControllerAdvice
class ApiErrors {
 @ExceptionHandler(ProductNotFoundException.class)
 ResponseEntity<Map<String,String>> missing() {
  return ResponseEntity.status(404).body(Map.of("error","NOT_FOUND"));
 }
}

Key Points

  • Map expected errors to 4xx
  • Log unexpected failures with correlation IDs
Q38Validation and errors

What is ProblemDetail?

ProblemDetail represents structured HTTP errors using fields such as status, title, detail, and instance

Answer

ProblemDetail represents structured HTTP errors using fields such as status, title, detail, and instance. Availability depends on the Spring Framework version in use.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "Product not found");
p.setTitle("Not found");

Key Points

  • Check framework version
  • Keep errors consistent
  • Never expose stack traces
Q39Observability

How should SLF4J logging be used?

Use a logging facade with meaningful contextual messages, appropriate severity, and parameterized values

Answer

Use a logging facade with meaningful contextual messages, appropriate severity, and parameterized values. Include trace identifiers when available and avoid logging credentials or sensitive payloads.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

private static final Logger log = LoggerFactory.getLogger(OrderService.class);
log.info("Creating order customerId={}", customerId);

Key Points

  • Prefer parameterized logs
  • Choose DEBUG/INFO/WARN/ERROR intentionally
Q40Observability

What is Spring Boot Actuator?

Actuator provides operational endpoints for health, metrics, and other management data

Answer

Actuator provides operational endpoints for health, metrics, and other management data. Expose only necessary endpoints and secure management interfaces.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

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

Key Points

  • Health endpoints support probes
  • Metrics can be exported via Micrometer
  • Do not expose all endpoints publicly
Q41Observability

How do health indicators work?

Health indicators report component status and are aggregated into health endpoints

Answer

Health indicators report component status and are aggregated into health endpoints. Separate liveness (process can progress) from readiness (instance should receive traffic).

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Component
class CatalogHealth implements HealthIndicator {
 public Health health() { return Health.up().withDetail("catalog","ok").build(); }
}

Key Points

  • Avoid dependency-based liveness loops
  • Set readiness according to serving ability
Q42Core Spring

What are conditional beans?

Conditional configuration activates when classpath, property, or bean conditions match

Answer

Conditional configuration activates when classpath, property, or bean conditions match. This enables optional integrations and allows application beans to override defaults.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Bean
@ConditionalOnProperty(name="payments.enabled", havingValue="true")
PaymentGateway gateway() { ... }

Key Points

  • Use @ConditionalOnMissingBean for overridable defaults
  • Debug condition reports
Q43Core Spring

Describe bean lifecycle callbacks.

Spring creates a bean, injects dependencies, applies post-processors, invokes initialization callbacks, and eventually runs destruction callbacks for managed beans when the context closes

Answer

Spring creates a bean, injects dependencies, applies post-processors, invokes initialization callbacks, and eventually runs destruction callbacks for managed beans when the context closes.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@PostConstruct void init() { ... }
@PreDestroy void close() { ... }

Key Points

  • Avoid expensive blocking startup work
  • Close resources reliably
Q44Core Spring

What is Spring AOP?

Spring AOP separates cross-cutting behavior such as transactions and method interception from business logic

Answer

Spring AOP separates cross-cutting behavior such as transactions and method interception from business logic. Proxies commonly intercept calls to managed beans.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Caller → proxy/advice → target bean

Key Points

  • Self-invocation may bypass proxy advice
  • Keep aspect behavior understandable
Q45REST APIs

Filter vs HandlerInterceptor

A servlet Filter runs at the servlet layer before MVC dispatch; a HandlerInterceptor participates in Spring MVC handler execution and can access handler metadata

Answer

A servlet Filter runs at the servlet layer before MVC dispatch; a HandlerInterceptor participates in Spring MVC handler execution and can access handler metadata.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

HTTP → Filter chain → DispatcherServlet → Interceptor → Controller

Key Points

  • Filters are lower-level
  • Spring Security uses a filter chain
Q46Security

What is CORS?

CORS is a browser-enforced policy in which the server states which cross-origin requests are allowed

Answer

CORS is a browser-enforced policy in which the server states which cross-origin requests are allowed. It is not authentication or authorization.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@CrossOrigin(origins="https://app.example.com")

Key Points

  • Allow only required origins and methods
  • Credentials require careful configuration
Q47Security

How does Spring Security protect APIs?

Spring Security uses a filter chain to authenticate requests and authorize access to routes or methods

Answer

Spring Security uses a filter chain to authenticate requests and authorize access to routes or methods. Explicit rules and tests should cover both permitted and denied paths.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

http.authorizeHttpRequests(a -> a
 .requestMatchers("/actuator/health").permitAll()
 .anyRequest().authenticated());

Key Points

  • Do not rely blindly on defaults
  • Use least privilege
Q48Security

How does a JWT resource server work?

A resource server validates bearer tokens and maps validated claims to an authenticated principal and authorities

Answer

A resource server validates bearer tokens and maps validated claims to an authenticated principal and authorities. Validation should include signature and issuer, expiry, and audience requirements as appropriate.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://id.example.com/issuer

Key Points

  • A decoded JWT is not necessarily valid
  • Use trusted issuers and algorithms
Q49Security

What is method security?

Method security applies authorization policies to service or method calls, complementing URL-based rules

Answer

Method security applies authorization policies to service or method calls, complementing URL-based rules. Enable it and use annotations such as @PreAuthorize.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@EnableMethodSecurity
@PreAuthorize("hasRole('ADMIN')")
void deleteProduct(long id) { ... }

Key Points

  • Test different roles
  • Proxy boundaries matter
Q50Testing

How do you unit-test a service?

Unit tests construct a service with controlled collaborators and test observable behavior without loading the full application context

Answer

Unit tests construct a service with controlled collaborators and test observable behavior without loading the full application context. Mockito is useful when interaction with collaborators matters.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
 @Mock OrderRepository repo;
 @InjectMocks OrderService service;
}

Key Points

  • Cover edge and failure paths
  • Avoid testing private implementation details
Q51Testing

What is @SpringBootTest?

@SpringBootTest loads the application context for integration-style tests of configuration and bean wiring

Answer

@SpringBootTest loads the application context for integration-style tests of configuration and bean wiring. It is more comprehensive and usually slower than a unit test or test slice.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@SpringBootTest
class AppIntegrationTest { @Test void contextLoads() {} }

Key Points

  • Use test slices when sufficient
  • Control external dependencies
Q52Testing

What does @WebMvcTest test?

@WebMvcTest loads a focused MVC slice for controller routing, serialization, validation, and status codes

Answer

@WebMvcTest loads a focused MVC slice for controller routing, serialization, validation, and status codes. Collaborators are usually mocked rather than loading the full application.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@WebMvcTest(ProductController.class)
class ProductControllerTest { @Autowired MockMvc mvc; }

Key Points

  • Use MockMvc for requests
  • Not a full database integration test
Q53Testing

What is @DataJpaTest?

@DataJpaTest focuses on entity and repository behavior and commonly rolls back test transactions

Answer

@DataJpaTest focuses on entity and repository behavior and commonly rolls back test transactions. An embedded database may differ from the production engine.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@DataJpaTest
class ProductRepositoryTest { @Autowired ProductRepository repo; }

Key Points

  • Test important query mappings
  • Use production-like database integration tests
Q54Testing

Why use Testcontainers?

Testcontainers runs disposable services such as PostgreSQL or Kafka for tests, providing more realistic integration behavior than many in-memory substitutes

Answer

Testcontainers runs disposable services such as PostgreSQL or Kafka for tests, providing more realistic integration behavior than many in-memory substitutes.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Container static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");

Key Points

  • Pin image versions
  • Keep test data isolated
Q55REST APIs

RestClient vs WebClient

RestClient is a synchronous fluent HTTP client; WebClient supports reactive non-blocking I/O and streaming

Answer

RestClient is a synchronous fluent HTTP client; WebClient supports reactive non-blocking I/O and streaming. Choose based on framework version and execution model.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

RestClient.create("https://api.example.com").get().uri("/items").retrieve().body(String.class);

Key Points

  • Set timeouts
  • Handle errors deliberately
  • Avoid blocking reactive event loops
Q56Performance

How does caching work in Spring?

Spring's cache abstraction uses a CacheManager and annotations to cache method results or evict entries

Answer

Spring's cache abstraction uses a CacheManager and annotations to cache method results or evict entries. Correct keys, expiry, and invalidation are essential to avoid stale data.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@EnableCaching
@Cacheable(cacheNames="products", key="#id")
ProductDto getProduct(long id) { ... }

Key Points

  • Cache only acceptable-to-stale data
  • Understand local vs distributed caches
Q57Concurrency

How does @Async work?

@Async runs eligible method calls on a configured executor

Answer

@Async runs eligible method calls on a configured executor. It is proxy-based in common setups, so self-invocation and executor saturation affect behavior.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Async("applicationExecutor")
CompletableFuture<Void> sendMail() { ... }

Key Points

  • Use bounded executors
  • Do not assume transactions cross threads
Q58Concurrency

How do you schedule a task?

@Scheduled supports fixed delay, fixed rate, and cron scheduling

Answer

@Scheduled supports fixed delay, fixed rate, and cron scheduling. In multi-instance deployments, each instance may run the job unless coordination is added.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@EnableScheduling
@Scheduled(cron="0 0/5 * * * *")
void refresh() { ... }

Key Points

  • Choose timezone intentionally
  • Use a distributed lock if only one run is allowed
Q59Core Spring

How do Spring application events work?

An event publisher notifies listeners through the application context

Answer

An event publisher notifies listeners through the application context. Synchronous listeners normally run on the publishing thread; in-process events are not a durable message broker.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

publisher.publishEvent(new OrderCreated(orderId));
@EventListener void on(OrderCreated e) { ... }

Key Points

  • Consider transaction timing
  • Use messaging for durable cross-service events
Q60Persistence

How should schema migrations be managed?

Flyway or Liquibase versions schema changes so deployments apply them consistently

Answer

Flyway or Liquibase versions schema changes so deployments apply them consistently. Treat migration scripts as code and maintain compatibility during rolling deployments.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

db/migration/V1__create_products.sql
V2__add_status.sql

Key Points

  • Prefer expand-and-contract changes
  • Test on a representative database
Q61Persistence

What is optimistic locking?

Optimistic locking uses a version field to detect conflicting updates and prevent silent overwrites

Answer

Optimistic locking uses a version field to detect conflicting updates and prevent silent overwrites. The application should handle conflict failures appropriately.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@Version
private long version;

Key Points

  • Good for lower contention
  • Not a substitute for business concurrency rules
Q62REST APIs

How would you version a REST API?

Versioning protects clients from breaking contract changes

Answer

Versioning protects clients from breaking contract changes. Path, header, and media-type strategies are possible; choose one policy and communicate deprecation clearly.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

/api/v1/products

Key Points

  • Prefer additive changes
  • Test old and new contracts during migration
Q63REST APIs

How do you make a payment endpoint idempotent?

Persist an idempotency key and request fingerprint with the result so retries return the original outcome instead of repeating a payment

Answer

Persist an idempotency key and request fingerprint with the result so retries return the original outcome instead of repeating a payment. A uniqueness constraint handles concurrent duplicate requests.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

POST /payments
Idempotency-Key: <unique-key>

Key Points

  • Validate key reuse with different payloads
  • Define retention and recovery
Q101Streams API

How do map and flatMap differ in Java streams?

How do map and flatMap differ in Java streams?

Answer

map transforms each input element into one output element, while flatMap transforms each input into a stream or container and flattens the results into one stream.

Syntax

stream.map(x -> transform(x)); stream.flatMap(x -> x.getItems().stream())

Example

Transform a list of users into names, or flatten each post's tags.

Code example

List<String> names = users.stream().map(User::getName).toList();
List<String> tags = posts.stream().flatMap(p -> p.getTags().stream()).toList();

Diagram

users -> map(User::getName) -> names
posts -> flatMap(tags) -> flattened tags

Key Points

  • Use map for one-to-one conversion
  • use flatMap to flatten nested collections.
Q102Streams API

What is the difference between intermediate and terminal stream operations?

What is the difference between intermediate and terminal stream operations?

Answer

Intermediate operations return another stream and are generally lazy. Terminal operations produce a result or side effect and trigger pipeline evaluation.

Syntax

stream.filter(...).map(...).collect(...)

Example

Transform a list of users into names, or flatten each post's tags.

Code example

long activeCount = users.stream().filter(User::isActive).count();

Diagram

source -> intermediate operations -> terminal operation -> execution

Key Points

  • Examples of intermediate operations include filter, map, and sorted
  • terminal operations include collect, reduce, count, and forEach.
Q103Streams API

Why should side effects be avoided in stream pipelines?

Why should side effects be avoided in stream pipelines?

Answer

Side effects make pipelines harder to reason about and can become unsafe with parallel execution. Prefer transformations and terminal reductions over mutating shared state.

Syntax

items.stream().map(this::transform).toList()

Example

Transform a list of users into names, or flatten each post's tags.

Code example

List<String> normalized = inputs.stream().map(String::trim).map(String::toLowerCase).toList();

Diagram

input -> pure transformations -> result

Key Points

  • Use collectors or reductions instead of updating a shared ArrayList inside forEach.
Q107Collections

How does HashMap handle hash collisions?

How does HashMap handle hash collisions?

Answer

HashMap uses the hash to select a bucket and then compares keys within that bucket using equality. Modern implementations can treeify heavily populated buckets under suitable conditions.

Syntax

map.put(key, value); map.get(key)

Example

Use a map to count values or remove entries through the iterator.

Code example

Map<String, Integer> counts = new HashMap<>();
counts.merge("java", 1, Integer::sum);

Diagram

key -> hash -> bucket -> equals comparison -> value

Key Points

  • Consistent equals and hashCode implementations are essential for reliable key lookup.
Q108Collections

What are fail-fast iterators?

What are fail-fast iterators?

Answer

Fail-fast iterators may throw ConcurrentModificationException when they detect structural modification outside the iterator's supported mutation methods. This is a best-effort bug-detection mechanism, not a synchronization guarantee.

Syntax

Iterator<T> it = list.iterator(); while (it.hasNext()) { ... }

Example

Use a map to count values or remove entries through the iterator.

Code example

Iterator<String> it = names.iterator();
while (it.hasNext()) { if (it.next().isBlank()) it.remove(); }

Diagram

collection -> iterator -> detect unexpected structural change -> exception

Key Points

  • Use Iterator.remove for supported in-loop removal, or choose a concurrent collection when needed.
Q110Object-Oriented Programming

What is the contract between equals() and hashCode()?

What is the contract between equals() and hashCode()?

Answer

If two objects are equal according to equals(), they must return the same hash code. Unequal objects may share a hash code. Both methods should remain consistent while equality-relevant state is unchanged.

Syntax

equals(Object other); hashCode()

Example

Use a record for value objects whose components define equality.

Code example

record Point(int x, int y) {} // generated value equality and hashCode

Diagram

equal objects -> equal hash codes -> correct hash-based lookup

Key Points

  • Override both together when defining value equality, especially for hash-based collections.
Q111Spring Boot

What does @ConfigurationProperties do?

What does @ConfigurationProperties do?

Answer

It binds external configuration values with a common prefix to a typed Java object, supporting structured configuration and validation.

Syntax

@ConfigurationProperties(prefix = "app.mail")

Example

Bind deployment-specific settings through configuration rather than hardcoding them.

Code example

@ConfigurationProperties(prefix = "app.mail")
@Validated
public record MailProperties(@NotBlank String host, int port) {}

Diagram

application.yml -> property binder -> typed configuration bean

Key Points

  • Prefer typed properties over scattered string lookups for grouped configuration.
Q112Spring Boot

How do profiles work in Spring Boot?

How do profiles work in Spring Boot?

Answer

Profiles allow environment-specific beans and configuration to be activated, for example development, test, and production settings.

Syntax

spring.profiles.active=dev; @Profile("dev")

Example

Bind deployment-specific settings through configuration rather than hardcoding them.

Code example

@Configuration
@Profile("dev")
class DevConfig { }

Diagram

base config + active profile -> effective environment configuration

Key Points

  • Keep secrets outside source control and avoid relying on a developer profile in production.
Q114REST APIs

What is the difference between PUT and PATCH?

What is the difference between PUT and PATCH?

Answer

PUT generally replaces the target resource representation, while PATCH applies a partial modification. Exact semantics depend on the API contract.

Syntax

@PutMapping("/{id}"); @PatchMapping("/{id}")

Example

Validate request DTOs and return a consistent error body.

Code example

@PatchMapping("/{id}")
ResponseEntity<ItemDto> patch(@PathVariable long id, @RequestBody ItemPatch patch) { ... }

Diagram

client update -> validation -> domain change -> response

Key Points

  • Document null, omitted-field, validation, and idempotency semantics for updates.
Q115REST APIs

How should validation errors be returned from a REST API?

How should validation errors be returned from a REST API?

Answer

Return a consistent client-error status and structured body that identifies invalid fields without leaking internal details. In Spring, Bean Validation and a controller advice can centralize this.

Syntax

@Valid @RequestBody CreateUserRequest request

Example

Validate request DTOs and return a consistent error body.

Code example

public record CreateUserRequest(@NotBlank String name, @Email String email) {}

Diagram

request -> validation -> field errors -> structured 400 response

Key Points

  • Use @NotBlank, @Email, and size constraints
  • map exceptions through @RestControllerAdvice.
Q116Hibernate & JPA

What is the N+1 query problem?

What is the N+1 query problem?

Answer

The N+1 problem occurs when one query loads a set of parent entities and additional queries load related data separately for each parent.

Syntax

@EntityGraph(attributePaths = "items")

Example

Inspect SQL and transaction boundaries when tuning persistence behavior.

Code example

@EntityGraph(attributePaths = "items")
List<Order> findByStatus(Status status);

Diagram

1 query for parents + N queries for relations -> optimize fetch strategy

Key Points

  • Inspect SQL logs and query counts
  • consider fetch joins, entity graphs, or batch fetching based on the use case.
Q118Hibernate & JPA

Why should database transactions have clear boundaries?

Why should database transactions have clear boundaries?

Answer

A transaction boundary groups related database operations into a unit of work with defined commit and rollback behavior. In Spring, @Transactional is commonly applied at service-layer methods.

Syntax

@Transactional

Example

Inspect SQL and transaction boundaries when tuning persistence behavior.

Code example

@Service
class OrderService {
  @Transactional
  public void placeOrder(OrderRequest request) { /* persist order and items */ }
}

Diagram

service method -> begin transaction -> database operations -> commit/rollback

Key Points

  • Avoid long-running transactions and understand proxy-based transaction behavior and propagation.
Q119Modern Java

What are records in Java?

What are records in Java?

Answer

Records are concise data-carrier classes that automatically provide component accessors, equals, hashCode, and toString. They are shallowly immutable, not deeply immutable.

Syntax

record UserDto(long id, String name) {}

Example

Use a record for a response DTO.

Code example

public record UserDto(long id, String name) {}

Diagram

record declaration -> canonical constructor + accessors + value methods

Key Points

  • Use records for DTOs and value-like data
  • mutable objects held in components can still change.
Q120Modern Java

What is Optional intended for?

What is Optional intended for?

Answer

Optional represents a value that may be absent, most commonly as a return type. It encourages callers to handle absence explicitly.

Syntax

Optional<User> findById(long id)

Example

Use a record for a response DTO.

Code example

String display = repository.findById(id).map(User::getName).orElse("Unknown");

Diagram

possible absence -> Optional -> map/fallback/exception

Key Points

  • Avoid blindly calling get()
  • use map, flatMap, orElseGet, or orElseThrow as appropriate.
Q124Collections

When would you choose ConcurrentHashMap?

When would you choose ConcurrentHashMap?

Answer

ConcurrentHashMap supports concurrent retrievals and updates without requiring callers to synchronize the entire map. It does not make compound multi-step application logic automatically atomic.

Syntax

ConcurrentMap<K,V> map = new ConcurrentHashMap<>(); map.computeIfAbsent(key, fn)

Example

Use a map to count values or remove entries through the iterator.

Code example

ConcurrentMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent("java", k -> new LongAdder()).increment();

Diagram

concurrent callers -> thread-safe map operations -> shared map

Key Points

  • Use atomic map methods such as computeIfAbsent for supported compound map operations.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q64Advanced Boot

How do you debug auto-configuration?

Use the condition evaluation report, startup logs, and dependency tree to determine why configuration matched or backed off

Answer

Use the condition evaluation report, startup logs, and dependency tree to determine why configuration matched or backed off. Verify properties, classpath, candidate beans, and framework compatibility.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

java -jar app.jar --debug
./mvnw dependency:tree

Key Points

  • Do not exclude auto-config first
  • Add a regression test
Q65Advanced Boot

How do you resolve circular dependencies?

A circular dependency means components require each other directly or indirectly

Answer

A circular dependency means components require each other directly or indirectly. Prefer separating responsibilities or introducing a shared collaborator rather than hiding the cycle with lazy resolution.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

AService → BService → AService
Refactor: AService → SharedPolicy ← BService

Key Points

  • Constructor cycles often block startup
  • @Lazy can mask coupling
Q66Advanced Boot

How would you build a custom starter?

A reusable starter combines dependency convenience with conditional auto-configuration

Answer

A reusable starter combines dependency convenience with conditional auto-configuration. It should be property-driven, overridable by user beans, and tested for activation and back-off behavior.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

starter → auto-configuration → @ConditionalOnClass / @ConditionalOnProperty / @ConditionalOnMissingBean

Key Points

  • Separate dependencies and configuration when useful
  • Test conditions
Q67Production

How does graceful shutdown work?

Graceful shutdown stops new work and gives in-flight requests a bounded time to finish

Answer

Graceful shutdown stops new work and gives in-flight requests a bounded time to finish. Coordinate server settings, orchestrator termination grace, and recovery for unfinished jobs.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=20s

Key Points

  • Drain readiness before termination
  • Persist durable work
Q68Performance

Can Spring Boot use virtual threads?

Supported Java and Spring Boot versions can use virtual threads to reduce the cost of many blocking tasks

Answer

Supported Java and Spring Boot versions can use virtual threads to reduce the cost of many blocking tasks. They do not speed up CPU-bound work or remove database and downstream limits.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

spring.threads.virtual.enabled=true

Key Points

  • Verify exact version support
  • Monitor pools and downstream concurrency
Q69Resilience

How does a circuit breaker help?

A circuit breaker temporarily rejects calls when a dependency is failing or slow, limiting resource exhaustion and allowing recovery

Answer

A circuit breaker temporarily rejects calls when a dependency is failing or slow, limiting resource exhaustion and allowing recovery. It must be paired with timeouts, sensible fallback behavior, and monitoring.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Closed → failures threshold → Open → timed wait → Half-open probes

Key Points

  • Retries can amplify load
  • Do not fake success for critical operations
Q70Resilience

How should retries use backoff?

Retry only likely transient failures, cap attempts, add exponential backoff with jitter, and respect deadlines

Answer

Retry only likely transient failures, cap attempts, add exponential backoff with jitter, and respect deadlines. Side-effecting operations must be idempotent or protected by idempotency keys.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

delay = min(maxDelay, initialDelay × 2^attempt) + jitter

Key Points

  • Do not retry validation errors
  • Avoid synchronized retry storms
Q71Resilience

How would you rate-limit an API?

Rate limiting caps request volume over a time window or token budget, often by user, tenant, or API key

Answer

Rate limiting caps request volume over a time window or token budget, often by user, tenant, or API key. It can run at a gateway or in the application.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Request → identify client → token bucket → allow or HTTP 429

Key Points

  • Distributed deployments need shared/partitioned state
  • Return useful retry guidance
Q72Distributed systems

Explain the transactional outbox pattern.

The business change and event record are written in the same database transaction

Answer

The business change and event record are written in the same database transaction. A publisher later sends pending events to a broker, avoiding the dual-write gap between database commit and message publication.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Transaction: update order + insert outbox row → commit → publisher → broker → idempotent consumer

Key Points

  • Consumers must tolerate duplicates
  • Monitor lag and poison events
Q73Distributed systems

What is a saga?

A saga coordinates local transactions across services with compensating business actions

Answer

A saga coordinates local transactions across services with compensating business actions. It is useful when a global ACID transaction is impractical, but partial completion and compensation failures must be modeled.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Reserve stock → charge payment → ship
Failure → compensate earlier steps

Key Points

  • Choreography vs orchestration
  • Make steps idempotent
Q74Messaging

How should Spring Boot integrate with Kafka?

Spring for Apache Kafka provides producers, listeners, serializers, and error-handling integration

Answer

Spring for Apache Kafka provides producers, listeners, serializers, and error-handling integration. Reliable processing requires deliberate partitioning, consumer groups, retry policies, and idempotent effects.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

@KafkaListener(topics="orders", groupId="billing")
void consume(OrderCreated event) { service.process(event); }

Key Points

  • Choose keys for ordering needs
  • Plan dead-letter handling
Q75Messaging

What does exactly-once mean?

Exactly-once is scoped, not universal

Answer

Exactly-once is scoped, not universal. A broker may provide transactional guarantees within its boundaries, while external side effects still require idempotency, deduplication, or coordination.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

At-least-once delivery + idempotent handler → one effective business outcome

Key Points

  • Define the guarantee boundary
  • Expect redelivery after failures
Q76Security

OAuth 2.0 vs OpenID Connect

OAuth 2.0 is an authorization framework; OpenID Connect adds an identity layer

Answer

OAuth 2.0 is an authorization framework; OpenID Connect adds an identity layer. Access tokens authorize API access, while ID tokens convey authentication information to the client.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Client → OIDC provider → ID token
Client → API with access token → resource server

Key Points

  • Do not use ID tokens as API access tokens
  • Validate issuer, audience, expiry, signature
Q77Security

How should production secrets be managed?

Use a secret manager or secure deployment mechanism, least-privilege access, rotation, and auditing

Answer

Use a secret manager or secure deployment mechanism, least-privilege access, rotation, and auditing. Never hard-code secrets in repositories, image layers, logs, or public management endpoints.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Application identity → secret manager → credential

Key Points

  • Separate environments
  • Plan rotation without downtime
  • Scan build artifacts
Q78Security

How do you prevent SSRF?

Server-side request forgery can make a service fetch unintended destinations

Answer

Server-side request forgery can make a service fetch unintended destinations. Allowlist destinations, validate resolved IPs, restrict redirects, and enforce outbound network controls.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Untrusted URL → host/IP policy → restricted HTTP client

Key Points

  • Block private and metadata destinations where appropriate
  • Account for DNS rebinding
Q79Security

What is mass assignment?

Mass assignment happens when client input is bound directly to sensitive model fields, allowing changes such as role or owner

Answer

Mass assignment happens when client input is bound directly to sensitive model fields, allowing changes such as role or owner. Use explicit DTOs and authorize changes in business logic.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

JSON → allowlisted DTO → authorized service update

Key Points

  • Never trust client-supplied roles
  • Test privileged-field tampering
Q80Persistence

Optimistic vs pessimistic locking

Optimistic locking detects conflicts on update and suits lower contention

Answer

Optimistic locking detects conflicts on update and suits lower contention. Pessimistic locking obtains database locks to serialize critical concurrent operations but can reduce throughput and cause deadlocks.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Low contention → @Version
High critical contention → short locked transaction

Key Points

  • Measure contention
  • Keep lock transactions short
  • Handle timeouts
Q81Performance

How do you size a connection pool?

Pool size depends on database capacity, concurrency, query duration, and replica count

Answer

Pool size depends on database capacity, concurrency, query duration, and replica count. Increasing it blindly can overload the database; inspect acquisition wait, active connections, leaks, and slow queries.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Potential connections = pool size × replica count

Key Points

  • Budget all application replicas
  • Monitor pool and database metrics
Q82Concurrency

How do you prevent thread-pool exhaustion?

Use bounded executors and queues, request deadlines, admission control, and predictable overload rejection

Answer

Use bounded executors and queues, request deadlines, admission control, and predictable overload rejection. Unbounded queues can hide overload until latency and memory usage become unacceptable.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Incoming work → bounded queue → worker pool; full → reject/shed load

Key Points

  • Monitor queue depth
  • Size for workload
  • Propagate deadlines
Q83Observability

How do you investigate a memory leak?

Track heap after garbage collection, inspect allocations, capture a protected heap dump, and identify unexpectedly retained objects

Answer

Track heap after garbage collection, inspect allocations, capture a protected heap dump, and identify unexpectedly retained objects. Common causes include unbounded caches and static collections.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Metrics → heap dump/profile → retained-object analysis → fix → regression test

Key Points

  • Use JFR or heap tools
  • Heap dumps may contain sensitive data
Q84Performance

How can startup time be improved?

Measure startup first, then reduce unnecessary bean creation, auto-configuration, and blocking initialization

Answer

Measure startup first, then reduce unnecessary bean creation, auto-configuration, and blocking initialization. Lazy initialization can help selectively, but readiness must not be declared before the service can safely serve traffic.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Measure → identify slow initializer → optimize → remeasure

Key Points

  • Compare cold starts consistently
  • Keep health-critical initialization
Q85Architecture

How would you design multi-tenancy?

Tenancy can use shared tables with tenant keys, schema-per-tenant, or database-per-tenant

Answer

Tenancy can use shared tables with tenant keys, schema-per-tenant, or database-per-tenant. Choose based on isolation, compliance, scale, and operational cost, and enforce tenant scope centrally.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Authenticated request → tenant context → authorization → tenant-scoped repository

Key Points

  • Derive tenant from trusted identity
  • Tenant-aware cache keys
  • Plan migrations
Q86Observability

How do distributed traces help?

Distributed tracing links spans across services using trace context, helping locate latency and failures

Answer

Distributed tracing links spans across services using trace context, helping locate latency and failures. Metrics show aggregate patterns and logs provide event detail.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Gateway span → Order span → Payment span → Database span

Key Points

  • Propagate context
  • Avoid high-cardinality metric labels
  • Protect sensitive trace attributes
Q87Deployment

Blue-green vs canary deployment

Blue-green switches traffic between two environments and supports fast rollback if data changes are compatible

Answer

Blue-green switches traffic between two environments and supports fast rollback if data changes are compatible. Canary gradually routes a small percentage to a new version and expands based on health signals.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Blue 100% → Green 100%
Canary: stable 95% + new 5% → gradual expansion

Key Points

  • Database compatibility matters
  • Set rollback thresholds
Q88Deployment

How do you containerize Spring Boot?

Package the application in a minimal supported runtime image, use a non-root user, externalize configuration, and avoid secrets in image layers

Answer

Package the application in a minimal supported runtime image, use a non-root user, externalize configuration, and avoid secrets in image layers. Pin and scan base images.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/app.jar app.jar
USER 10001
ENTRYPOINT ["java","-jar","app.jar"]

Key Points

  • Use reproducible builds
  • Configure resource limits and graceful shutdown
Q89Deployment

How should Kubernetes probes be configured?

Liveness determines whether a process should restart; readiness determines whether it should receive traffic

Answer

Liveness determines whether a process should restart; readiness determines whether it should receive traffic. A startup probe can protect slow initialization from premature liveness failure.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    port: 8080
readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    port: 8080

Key Points

  • Do not overuse deep dependency checks
  • Align probe thresholds with startup behavior
Q90Architecture

How would you apply clean architecture?

Clean architecture keeps domain rules and use cases independent of infrastructure details

Answer

Clean architecture keeps domain rules and use cases independent of infrastructure details. HTTP, persistence, and messaging adapters depend inward on stable interfaces rather than making business logic depend on framework specifics.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

HTTP adapter → use case → domain
                 ↑
       repository port ← persistence adapter

Key Points

  • Keep framework types near edges when practical
  • Avoid layers without purpose
Q91Architecture

What is hexagonal architecture?

Ports-and-adapters architecture exposes application capabilities through ports and implements them with adapters for HTTP, databases, or messaging

Answer

Ports-and-adapters architecture exposes application capabilities through ports and implements them with adapters for HTTP, databases, or messaging. This lets tests or alternate transports exercise the same use cases.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

REST adapter → inbound port → application core → outbound port → DB adapter

Key Points

  • Ports express required capabilities
  • Adapters contain infrastructure details
Q92Production

What is a production-readiness checklist?

Review correctness, security, resilience, observability, performance, deployment, and recovery

Answer

Review correctness, security, resilience, observability, performance, deployment, and recovery. Check authorization, timeouts, probes, migrations, alerts, rollback, and load-tested resource limits.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Code/tests → security review → load/failure tests → deploy → observe → rollback if needed

Key Points

  • Test failure paths
  • Protect sensitive logs
  • Document operations
Q93Setup and configuration

How do you plan a Spring Boot major upgrade?

Review Java compatibility, migration notes, dependency versions, deprecated APIs, security changes, and runtime behavior

Answer

Review Java compatibility, migration notes, dependency versions, deprecated APIs, security changes, and runtime behavior. Upgrade in a branch, run integration tests and representative workloads, then deploy with monitoring and rollback.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Inventory → compatibility review → upgrade → test → canary → full rollout

Key Points

  • Read official migration notes
  • Test serialization, security, persistence, and startup
Q94REST APIs

How would you design a maintainable REST API?

Define resource routes, DTOs, validation, status codes, pagination, error formats, authentication, and compatibility rules

Answer

Define resource routes, DTOs, validation, status codes, pagination, error formats, authentication, and compatibility rules. Keep controllers thin, business logic in services, and test both contract and persistence behavior.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Client → security → controller/validation → service → repository → DB

Key Points

  • Document contracts
  • Apply authorization and rate limits
  • Add observability
Q95Distributed systems

Why are distributed transactions difficult?

Independent services cannot normally share one local database transaction

Answer

Independent services cannot normally share one local database transaction. Partial failures and network partitions require explicit consistency choices, often using sagas, outbox events, idempotency, and reconciliation.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Service A commit → outbox/event → Service B commit
Failure → retry / compensate / reconcile

Key Points

  • Define consistency requirements
  • Build recovery paths
Q96Resilience

Rate limiting vs backpressure

Rate limiting caps client request volume

Answer

Rate limiting caps client request volume. Backpressure communicates or enforces downstream capacity so producers do not overwhelm consumers; both may be needed at different boundaries.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Client → rate limiter → service → bounded queue → consumer

Key Points

  • 429 can signal rate limits
  • Bound queues
  • Monitor rejection and latency
Q97Testing

What is contract testing?

Contract testing verifies that a provider and consumer agree on HTTP or message expectations without always requiring a full end-to-end environment

Answer

Contract testing verifies that a provider and consumer agree on HTTP or message expectations without always requiring a full end-to-end environment. It complements integration and end-to-end testing.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Consumer expectation → provider verification → CI gate

Key Points

  • Use realistic contracts
  • Test backward compatibility
  • Version event schemas
Q98Performance

How do you load-test a Spring Boot API?

Define representative traffic, data volume, concurrency, and success criteria

Answer

Define representative traffic, data volume, concurrency, and success criteria. Measure throughput, p95/p99 latency, errors, CPU, memory, pools, and database behavior while ramping load and testing recovery.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Baseline → ramp → sustain → spike/recovery → analyze bottleneck

Key Points

  • Use realistic data
  • Measure tail latency
  • Protect shared environments
Q99Distributed systems

What is eventual consistency?

Eventual consistency means separate services or replicas may temporarily disagree but converge if updates stop and propagation succeeds

Answer

Eventual consistency means separate services or replicas may temporarily disagree but converge if updates stop and propagation succeeds. APIs should communicate pending operations and expose status rather than promise immediate downstream completion.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Command accepted → pending → event propagation → state converges

Key Points

  • Define acceptable delay
  • Support retries and reconciliation
Q100Deployment

How should feature flags be used?

Feature flags separate deployment from activation, enabling controlled rollout and rapid disablement

Answer

Feature flags separate deployment from activation, enabling controlled rollout and rapid disablement. Define safe defaults, ownership, monitoring, and cleanup because stale flags add complexity.

Practical interview angle: explain when you would use this approach, its main trade-off, and how you would test or monitor it in a real application.

Syntax

Deploy disabled → internal users → canary → expand → remove flag

Key Points

  • Plan behavior if flag service fails
  • Remove temporary flags
Q104Concurrency

What is the difference between synchronized and ReentrantLock?

What is the difference between synchronized and ReentrantLock?

Answer

Both provide mutual exclusion. synchronized uses language-level monitor locking and releases automatically when leaving the block; ReentrantLock offers features such as timed/interruptible acquisition and optional fairness.

Syntax

lock.lock(); try { ... } finally { lock.unlock(); }

Example

Use an atomic counter or a lock when multiple threads update shared state.

Code example

private final Lock lock = new ReentrantLock();
void update() { lock.lock(); try { state++; } finally { lock.unlock(); } }

Diagram

thread A/B -> lock -> critical section -> unlock

Key Points

  • Always unlock in finally
  • choose the simpler synchronized construct unless extra lock features are needed.
Q105Concurrency

What is a race condition?

What is a race condition?

Answer

A race condition occurs when the result depends on the unpredictable timing or interleaving of concurrent operations on shared state.

Syntax

synchronized (mutex) { counter++; }

Example

Use an atomic counter or a lock when multiple threads update shared state.

Code example

private final AtomicInteger counter = new AtomicInteger();
int next() { return counter.incrementAndGet(); }

Diagram

threads -> shared state -> unsynchronized interleaving -> unpredictable result

Key Points

  • Compound operations such as read-modify-write are not automatically atomic.
Q106Concurrency

When should you use CompletableFuture?

When should you use CompletableFuture?

Answer

Use CompletableFuture to compose asynchronous tasks, combine results, and handle completion or errors without manually coordinating threads.

Syntax

CompletableFuture.supplyAsync(...).thenApply(...).exceptionally(...)

Example

Use an atomic counter or a lock when multiple threads update shared state.

Code example

CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> loadName(), executor)
    .thenApply(String::trim);

Diagram

task A -> thenApply -> result
       \-> exceptionally -> recovery

Key Points

  • Choose an appropriate executor for blocking work
  • do not assume every async task should use the common pool.
Q113Spring Boot

How should secrets be managed in a Spring Boot application?

How should secrets be managed in a Spring Boot application?

Answer

Keep secrets out of source code and version control. Inject them from a secret manager or deployment environment, rotate them, and limit access.

Syntax

${DB_PASSWORD}

Example

Bind deployment-specific settings through configuration rather than hardcoding them.

Code example

spring:
  datasource:
    password: ${DB_PASSWORD}

Diagram

secret manager -> deployment injection -> application configuration

Key Points

  • Avoid logging credentials
  • use separate credentials per environment and least-privilege database accounts.
Q117Hibernate & JPA

What is the difference between optimistic and pessimistic locking?

What is the difference between optimistic and pessimistic locking?

Answer

Optimistic locking detects conflicting updates, commonly with @Version. Pessimistic locking obtains a database lock to restrict concurrent access while a transaction proceeds.

Syntax

@Version private long version;

Example

Inspect SQL and transaction boundaries when tuning persistence behavior.

Code example

@Entity
class Inventory { @Id Long id; @Version long version; int quantity; }

Diagram

read version -> update with version predicate -> conflict detected if stale

Key Points

  • Optimistic locking suits many low-contention cases
  • use pessimistic locking only when contention and transaction design justify it.
Q121REST APIs

How do you version a REST API?

How do you version a REST API?

Answer

Common strategies include URI versioning, custom headers, and media-type versioning. Choose one strategy, document compatibility rules, and provide a migration path.

Syntax

/api/v1/orders

Example

Validate request DTOs and return a consistent error body.

Code example

@RequestMapping("/api/v1/orders")
@RestController
class OrderController { }

Diagram

client v1 -> stable contract; client v2 -> new contract

Key Points

  • Avoid breaking existing clients without a clear deprecation and migration plan.
Q122Observability

What is the role of Actuator in Spring Boot?

What is the role of Actuator in Spring Boot?

Answer

Spring Boot Actuator exposes operational endpoints such as health and metrics, with exposure controlled by configuration and security.

Syntax

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

Example

Expose health and metrics endpoints only to authorized monitoring systems.

Code example

management:
  endpoints:
    web:
      exposure:
        include: health,info

Diagram

application -> Actuator endpoints -> monitoring system

Key Points

  • Do not expose sensitive management endpoints publicly without authentication and authorization.
Q123Concurrency

What is a deadlock and how can it be prevented?

What is a deadlock and how can it be prevented?

Answer

A deadlock occurs when threads wait indefinitely for resources held by one another. Prevention techniques include consistent lock ordering, reducing nested locks, and using timeouts where suitable.

Syntax

lock.tryLock(timeout, unit)

Example

Use an atomic counter or a lock when multiple threads update shared state.

Code example

if (first.tryLock()) { try { if (second.tryLock()) { try { work(); } finally { second.unlock(); } } } finally { first.unlock(); } }

Diagram

thread A holds lock 1 -> waits lock 2
thread B holds lock 2 -> waits lock 1

Key Points

  • Collect thread dumps during incidents
  • use a consistent global order when multiple locks are required.
Q125Hibernate & JPA

What is the difference between flush and commit?

What is the difference between flush and commit?

Answer

Flush synchronizes pending persistence-context changes with the database, while commit completes the transaction. A flush does not itself guarantee the transaction will commit.

Syntax

entityManager.flush();

Example

Inspect SQL and transaction boundaries when tuning persistence behavior.

Code example

entityManager.persist(entity);
entityManager.flush(); // SQL synchronization, not transaction commit

Diagram

persistence context -> flush SQL -> transaction commit/rollback

Key Points

  • Constraints may fail at flush time
  • the transaction can still roll back afterward.

Share this question bank

Send this page to someone preparing for an interview.