🍃Frameworks & Runtimes

Top 50 Spring / Spring Boot
interview questions

IoC, auto-configuration, Spring Data, Security and microservices. Open a question to read the answer.

01

Explain Spring IoC and dependency injection in the context of Spring / Spring Boot.

Inversion of Control means the framework, not the application code, creates objects and wires them together. Dependency injection is the mechanism Spring uses to do it: the container (ApplicationContext) instantiates beans, resolves what each one needs, and hands those collaborators in through constructor parameters, setters, or fields.

The container builds a graph of bean definitions from annotations or @Configuration classes, then instantiates them in dependency order. The class under construction never calls new on its collaborators, so it depends only on interfaces and can be tested with substitutes.

@Service
public class OrderService {
    private final PaymentGateway gateway;
    private final OrderRepository orders;

    // Single constructor: Spring injects without @Autowired
    public OrderService(PaymentGateway gateway, OrderRepository orders) {
        this.gateway = gateway;
        this.orders = orders;
    }
}

Constructor injection is the recommended style since Spring 4.3: dependencies are final, mandatory, and visible in the signature. Field injection (@Autowired on a private field) still works but hides dependencies and forces reflection in tests. Spring Boot adds nothing to the mechanism itself; it simply pre-registers hundreds of beans through auto-configuration so most wiring is already done.

Interview takeaway: IoC is the principle, DI is the technique, and the ApplicationContext is the implementation.

02

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring IoC and dependency injection?

Apply. In a payments service I keep every collaborator behind an interface (FraudCheck, LedgerClient) and inject through constructors. Where two implementations exist, for example a sandbox and a live gateway, I mark one @Primary or select by @Qualifier, or better, let a @ConditionalOnProperty decide which bean exists at all. Configuration objects come in as @ConfigurationProperties records rather than scattered @Value strings.

Test. Unit tests construct the class directly with Mockito mocks; no Spring context is needed because constructor injection makes that trivial. For wiring itself I use a slice test or @SpringBootTest with @MockitoBean (Boot 3.4+, replacing the deprecated @MockBean) to swap the external gateway, and one context-load test that fails fast if the graph cannot be assembled.

Troubleshoot. The classic symptoms are NoSuchBeanDefinitionException and NoUniqueBeanDefinitionException at startup. I read the condition evaluation report (debug=true or the Actuator conditions endpoint) to see why a bean was or was not created, check that the class sits under the @SpringBootApplication package, and verify profile-gated beans are active. A null field at runtime almost always means the object was created with new instead of being injected, or a static reference was taken before the context finished.

Important consideration: injecting too many dependencies into one class is a design smell the container will happily hide; a constructor with eight parameters is a signal to split the service.

03

Explain Spring beans and scopes in the context of Spring / Spring Boot.

A bean is any object whose lifecycle the Spring container manages: instantiation, dependency injection, initialisation callbacks (@PostConstruct, InitializingBean), and destruction (@PreDestroy). Beans are declared with stereotype annotations or @Bean methods and identified by name and type.

Scope controls how many instances exist and how long they live.

ScopeInstancesAvailable in
singleton (default)One per ApplicationContextAny application
prototypeNew object on every request to the containerAny application
requestOne per HTTP requestWeb applications
sessionOne per HTTP sessionWeb applications
applicationOne per ServletContextWeb applications

The lifecycle of a singleton bean runs through these stages.

Diagram: Bean definition, Instantiate, Inject dependencies, Aware callbacks, @PostConstruct, Post-processors (proxies), In use, @PreDestroy

Singletons are created eagerly at startup unless marked @Lazy, which is why most wiring errors appear before the application serves traffic. Because singletons are shared across threads, they must be stateless or guard their state. Injecting a shorter-lived scope into a singleton requires a scoped proxy (@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)) or an ObjectProvider; otherwise the singleton captures the first instance for ever.

@Bean
@Scope("prototype")
public ReportBuilder reportBuilder() {
    return new ReportBuilder(); // fresh instance per injection point or getBean()
}

Spring does not call @PreDestroy on prototype beans; once handed out, their cleanup is the caller’s responsibility.

04

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring beans and scopes?

Apply. Almost everything stays singleton. In a reporting service, the exceptions are a mutable ReportBuilder that accumulates rows, which I make prototype and obtain through an injected ObjectProvider<ReportBuilder>, and a RequestContext holding the tenant id, which I declare request-scoped with a TARGET_CLASS proxy so services can inject it directly. Expensive singletons that are rarely used (a PDF renderer) get @Lazy so they do not slow startup.

Test. A context test asserts context.getBean(ReportBuilder.class) != context.getBean(ReportBuilder.class) to prove the prototype scope is in effect, and a @WebMvcTest with two sequential MockMvc calls checks the request-scoped bean is rebuilt each time. Startup time is tracked with the Actuator startup endpoint to see whether @Lazy actually helped.

Troubleshoot. State leaking between users is the signature of a singleton holding per-request data in a field; a thread dump or a simple log of this.hashCode() confirms one instance is being reused. The Scope 'request' is not active for the current thread exception means a request-scoped bean was touched from an @Async or scheduled thread; the fix is to pass the needed values explicitly rather than reach for the bean. Memory growth from prototype beans points to code that expects Spring to destroy them.

Important consideration: scopes other than singleton add proxies and indirection, so I reach for them only when the lifecycle truly differs, not as a substitute for passing method arguments.

05

Explain component scanning annotations in the context of Spring / Spring Boot.

Component scanning is the process by which Spring walks the classpath, finds classes carrying stereotype annotations, and registers them as bean definitions. @ComponentScan turns it on and sets the base packages; @SpringBootApplication includes it implicitly, defaulting to the package of the annotated class and everything below it.

The stereotype annotations all derive from @Component and differ mainly in intent and in the extra behaviour attached to them:

  • @Component – generic managed class.
  • @Service – business logic; no extra behaviour today but documents the layer.
  • @Repository – data access; enables PersistenceExceptionTranslationPostProcessor, which converts JPA and JDBC exceptions into Spring’s DataAccessException hierarchy.
  • @Controller / @RestController – web layer; @RestController adds @ResponseBody to every handler.
  • @Configuration – a source of @Bean methods, proxied so repeated calls return the same singleton.

Scanning can be narrowed with includeFilters, excludeFilters, or a custom annotation meta-annotated with @Component. Because the default root is the main class’s package, placing MyApplication in com.acme and a service in com.acme.orders works, while a service in com.other is silently ignored. Boot’s @SpringBootApplication also carries @EnableAutoConfiguration, which registers framework beans through a different mechanism, META-INF/spring/...AutoConfiguration.imports, not scanning.

06

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot component scanning annotations?

Apply. I put the @SpringBootApplication class at the root package (com.acme.billing) and keep every module beneath it, so no explicit @ComponentScan is needed. In a multi-module build where a shared library ships its own beans, I expose them through an auto-configuration class listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports rather than asking consumers to widen their scan. Annotating repositories with @Repository gives me the exception translation that lets services catch DataIntegrityViolationException instead of vendor-specific types.

Test. @WebMvcTest(InvoiceController.class) and @DataJpaTest deliberately scan only one layer, so a service accidentally pulled into a web slice fails the test and reveals a misplaced annotation. An ApplicationModules -style architecture test (ArchUnit) asserts that classes in ..web.. carry @RestController and nothing in ..domain.. depends on Spring.

Troubleshoot. A bean that “does not exist” when the class clearly has @Service is almost always outside the scanned package; --debug plus a search of the condition report, or listing beans via the Actuator beans endpoint, settles it quickly. ConflictingBeanDefinitionException arises when two classes with the same simple name sit in different packages; I give one an explicit bean name. Slow startup in a large monolith can come from scanning thousands of classes, which is where AOT processing or a tighter base package helps.

Important consideration: widening @ComponentScan to a parent package also pulls in test fixtures and sample code on the classpath, so I prefer narrowing scope to broadening it.

07

Explain Spring Boot auto-configuration in the context of Spring / Spring Boot.

Auto-configuration is Boot’s mechanism for registering sensible default beans based on what is on the classpath and what properties are set. @EnableAutoConfiguration (part of @SpringBootApplication) loads the classes listed in each jar’s META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports and evaluates their conditions after the application’s own beans have been defined.

Each auto-configuration class is guarded by conditions:

  • @ConditionalOnClass – only if, say, DataSource and HikariCP are present.
  • @ConditionalOnMissingBean – back off when the application defines its own bean of that type.
  • @ConditionalOnProperty – honour switches such as spring.jpa.open-in-view.
  • @ConditionalOnWebApplication – servlet or reactive stack only.

The diagram shows how a DataSource ends up in the context.

Diagram: Classpath HikariCP, JDBC, Properties spring.datasource.*, DataSourceAutoConfiguration, User @Bean DataSource, backs off, …

Because user beans are processed first, defining your own ObjectMapper or DataSource simply switches the default off. Individual classes can also be disabled with spring.autoconfigure.exclude or @SpringBootApplication(exclude = ...). The condition evaluation report, printed with debug=true, lists every positive and negative match, which makes the “magic” fully inspectable.

08

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring Boot auto-configuration?

Apply. For a company platform team I package cross-cutting defaults (correlation-id filter, standard ObjectMapper modules, Micrometer common tags) into a platform-starter with its own @AutoConfiguration classes guarded by @ConditionalOnMissingBean, so any service gets them by adding one dependency and can still override piece by piece. Inside a service, I rely on the provided DataSource, JdbcTemplate and KafkaTemplate instead of hand-building them, and tune through properties.

Test. ApplicationContextRunner tests the custom auto-configuration in isolation: one case asserts the bean appears with defaults, another registers a user bean and asserts the auto-configured one backed off, a third sets platform.tracing.enabled=false and asserts absence. Service-level @SpringBootTest runs confirm the real combination loads.

new ApplicationContextRunner()
    .withConfiguration(AutoConfigurations.of(CorrelationAutoConfiguration.class))
    .withPropertyValues("platform.correlation.enabled=false")
    .run(ctx -> assertThat(ctx).doesNotHaveBean(CorrelationFilter.class));

Troubleshoot. When a bean unexpectedly appears or disappears, I run with --debug and read the CONDITIONS EVALUATION REPORT, or hit /actuator/conditions in a non-production environment. Typical findings: a transitive dependency dragged in spring-boot-starter-web, so an embedded Tomcat started in a batch job; or two DataSource candidates made Boot stop configuring JPA. Startup failures that mention Failed to configure a DataSource mean the JDBC starter is present but no URL was set.

Important consideration: excluding an auto-configuration class is a blunt tool; defining the one bean you want to change is usually the cleaner override.

09

Explain starters and dependency management in the context of Spring / Spring Boot.

A starter is a curated Maven or Gradle dependency, such as spring-boot-starter-web or spring-boot-starter-data-jpa, that pulls in a coherent set of libraries and the matching auto-configuration. The starter itself contains no code; its value is the dependency list and the versions chosen to work together.

Version alignment comes from the spring-boot-dependencies BOM. With Maven, projects either inherit from spring-boot-starter-parent or import the BOM in dependencyManagement; with Gradle, the io.spring.dependency-management plugin or Gradle’s native platform support does the same. Either way, dependencies declared without a version receive the Boot-tested one.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
  <!-- no version: managed by the Boot BOM -->
</dependency>

Overriding a managed version is done through properties such as <hibernate.version> or ext['hibernate.version'], which keeps the override visible and centralised. Third-party BOMs, for example Spring Cloud, layer on top with their own release trains that state which Boot line they support.

Spring Boot 4 (November 2025) split several starters and auto-configuration modules more finely, so some features that arrived transitively in 3.x now require an explicit starter; the dependency-management model itself is unchanged. (Verified against Boot 4 release coverage.)

10

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot starters and dependency management?

Apply. Every service in the fleet inherits a company parent POM that imports the Boot BOM, the Spring Cloud BOM, and a small internal BOM for shared libraries. Teams add only starters and never type versions. When a CVE lands in, say, Tomcat, the parent bumps tomcat.version once and every service picks it up on the next build. I exclude spring-boot-starter-tomcat and add spring-boot-starter-undertow or -jetty only when a measured need exists.

Test. The build runs mvn dependency:tree -Dverbose or ./gradlew dependencies in CI and fails on duplicate artifacts with differing versions via the Maven Enforcer plugin’s dependencyConvergence rule.

OWASP Dependency-Check or Snyk scans the resolved tree. A smoke @SpringBootTest after each Boot upgrade confirms the context still loads.

Troubleshoot. NoSuchMethodError or ClassNotFoundException at runtime almost always means a library bypassed the BOM; dependency:tree shows which path introduced the stray version, and an <exclusion> or a managed override resolves it. An unexpected embedded server or JPA bootstrap points to a starter pulled in transitively by an internal library, which should declare it optional or provided. When Spring Cloud and Boot release trains are mismatched, the error is often a cryptic BeanDefinitionOverrideException; checking the compatibility matrix fixes it.

Important consideration: starters make it easy to accumulate unused dependencies, each of which widens the attack surface and startup time, so the tree deserves periodic pruning.

11

Explain application properties profiles in the context of Spring / Spring Boot.

Profiles let one artifact carry several configurations and activate the right one per environment. Boot loads application.properties or application.yml first, then application-<profile>.properties for each active profile, with later files overriding earlier keys. Profiles are activated through spring.profiles.active, the SPRING_PROFILES_ACTIVE environment variable, or --spring.profiles.active=prod on the command line.

Beans can be gated as well: a class or @Bean method annotated @Profile("local") exists only when that profile is active, and @Profile("!prod") inverts the condition.

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/orders
---
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:postgresql://db.internal:5432/orders

Since Boot 2.4 the --- document separator with spring.config.activate.on-profile replaces the older spring.profiles key, and spring.profiles.group can bundle profiles (prod implies metrics,secure). Properties from the environment and command line always outrank files, which is how containers inject secrets without a profile file. spring.profiles.default names the fallback when nothing is active; if nothing is set, the profile is literally default.

12

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot application properties profiles?

Apply. In a Kubernetes-deployed order service, the image is built once. application.yml holds safe defaults, application-local.yml points at Docker Compose dependencies, and prod is not a file at all: the deployment sets SPRING_PROFILES_ACTIVE=prod and injects hosts and credentials as environment variables or a mounted application-prod.yml from a Secret via spring.config.import=optional:configtree:/etc/secrets/. Typed @ConfigurationProperties classes with @Validated fail startup when a required value is missing.

Test. @SpringBootTest with @ActiveProfiles("test") loads an application-test.yml that points at Testcontainers. A dedicated test asserts the bound properties object has the expected values, and a CI step runs the jar with the prod profile and placeholder secrets to prove the context starts. The /actuator/env endpoint, enabled only in non-production, shows which PropertySource won for a given key.

Troubleshoot. A value “not taking effect” is nearly always precedence: an environment variable or a stale -D system property outranks the file. Boot’s relaxed binding also matters; SPRING_DATASOURCE_URL maps correctly, but spring.dataSource.url with odd casing does not. If a @Profile("prod") bean is missing, the startup log line The following 1 profile is active reveals which profiles were really applied. Multi-document YAML with the pre-2.4 spring.profiles key is silently ignored on Boot 3.

Important consideration: never commit production secrets in application-prod.yml; profiles select configuration, they are not a secret store.

13

Explain REST controllers and DTOs in the context of Spring / Spring Boot.

A @RestController is a Spring MVC controller whose handler methods return data that is written straight to the response body, serialised by Jackson (or another HttpMessageConverter), rather than a view name. Request mapping annotations (@GetMapping, @PostMapping, @RequestMapping) bind URLs and HTTP methods to methods, while @PathVariable, @RequestParam, @RequestBody and @RequestHeader bind inputs.

The diagram shows where DTOs sit in a request.

Diagram: Client JSON, DispatcherServlet, Jackson converter, Response DTO, Request DTO, @RestController, Service, JPA Entity

A DTO (data transfer object) is the shape of that payload, kept separate from JPA entities. Entities carry persistence concerns: lazy associations, bidirectional links, audit columns, and internal identifiers. Exposing them directly leaks schema, risks infinite recursion in serialisation, and lets clients post fields they should not control. A DTO defines the public contract explicitly and can evolve independently.

public record CreateOrderRequest(@NotBlank String customerId,
                                 @NotEmpty List<LineDto> lines) {}

public record OrderResponse(UUID id, String status, BigDecimal total) {}

@RestController
@RequestMapping("/api/orders")
class OrderController {
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    OrderResponse create(@Valid @RequestBody CreateOrderRequest req) {
        return mapper.toResponse(service.place(req));
    }
}

Java records are the natural DTO type since Boot 3 requires Java 17. Mapping between entity and DTO is done by hand or with MapStruct; ResponseEntity is used when status codes or headers vary per response.

14

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot REST controllers and DTOs?

Apply. Controllers in an order API stay thin: bind, validate, delegate to a service, map the result. Request and response DTOs are records in an api package, versioned by URL (/api/v1/orders) or media type when a breaking change is unavoidable. MapStruct generates the entity-to-DTO mappers so field additions are caught at compile time. ResponseEntity is used for 201 Created with a Location header and for conditional responses with ETag.

Test. @WebMvcTest(OrderController.class) with MockMvc and a @MockitoBean service checks routing, status codes, JSON field names, and that an invalid body yields 400 with the expected error shape. A contract test (Spring Cloud Contract or an OpenAPI diff in CI) guards the published schema. Serialisation of each DTO is tested once with @JsonTest to lock down date formats and null handling.

Troubleshoot. HttpMessageNotReadableException on a POST usually means a record component name does not match the JSON, or a constructor is ambiguous; enabling logging.level.org.springframework.web=DEBUG shows the parsed request. StackOverflowError or an enormous payload during serialisation signals an entity with a bidirectional relation leaked into the response. A 415 Unsupported Media Type points at a missing Content-Type: application/json header from the client.

Important consideration: once a DTO is public, renaming a field is a breaking change for every consumer, so additive evolution with @JsonIgnoreProperties(ignoreUnknown = true) on the client side is the safer path.

15

Explain validation annotations in the context of Spring / Spring Boot.

Validation annotations come from Jakarta Bean Validation (jakarta.validation.constraints in Spring Boot 3, previously javax), implemented by Hibernate Validator, and are wired into Spring by spring-boot-starter-validation. Constraints such as @NotNull, @NotBlank, @Size, @Min, @Max, @Email, @Pattern, @Past and @Positive are declared on fields, record components, or method parameters.

In a controller, @Valid on a @RequestBody parameter triggers validation before the handler runs; a failure raises MethodArgumentNotValidException, which Boot’s default error handling turns into 400 Bad Request. Spring’s own @Validated on a class enables method-level validation of service or @ConfigurationProperties beans through an AOP proxy, and its groups attribute lets one DTO carry different rules for create and update.

public record RegisterRequest(
    @NotBlank @Size(max = 60) String name,
    @Email @NotBlank String email,
    @Min(18) int age,
    @Valid Address address) {}   // cascades into the nested object

Nested objects are validated only when the field itself carries @Valid. Custom rules are built by defining an annotation plus a ConstraintValidator, for example @UniqueEmail that queries a repository. Cross-field rules (end date after start date) go on the class level.

Bean Validation checks shape and syntax; business rules that need database state or external services belong in the service layer, where failures can carry domain-specific status codes.

16

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot validation annotations?

Apply. In a customer-onboarding API every inbound record is annotated, @Valid sits on each @RequestBody, and a @RestControllerAdvice converts MethodArgumentNotValidException into a ProblemDetail listing field and message pairs so the front end can highlight inputs. Shared rules such as IBAN format live in a custom @Iban constraint in a common library. Configuration classes use @Validated so a missing payments.api-key stops the application at startup instead of failing on the first call.

Test. Pure unit tests build a Validator via Validation.buildDefaultValidatorFactory() and assert the violation set for each boundary case, which runs in milliseconds. One @WebMvcTest per controller proves the 400 response body shape. Custom validators that hit the database are tested with @DataJpaTest plus Testcontainers.

Set<ConstraintViolation<RegisterRequest>> v =
    validator.validate(new RegisterRequest("", "bad", 12, null));
assertThat(v).extracting(c -> c.getPropertyPath().toString())
             .containsExactlyInAnyOrder("name", "email", "age");

Troubleshoot. Validation that “does nothing” is usually a missing spring-boot-starter-validation dependency (Boot 2.3+ no longer includes it in the web starter) or a forgotten @Valid. Nested DTOs that pass despite bad data lack @Valid on the field. @Validated on a service with constraint annotations on an interface method but not the implementation produces ConstraintDeclarationException. Messages showing as {jakarta.validation...} keys mean the message bundle is not on the classpath.

Important consideration: @NotNull on a primitive int can never fail; use wrapper types for optional numeric fields.

17

Explain exception handling ControllerAdvice in the context of Spring / Spring Boot.

@ControllerAdvice (or @RestControllerAdvice, which adds @ResponseBody) declares a component whose @ExceptionHandler methods apply to every controller, or to a subset chosen by package, annotation or class. It centralises the translation of exceptions into HTTP responses so controllers contain no try/catch blocks.

Resolution order matters: Spring picks the handler whose exception type is closest to the thrown one, checks @ControllerAdvice beans in @Order sequence, and falls back to Boot’s BasicErrorController when nothing matches. The ResponseEntityExceptionHandler base class already maps framework exceptions (MethodArgumentNotValidException, HttpRequestMethodNotSupportedException) to the right status codes and can be extended.

@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(OrderNotFoundException.class)
    ProblemDetail notFound(OrderNotFoundException ex) {
        var pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND,
                                                  ex.getMessage());
        pd.setProperty("orderId", ex.orderId());
        return pd;
    }
}

Spring 6 introduced ProblemDetail and the RFC 9457 application/problem+json media type; setting spring.mvc.problemdetails.enabled=true makes Boot emit it for built-in errors too. Alternatives for simple cases are @ResponseStatus on an exception class or throwing ResponseStatusException directly.

Advice only intercepts exceptions thrown inside handler methods and argument resolution. Failures in servlet filters, including Spring Security, occur before dispatch and need an AuthenticationEntryPoint or AccessDeniedHandler instead.

18

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot exception handling ControllerAdvice?

Apply. The order service has a single ApiExceptionHandler that maps domain exceptions to ProblemDetail: OrderNotFoundException to 404, InsufficientStockException to 409 with the shortfall in an extra property, DataIntegrityViolationException to 409, and a catch-all for Exception returning 500 with a correlation id and no stack trace. Every handler logs at WARN for 4xx and ERROR for 5xx with the trace id from Micrometer, so a client-supplied traceId can be matched to logs.

Test. @WebMvcTest with a @MockitoBean service that throws each exception verifies status, Content-Type: application/problem+json, and the body fields. A test with a bare RuntimeException proves the catch-all hides internals. Because advice is ordinary Spring beans, the handler’s mapping logic is also unit-tested directly.

Troubleshoot. When an exception bypasses the advice and surfaces as Boot’s default white-label JSON, the cause is usually one of three: the advice class is outside the scanned package, two handlers match and the more generic one sits in a higher-priority advice, or the exception was thrown from a filter. Enabling logging.level.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=D shows which resolver handled it. Responses that still include stack traces come from server.error.include-stacktrace=always left over from development.

Important consideration: wrapping every exception into the same 500 destroys information; map the ones clients can act on to distinct status codes and keep the generic handler small.

19

Explain Spring Data JPA repositories in the context of Spring / Spring Boot.

Spring Data JPA repositories are interfaces that Spring implements at runtime. Extending JpaRepository<Order, UUID> yields CRUD methods, paging, sorting and flush operations with no code; the proxy delegates to SimpleJpaRepository, which uses the EntityManager under the hood.

Query methods are derived from method names: findByCustomerIdAndStatus(UUID id, Status s) is parsed into JPQL at startup, so a typo in a property name fails fast. For anything the grammar cannot express, @Query accepts JPQL or native SQL, and @Modifying marks bulk updates. Projections return interfaces or records containing only the selected columns, and Specification or Querydsl handle dynamic criteria.

public interface OrderRepository extends JpaRepository<Order, UUID> {

    Page<Order> findByStatus(OrderStatus status, Pageable pageable);

    @Query("select o from Order o join fetch o.lines where o.id = :id")
    Optional<Order> findWithLines(@Param("id") UUID id);

    @Modifying
    @Query("update Order o set o.status = 'EXPIRED' where o.createdAt < :cutoff")
    int expireOlderThan(@Param("cutoff") Instant cutoff);
}

Repository methods are transactional by default (read-only for reads), and @Repository semantics give exception translation into DataAccessException. Since Spring Data 3 the entity id type and JpaRepository replace the older PagingAndSortingRepository plus CrudRepository combination, and ListCrudRepository exists for callers that prefer List to Iterable.

20

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring Data JPA repositories?

Apply. In an e-commerce back end, each aggregate (Order, Customer) gets one repository; line items are reached through the aggregate rather than through their own repository. Reads that feed list screens use interface projections and Page with a capped page size, never full entities. Hot queries are written explicitly with @Query and join fetch so their SQL is reviewable, and a custom fragment interface holds the one Criteria query the name grammar cannot express.

Test. @DataJpaTest with @Testcontainers PostgreSQL (and @AutoConfigureTestDatabase(replace = NONE)) runs each query against the real dialect; H2 hides differences in ILIKE, jsonb and sequence behaviour. Tests assert both results and, for critical paths, the statement count via Hibernate’s Statistics or a datasource proxy. Flyway migrations run in the same test so the schema matches production.

Troubleshoot. LazyInitializationException after a repository call means the entity was touched outside a transaction; the fix is a fetch join or a projection, not spring.jpa.open-in-view=true. A derived query that fails at startup with No property 'custmer' found is a method-name typo. Slow endpoints are diagnosed by enabling spring.jpa.show-sql=false but logging.level.org.hibernate.SQL=DEBUG plus org.hibernate.orm.jdbc.bind=TRACE, which surfaces repeated or unbounded queries. @Modifying queries leaving stale objects in the persistence context need clearAutomatically = true.

Important consideration: repositories make queries easy to write, which also makes them easy to multiply; every method should be justified by a real use case and its SQL inspected once.

21

Explain Hibernate lazy and eager loading in the context of Spring / Spring Boot.

Fetch type decides when an association is loaded. Eager loading retrieves the related rows together with the owning entity, typically via a join or an immediate secondary query. Lazy loading defers it: Hibernate injects a proxy or a PersistentCollection, and the SQL runs only when the association is first accessed, which requires an open Session.

JPA defaults are LAZY for @OneToMany and @ManyToMany, EAGER for @ManyToOne and @OneToOne. The eager default on @ManyToOne is the one most teams override, because every load of a child drags in its parent chain.

@Entity
class OrderLine {
    @ManyToOne(fetch = FetchType.LAZY)   // override the EAGER default
    @JoinColumn(name = "order_id")
    private Order order;
}

Lazy loading in a Spring Boot web application is complicated by spring.jpa.open-in-view, which defaults to true and keeps the EntityManager open for the entire HTTP request. That hides LazyInitializationException at the cost of holding a database connection while the view or JSON is rendered; Boot logs a warning at startup for exactly this reason.

The sound approach is: default everything to lazy, then state the required fetch plan per use case with join fetch, @EntityGraph, or a DTO projection, so each query loads precisely what that screen needs and nothing more.

22

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Hibernate lazy and eager loading?

Apply. In an order-management service every association is LAZY, including @ManyToOne, and spring.jpa.open-in-view=false is set on day one so lazy access outside a transaction fails in development instead of production. Each read use case declares its fetch plan: the order detail page uses @EntityGraph(attributePaths = {"lines", "lines.product"}), the order list uses a projection with no associations, and the fulfilment batch uses a join fetch query with a Pageable. Collections that can grow unbounded (audit events) are never mapped as @OneToMany at all; they get their own repository.

Test. @DataJpaTest cases call a repository method, then detach the entity with entityManager.clear() and access the expected associations; a LazyInitializationException reveals a missing fetch path. Hibernate Statistics (hibernate.generate_statistics=true in the test profile) asserts getPrepareStatementCount() equals the expected number.

Troubleshoot. The two production symptoms are LazyInitializationException: could not initialize proxy - no Session in a JSON response, and connection-pool exhaustion when open-in-view keeps connections busy during slow serialisation. For the first I find the access point in the stack trace and add the association to that query’s fetch plan. For the second, Hikari’s leakDetectionThreshold and the hikaricp.connections.pending metric confirm connections are held through rendering, and disabling open-in-view plus explicit fetching resolves it.

Important consideration: join fetch on two collections in one query produces a Cartesian product; use @BatchSize or a second query for the additional collection.

23

Explain N+1 queries in the context of Spring / Spring Boot.

An N+1 problem occurs when loading a list of N parent entities triggers one additional query per parent to fetch an association, giving N+1 round trips instead of one or two. With Hibernate it arises whenever a lazy association is accessed inside a loop, or an eager @ManyToOne is resolved with a secondary select for each row.

List<Order> orders = orderRepository.findAll();          // 1 query
for (Order o : orders) {
    total += o.getLines().size();                       // N more queries
}

The resulting SQL log shows one select ... from orders followed by hundreds of select ... from order_line where order_id = ?. The latency is proportional to list size, so it is often invisible in development with ten rows and crippling in production with ten thousand.

Remedies, in order of preference:

  • Fetch join (@Query("select o from Order o join fetch o.lines")) or @EntityGraph to load parents and children in one statement.
  • A DTO projection that selects only the needed columns and skips entity graphs entirely.
  • @BatchSize(size = 50) on the association or hibernate.default_batch_fetch_size, which turns N queries into N/50 IN queries while keeping lazy semantics.
  • Hibernate 6’s @Fetch(FetchMode.SUBSELECT) to load all children with one subquery.

The N+1 pattern is a consequence of the per-entity loading model, not a bug; the mapping simply needs a fetch plan that matches the access pattern.

24

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot N+1 queries?

Apply. For a catalogue service listing products with their category and price tiers, the list endpoint uses a projection query returning exactly the columns the grid shows, which cannot produce N+1 because no entity graph exists. The detail endpoint uses an @EntityGraph for the two associations it renders. Globally, spring.jpa.properties.hibernate.default_batch_fetch_size=50 acts as a safety net so an unplanned lazy access costs a handful of IN queries rather than hundreds.

Test. A repository test wraps the call in Hibernate Statistics and asserts the prepared-statement count, failing the build if a future mapping change reintroduces the pattern. For the full stack, a @SpringBootTest with a datasource proxy (datasource-proxy or p6spy) counts statements per request; a lightweight alternative is a Testcontainers Postgres with log_statement=all and a grep in the test.

Statistics stats = entityManagerFactory.unwrap(SessionFactory.class)
                                       .getStatistics();
stats.clear();
List<ProductView> page = productRepository.findCatalogPage(PageRequest.of(0, 50));
assertThat(stats.getPrepareStatementCount()).isEqualTo(1L);

Troubleshoot. In production the tell-tale is an endpoint whose p99 latency scales with result size while the database reports many tiny identical queries; pg_stat_statements ordered by calls or APM span lists exposes them instantly. Enabling logging.level.org.hibernate.SQL=DEBUG on one instance reproduces the pattern. The fix is a fetch join or projection on the specific query; occasionally the real culprit is toString() or Jackson serialising a lazy collection.

Important consideration: making the association EAGER does not fix N+1 reliably, since Hibernate may still issue secondary selects, and it penalises every other query that loads the same entity.

25

Explain transactional propagation in the context of Spring / Spring Boot.

Propagation defines how a @Transactional method behaves when a transaction is already in progress on the calling thread. Spring implements it in TransactionInterceptor, which wraps the bean in a proxy and consults the PlatformTransactionManager before invoking the method.

PropagationExisting transactionNo transaction
REQUIRED (default)Join itStart a new one
REQUIRES_NEWSuspend it, start an independent oneStart a new one
SUPPORTSJoin itRun non-transactionally
MANDATORYJoin itThrow exception
NOT_SUPPORTEDSuspend it, run withoutRun non-transactionally
NEVERThrow exceptionRun non-transactionally
NESTEDCreate a JDBC savepointStart a new one

The diagram contrasts REQUIRED and REQUIRES_NEW for an inner call.

Diagram: capture() TX1 begins, ledger.post() REQUIRED, audit.record() REQUIRES_NEW, joins TX1, TX1 suspended TX2 commits, exception TX1 rolls back

With REQUIRED, an inner method that throws a RuntimeException marks the shared transaction rollback-only even if the outer method catches the exception, which surfaces as UnexpectedRollbackException at commit. REQUIRES_NEW isolates the inner work (an audit record that must persist even when the business operation fails) but needs a second connection from the pool. NESTED rolls back only to the savepoint and is supported by DataSourceTransactionManager but not by JPA.

Because propagation is enforced by the proxy, a call from one method to another inside the same bean bypasses it entirely; the inner annotation is ignored. Only public methods on Spring-managed beans invoked through the proxy are intercepted (Spring 6 also allows protected and package-private methods with class-based proxies, but self-invocation remains unproxied).

26

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot transactional propagation?

Apply. In a payment-capture flow, PaymentService.capture() is REQUIRED and spans ledger update, order status change and outbox insert, so they commit or roll back together. AuditService.record() is REQUIRES_NEW because compliance needs the attempt logged even when capture fails. A read-heavy reporting query uses @Transactional(readOnly = true), which lets Hibernate skip dirty checking and the driver route to a replica. Methods that must only run inside a caller’s transaction, such as outbox writers, are MANDATORY to catch misuse early.

Test. @SpringBootTest with Testcontainers runs the real transaction manager. One test forces the inner step to throw and asserts the ledger row was rolled back while the audit row survived. TransactionSynchronizationManager.isActualTransactionActive() and getCurrentTransactionName() are asserted inside a test-only aspect to prove the expected boundaries. Test methods annotated @Transactional roll back automatically, which is convenient but hides commit-time failures, so a few tests use TestTransaction.end() to commit for real.

Troubleshoot. UnexpectedRollbackException means an inner REQUIRED method threw and was caught; either let it propagate or give the inner method REQUIRES_NEW. Changes that never persist while no error appears are usually self-invocation (this.save() bypasses the proxy) or a checked exception, which Spring does not roll back on by default without rollbackFor. Pool exhaustion under load with REQUIRES_NEW is expected arithmetic: each nested transaction holds a second connection. Setting logging.level.org.springframework.transaction.interceptor=TRACE prints every “Getting transaction for” and “Completing transaction for” line.

Important consideration: long REQUIRED transactions that include remote HTTP calls hold locks and connections for the duration of the network round trip; move external calls outside the boundary or use an outbox.

27

Explain transaction isolation in the context of Spring / Spring Boot.

Isolation defines what a transaction may see of other transactions’ uncommitted or concurrently committed changes. Spring exposes it through @Transactional(isolation = ...), which the transaction manager translates into Connection.setTransactionIsolation() on the JDBC connection at the start of the transaction. Isolation.DEFAULT uses whatever the database defaults to, which is READ_COMMITTED on PostgreSQL and Oracle and REPEATABLE_READ on MySQL InnoDB.

LevelPreventsStill allows
READ_UNCOMMITTEDNothingDirty, non-repeatable, phantom reads
READ_COMMITTEDDirty readsNon-repeatable and phantom reads
REPEATABLE_READDirty and non-repeatable readsPhantom reads (DB-dependent)
SERIALIZABLEAll anomaliesNothing; may abort with serialization failures

Isolation is a per-transaction property, so Spring applies the requested level only when it actually starts the transaction; a REQUIRED method joining an existing transaction cannot change the level, and Spring ignores the mismatch unless validateExistingTransaction is enabled on the transaction manager. Higher levels cost more locking or more aborted transactions, and the exact semantics differ by engine: PostgreSQL implements REPEATABLE_READ with snapshots and no phantoms, while SQL Server uses range locks.

Most Spring applications stay on READ_COMMITTED and handle the remaining anomalies in application terms, through @Version optimistic locking on JPA entities or SELECT ... FOR UPDATE via @Lock(LockModeType.PESSIMISTIC_WRITE) on a repository method, rather than raising the global level.

28

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot transaction isolation?

Apply. An inventory service on PostgreSQL runs at READ_COMMITTED by default. Stock reservation, which must not oversell, uses a repository method with @Lock(LockModeType.PESSIMISTIC_WRITE) so the row is locked within the REQUIRED transaction; concurrent reservers queue on the row rather than both reading the same quantity. Customer-profile updates, where conflicts are rare, use @Version and surface ObjectOptimisticLockingFailureException as a 409 for the client to retry. Month-end financial reconciliation runs in a dedicated @Transactional(isolation = SERIALIZABLE, readOnly = true) method so its totals come from a consistent snapshot.

Test. Concurrency is tested with Testcontainers Postgres and two threads coordinated by a CountDownLatch: both read stock 1, both try to reserve, and the test asserts exactly one succeeds. A second test asserts the optimistic-lock path throws on a stale version. For the serializable report, a test commits an insert midway and asserts the report total does not change.

Troubleshoot. Oversold stock in production with no errors points to a missing lock and plain READ_COMMITTED reads. CannotAcquireLockException or could not serialize access under SERIALIZABLE are expected and should be retried with Spring Retry or a small loop, not treated as bugs. Deadlocks show up in PostgreSQL logs with both statements; ordering updates consistently fixes them. An isolation annotation that appears to have no effect usually sits on a method that joined an outer transaction.

Important consideration: locks held across an external HTTP call inside the transaction turn a correct isolation strategy into a throughput bottleneck.

29

Explain Spring Security filter chain in the context of Spring / Spring Boot.

Spring Security plugs into the servlet container as a single filter, DelegatingFilterProxy, registered as springSecurityFilterChain. It delegates to FilterChainProxy, which holds one or more SecurityFilterChain beans; the first chain whose request matcher accepts the request handles it, and its ordered list of filters runs before the request reaches DispatcherServlet.

Typical filters in order: SecurityContextHolderFilter (loads the context), CsrfFilter, LogoutFilter, authentication filters such as BearerTokenAuthenticationFilter or UsernamePasswordAuthenticationFilter, ExceptionTranslationFilter (turns AuthenticationException into a 401 and AccessDeniedException into a 403), and finally AuthorizationFilter, which evaluates the authorizeHttpRequests rules. This diagram shows the path of a request.

Diagram: HTTP request, DelegatingFilterProxy, FilterChainProxy, SecurityContext filter, Authentication filter, ExceptionTranslation filter, …

Since Spring Security 5.7 and throughout 6.x, configuration is a @Bean SecurityFilterChain built from HttpSecurity with lambda DSL; WebSecurityConfigurerAdapter is gone in 6. Multiple chains with securityMatcher("/api/**") let an application serve stateless JWT APIs and a session-based admin UI side by side. Custom filters are inserted with addFilterBefore or addFilterAfter relative to a known filter class.

30

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring Security filter chain?

Apply. A customer-facing service exposes two chains. The @Order(1) chain matches /api/**, is stateless (SessionCreationPolicy.STATELESS), disables CSRF, validates bearer JWTs, and permits only /api/public/** anonymously. The @Order(2) chain covers the operator UI with form login, CSRF enabled, and hasRole("OPS"). A custom TenantContextFilter is added after BearerTokenAuthenticationFilter to copy the tenant claim into an MDC key. Actuator health is permitted, everything else under /actuator requires ACTUATOR authority.

Test. @WebMvcTest with spring-security-test uses @WithMockUser(roles = "OPS") and .with(jwt().authorities(...)) request post-processors to check 200, 401 and 403 outcomes per endpoint, including a CSRF-less POST to the UI chain returning 403. A @SpringBootTest(webEnvironment = RANDOM_PORT) test walks the real filter chain with TestRestTemplate and a locally minted token. An authorization matrix test iterates endpoints and roles so a new controller cannot ship unprotected.

Troubleshoot. A 401 on a public endpoint usually means the wrong chain matched because securityMatcher was omitted and the first chain claimed everything. Setting logging.level.org.springframework.security=TRACE prints which chain was selected and each filter invoked. A 403 on POST with valid credentials is nearly always CSRF on a chain that should be stateless. Custom filters that execute twice were registered both as a @Component (auto-registered by Boot) and via addFilterBefore; the fix is a FilterRegistrationBean with setEnabled(false) or dropping the stereotype.

Important consideration: permitAll() on a path still runs the whole chain, so an invalid token on a public endpoint produces 401 unless the chain is excluded for that path.

31

Explain JWT OAuth2 authorization in the context of Spring / Spring Boot.

OAuth 2.0 separates roles: a client obtains an access token from an authorization server (Keycloak, Auth0, Entra ID, Spring Authorization Server) and presents it to a resource server, which validates it and enforces scopes. When the token is a JWT, the resource server can verify the signature locally using the issuer’s public keys (JWKS) and read claims such as sub, scope, exp and aud without a network call per request.

Spring Boot supports this through spring-boot-starter-oauth2-resource-server. Setting spring.security.oauth2.resourceserver.jwt.issuer-uri makes Boot fetch the OpenID discovery document, configure a JwtDecoder with the JWKS endpoint, and validate issuer and expiry automatically. BearerTokenAuthenticationFilter extracts the token, the decoder validates it, and JwtAuthenticationConverter maps scope claims to SCOPE_xxx authorities.

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http.securityMatcher("/api/**")
        .authorizeHttpRequests(a -> a
            .requestMatchers(HttpMethod.GET, "/api/orders/**")
                .hasAuthority("SCOPE_orders:read")
            .anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
        .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
        .csrf(c -> c.disable());
    return http.build();
}

Method-level rules complement URL rules: @PreAuthorize("hasAuthority('SCOPE_orders:write') and #id == authentication.name") combines scope with ownership. Opaque tokens are an alternative validated via introspection; spring-boot-starter-oauth2-client covers the other side, where the application is the client obtaining tokens.

32

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot JWT OAuth2 authorization?

Apply. An order API trusts a Keycloak realm via issuer-uri. A custom JwtAuthenticationConverter maps the realm’s roles claim to ROLE_ authorities alongside scopes, and an audience validator (JwtValidators.createDefaultWithIssuer plus a JwtClaimValidator for aud) rejects tokens minted for other services. Service-to-service calls use client-credentials tokens obtained by OAuth2AuthorizedClientManager and attached to RestClient requests. Token lifetimes stay short (five minutes) and revocation is handled at the authorization server.

Test. @WebMvcTest uses jwt().jwt(j -> j.claim("scope", "orders:read")) from spring-security-test so no real tokens are needed. An integration test runs Keycloak in Testcontainers, obtains a real token with the password or client-credentials grant, and calls the API through TestRestTemplate, which proves discovery, JWKS retrieval and claim mapping end to end. Negative tests cover expired tokens, wrong audience and a token signed with an unknown key.

Troubleshoot. 401 invalid_token with WWW-Authenticate naming the cause is the first stop: “The iss claim is not valid” means the token’s issuer URL differs from the configured one, often http versus https or a trailing slash behind a proxy. A 403 with a valid token means the authorities mapping is wrong; logging authentication.getAuthorities() once shows whether scopes arrived as SCOPE_ or roles were not mapped. Startup failure fetching the discovery document indicates the issuer is unreachable; jwk-set-uri can be set explicitly to avoid the startup call. Clock skew between pods and the issuer causes intermittent exp failures.

Important consideration: JWT validation is only as strong as key management, so JWKS caching and key rotation at the issuer must be tested, not assumed.

33

Explain caching abstraction in the context of Spring / Spring Boot.

Spring’s caching abstraction adds declarative caching to methods through annotations, independent of the underlying store. @EnableCaching activates an AOP interceptor; @Cacheable returns a stored value instead of invoking the method when the key is present, @CachePut always invokes and stores, @CacheEvict removes entries, and @Caching groups several of these. Keys default to the method parameters and can be customised with SpEL (key = "#customerId") or a KeyGenerator.

@Service
public class ProductService {
    @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
    public ProductView byId(UUID id) { return load(id); }

    @CacheEvict(cacheNames = "products", key = "#product.id")
    public void update(Product product) { save(product); }
}

The CacheManager decides where entries live. Boot auto-configures one based on the classpath: ConcurrentMapCacheManager as a fallback, Caffeine for a local in-process cache with size and TTL policies, or Redis for a shared cache across instances via spring-boot-starter-data-redis. The spring.cache.type property forces a choice, and spring.cache.cache-names plus spring.cache.caffeine.spec configure it without code.

Because caching is proxy-based, self-invocation within the same bean bypasses it, and the method must be public. sync = true on @Cacheable prevents a stampede by letting one thread compute while others wait, where the provider supports it.

34

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot caching abstraction?

Apply. A product-catalogue service caches ProductView DTOs, never JPA entities, so lazy proxies and detached-state problems cannot leak into the cache. A two-level setup uses Caffeine (maximumSize=10000,expireAfterWrite=5m) for the hot path and Redis for cross-instance sharing of pricing rules that change daily. Writes go through @CacheEvict on the same keys, and bulk imports call @CacheEvict(allEntries = true). Each cache has an explicit TTL; nothing is cached for ever. Values stored in Redis are serialised as JSON with GenericJackson2JsonRedisSerializer so deployments with changed classes do not fail on deserialisation.

Test. A @SpringBootTest with the real CacheManager calls the service twice with a @MockitoBean repository and verifies the repository was invoked once; a second test updates the product and asserts the next read hits the repository again. Redis-backed caches run against a Testcontainers Redis. Micrometer’s cache.gets hit and miss counters are asserted in a load test to show the hit ratio stays above the target.

Troubleshoot. Stale data after an update means the evict key does not match the cacheable key; logging logging.level.org.springframework.cache=TRACE shows the computed keys. No caching at all is usually self-invocation or a missing @EnableCaching. Memory pressure in the JVM points to a Caffeine cache without maximumSize. Redis SerializationException after a deploy means the stored class changed; versioning cache names (products-v2) sidesteps it. A thundering herd on cache expiry is handled with sync = true or staggered TTLs.

Important consideration: caching hides the cost of slow queries rather than fixing them, so the underlying query is still worth optimising before the cache is added.

35

Explain Spring AOP proxies in the context of Spring / Spring Boot.

Spring applies cross-cutting behaviour (@Transactional, @Cacheable, @Async, @PreAuthorize, custom @Aspect advice) by wrapping a bean in a proxy. The container injects the proxy wherever the bean is requested; callers invoke the proxy, which runs the advice chain and then delegates to the real object. Nothing changes in the target class’s bytecode.

Two proxy kinds exist. JDK dynamic proxies implement the bean’s interfaces and work only when callers depend on the interface. CGLIB proxies subclass the target class, so they work with concrete types but cannot intercept final methods or final classes, and the class needs a visible constructor. Spring Boot defaults to CGLIB (spring.aop.proxy-target-class=true) for exactly that reason. The diagram shows the call path.

Diagram: Controller, CGLIB proxy OrderService$$, TransactionInterceptor, CacheInterceptor, OrderService (real bean), bypasses proxy, this.helper()

The main consequence is self-invocation: a call from one method to another inside the same bean goes through this, not the proxy, so the inner method’s @Transactional or @Cacheable is ignored. Workarounds are moving the method to another bean, injecting the bean into itself via ObjectProvider, or using AspectJ compile-time weaving. Proxies also explain why getClass() returns OrderService$$SpringCGLIB$$0 and why @Autowired by concrete class can fail when a JDK proxy is in play.

36

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring AOP proxies?

Apply. Beyond the framework’s own annotations, I write a small number of aspects: a @Timed -style @Around advice on @Service methods that records Micrometer timers with method tags, and an @AfterThrowing aspect on repository ports that enriches exceptions with the tenant id. Pointcuts target annotations rather than package patterns so adding behaviour is an explicit opt-in. Classes meant to be proxied are kept non-final with their transactional methods public, and service-to-service calls always go through injected dependencies, never this.

Test. AopTestUtils.getTargetObject(bean) and AopUtils.isAopProxy(bean) in a context test assert that the expected beans are proxied. The aspect itself is unit-tested with AspectJProxyFactory, which builds a proxy around a plain object and the aspect without a Spring context. A @SpringBootTest with @MockitoBean MeterRegistry verifies the timer is recorded with the correct tags on one representative call.

AspectJProxyFactory factory = new AspectJProxyFactory(new OrderService(repo));
factory.addAspect(new TimingAspect(registry));
OrderService proxied = factory.getProxy();
proxied.place(request);
assertThat(registry.get("service.calls").timer().count()).isEqualTo(1);

Troubleshoot. Advice that never fires is diagnosed by checking three things: is the method public, is it called through the proxy rather than this, and does the pointcut actually match (a quick @Pointcut test with AspectJExpressionPointcut.matches() settles it). BeanNotOfRequiredTypeException saying a bean is a $Proxy means a JDK proxy is injected into a field typed with the concrete class; depend on the interface or force CGLIB. Unexpectedly slow startup or IllegalArgumentException: Cannot subclass final class signals a final service class.

Important consideration: every proxied call adds reflection overhead and a deeper stack, so aspects belong on coarse-grained service methods, not on hot inner loops or entity getters.

37

Explain circular dependencies in the context of Spring / Spring Boot.

A circular dependency exists when bean A needs bean B and B needs A, directly or through a longer chain. With constructor injection the container cannot resolve it: to construct A it needs a finished B, which needs a finished A. Spring reports BeanCurrentlyInCreationException wrapped in the message “The dependencies of some of the beans in the application context form a cycle” and lists the ring.

Field and setter injection can break the deadlock because Spring instantiates A first, registers an early reference, then injects it into B. Spring Boot 2.6 disabled this behaviour by default (spring.main.allow-circular-references=false), so a cycle now fails at startup regardless of injection style unless the flag is flipped back on.

@Service
class OrderService {
    OrderService(InvoiceService invoices) { ... }   // needs InvoiceService
}
@Service
class InvoiceService {
    InvoiceService(OrderService orders) { ... }     // needs OrderService: cycle
}

Legitimate fixes, in order of preference:

  • Extract the shared behaviour into a third bean both depend on, which usually exposes a missing abstraction.
  • Invert one direction with events (ApplicationEventPublisher) so InvoiceService reacts to OrderPlaced instead of being called.
  • Inject ObjectProvider<InvoiceService> or mark one parameter @Lazy, which injects a proxy resolved on first use.

A cycle is almost always a design signal that two classes share a responsibility; the @Lazy escape hatch should be the exception, not the habit.

38

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot circular dependencies?

Apply. The team rule is constructor injection everywhere and allow-circular-references left at its default false, so cycles fail in the first local run rather than hiding behind field injection. Layering is enforced: web depends on application, which depends on domain; two application services never call each other directly. When OrderService and InvoiceService genuinely need to coordinate, OrderService publishes OrderPlacedEvent and InvoiceService has a @TransactionalEventListener, which also decouples transaction boundaries. The one accepted @Lazy in the codebase is documented with a comment explaining why.

Test. The plain contextLoads() test catches any cycle immediately, since Boot refuses to start. ArchUnit’s slices().matching("..application.(*)..").should().beFreeOfCycles() runs in CI and fails on package-level cycles before they turn into bean cycles. A @DataJpaTest and a @WebMvcTest slice per module prove each layer can start without the others.

Troubleshoot. The startup failure report prints the ring in order (orderService -> invoiceService -> orderService), which identifies the participants. If the cycle appears only after adding an aspect or @Transactional, the cause is often a BeanPostProcessor or a configuration class that injects a bean it also produces; moving the @Bean method to its own configuration class resolves it. @Lazy cycles that compile and start but throw BeanCurrentlyInCreationException at the first request usually involve a prototype or request scope that cannot be proxied lazily. Cycles through @Configuration classes injecting each other are fixed by injecting the needed bean into the @Bean method parameter instead of the class.

Important consideration: re-enabling spring.main.allow-circular-references=true to make an upgrade pass hides a design problem and makes bean initialisation order fragile; treat it as a temporary bridge with a ticket to remove it.

39

Explain Spring Actuator metrics in the context of Spring / Spring Boot.

Spring Boot Actuator exposes operational endpoints over HTTP or JMX: health, info, metrics, prometheus, env, loggers, threaddump, conditions and others. Metrics are built on Micrometer, a vendor-neutral facade comparable to SLF4J for logging, so the same instrumentation publishes to Prometheus, Datadog, CloudWatch, OTLP or Dynatrace depending on which registry dependency is present.

Boot auto-instruments a wide set of meters: JVM memory and GC, CPU and uptime, HikariCP pool state, HTTP server requests (http.server.requests timer with uri, status, method, exception tags), RestClient / WebClient calls, Spring Data repository invocations, cache hits and misses, Kafka and RabbitMQ clients, and Tomcat threads. Custom meters are registered through the injected MeterRegistry.

@Component
class OrderMetrics {
    private final Counter placed;
    OrderMetrics(MeterRegistry registry) {
        placed = Counter.builder("orders.placed")
                        .tag("channel", "web")
                        .register(registry);
    }
    void onPlaced() { placed.increment(); }
}

The @Timed and @Counted annotations instrument methods via AOP when TimedAspect is a bean, and Observation (Micrometer 1.10+, Boot 3) unifies metrics and tracing so one observe() call produces both a timer and a span. Exposure is controlled with management.endpoints.web.exposure.include; only health is exposed over HTTP by default, and management.server.port can move the endpoints to a separate port that is not reachable from the internet.

Metrics answer “how often and how long”, health answers “can this instance serve traffic”, and the two are deliberately separate endpoints.

40

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot Spring Actuator metrics?

Apply. Every service exposes health,info,prometheus,metrics on a separate management port (management.server.port=9090) that only the cluster network reaches, with the main port carrying no Actuator at all. Common tags (application, region, instance) come from management.metrics.tags.* so dashboards aggregate correctly. Business metrics are few and deliberate: orders.placed counter, payment.latency timer with a provider tag, and a gauge for outbox backlog. High-cardinality values such as order ids never become tags. Percentile histograms are enabled only for http.server.requests and the payment timer, since each adds buckets.

Test. A @SpringBootTest with SimpleMeterRegistry calls the service and asserts registry.get("orders.placed").counter().count() increased, and that the tag set is exactly what the dashboard expects. A smoke test scrapes /actuator/prometheus with TestRestTemplate and checks the custom metric names appear, which catches a registration that silently moved out of a scanned package. Alert rules are tested by a promtool test rules step in CI.

Troubleshoot. A metric missing in Grafana but present locally is usually a registry dependency absent from the production build or management.endpoints.web.exposure.include not listing prometheus. Prometheus memory growth or a too many series warning points to an unbounded tag, and the /actuator/metrics/http.server.requests endpoint shows the offending uri values; @PathVariable templates fix it, and management.metrics.web.server.max-uri-tags caps the damage. Gauges that read zero after a restart were registered with a lambda over an object that was garbage-collected; hold a strong reference.

Important consideration: Actuator endpoints such as env and heapdump leak secrets and memory contents, so exposure must be an explicit allow-list reviewed with security, never *.

41

Explain database migrations Flyway in the context of Spring / Spring Boot.

Flyway versions a database schema with ordered SQL (or Java) migration scripts applied exactly once and tracked in a flyway_schema_history table. Each script is named V<version>__<description>.sql, for example V3__add_order_status_index.sql; on startup Flyway compares the scripts on the classpath with the history table, applies the pending ones in version order inside a transaction where the database allows, and records checksum, execution time and success.

The startup sequence looks like this.

Diagram: Boot startup, DataSource, flyway_schema_history, classpath:db/migration, Flyway bean, Apply pending V8, V9, JPA / Hibernate validate

Spring Boot integrates it through spring-boot-starter-flyway (Boot 4) or the org.flywaydb:flyway-core dependency plus the database-specific module such as flyway-database-postgresql (Boot 3.x). Boot auto-configures a Flyway bean against the application DataSource, runs the migration before JPA initialises so Hibernate sees the final schema, and reads scripts from classpath:db/migration. Key properties: spring.flyway.locations, spring.flyway.baseline-on-migrate for adopting an existing database, and spring.flyway.validate-on-migrate, which refuses to start if an applied script’s checksum changed.

-- V7__orders_add_fulfilled_at.sql
ALTER TABLE orders ADD COLUMN fulfilled_at TIMESTAMPTZ;
CREATE INDEX CONCURRENTLY idx_orders_fulfilled_at ON orders (fulfilled_at);

Repeatable migrations (R__refresh_views.sql) rerun whenever their checksum changes and suit views and functions. With Flyway managing the schema, spring.jpa.hibernate.ddl-auto must be validate or none; letting Hibernate generate DDL alongside Flyway produces conflicting ownership. Liquibase is the equivalent alternative with XML/YAML changelogs and built-in rollback support, which Flyway offers only in its paid editions.

42

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot database migrations Flyway?

Apply. Migrations live in the service repository under db/migration, reviewed like code. Each is small, forward-only and backward compatible with the currently deployed version so rolling deployments survive: add a nullable column, deploy code that writes both, backfill in a separate V script with batched UPDATEs, then drop the old column two releases later. Production runs migrations as a Kubernetes init container or a dedicated job (flyway migrate via the CLI with the same scripts), not inside every replica’s startup, and spring.flyway.enabled=false on the application pods avoids races. CREATE INDEX CONCURRENTLY scripts are marked non-transactional with --flyway:executeInTransaction=false.

Test. @DataJpaTest and @SpringBootTest run against Testcontainers PostgreSQL with Flyway enabled and ddl-auto=validate, so every test proves scripts apply from empty and that the JPA mappings match the resulting schema. A CI job restores an anonymised production snapshot and runs flyway migrate plus flyway validate to time long migrations before release.

Troubleshoot. Validate failed: Migration checksum mismatch means an applied script was edited; the fix is a new script, or flyway repair when the edit was cosmetic and deliberate. Found non-empty schema without schema history table on a legacy database calls for baseline-on-migrate=true with baseline-version set to the current state. A migration that failed mid-way on MySQL (no transactional DDL) leaves a failed row that repair must clear after manual cleanup. Two developers producing V12 on parallel branches is caught by spring.flyway.out-of-order=false and resolved by renumbering before merge.

Important consideration: a migration holding an ACCESS EXCLUSIVE lock on a large table blocks the whole application, so lock_timeout and batched changes belong in every production script.

43

Explain testing MockMvc in the context of Spring / Spring Boot.

MockMvc tests Spring MVC controllers by driving DispatcherServlet directly, without starting a servlet container or opening a port. Requests are built with MockMvcRequestBuilders, pass through the real HandlerMapping, argument resolvers, message converters, validation, @ControllerAdvice and (if included) the Spring Security filter chain, and the response is checked with ResultMatchers such as status(), jsonPath() and header().

The diagram shows what a MockMvc request passes through and what it skips.

Diagram: Test mvc.perform(), Tomcat / socket skipped, Security filter chain, DispatcherServlet, Controller, exception, @ControllerAdvice, …

Boot’s @WebMvcTest(OrderController.class) loads only the web slice: controllers, advice, converters, WebMvcConfigurer beans and security configuration, while services and repositories are replaced with @MockitoBean doubles. The result is a context that starts in a second and tests the HTTP contract in isolation.

@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mvc;
    @MockitoBean OrderService service;

    @Test
    void returns404WhenMissing() throws Exception {
        given(service.find(ID)).willThrow(new OrderNotFoundException(ID));
        mvc.perform(get("/api/orders/{id}", ID).accept(APPLICATION_JSON))
           .andExpect(status().isNotFound())
           .andExpect(jsonPath("$.title").value("Not Found"));
    }
}

MockMvc can also be obtained in a full @SpringBootTest with @AutoConfigureMockMvc, keeping real services but still skipping the network. Spring Framework 6.2 added MockMvcTester, an AssertJ-style fluent API over the same engine. Because no real server is involved, aspects of the container such as HTTP compression, servlet filters registered by Boot outside the MVC chain, and actual serialisation over the wire are not exercised; TestRestTemplate or WebTestClient against RANDOM_PORT covers those.

44

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot testing MockMvc?

Apply. The test pyramid for an order API puts one @WebMvcTest class per controller covering every route: happy path, validation failure, not-found, forbidden, and content negotiation. @Import(ApiExceptionHandler.class) and @Import(SecurityConfig.class) ensure the real advice and security rules participate, with @WithMockUser or jwt() post-processors supplying identity. Request bodies come from small JSON fixtures or ObjectMapper.writeValueAsString(record) so field names are checked against the real serialiser. A handful of @SpringBootTest + @AutoConfigureMockMvc tests exercise controller-to-database flows with Testcontainers.

Test. The tests themselves are the point, so the emphasis is on assertions that catch regressions: exact status codes, content().contentType(APPLICATION_PROBLEM_JSON), jsonPath("$.errors.length()"), response headers such as Location, and verify(service).place(argThat(...)) to confirm the controller translated the DTO correctly. andDo(print()) is used only while debugging and removed before commit to keep CI logs readable.

Troubleshoot. A slice test that fails to start because it wants a DataSource or a repository means a web-layer class injects infrastructure directly; @MockitoBean the dependency or, better, refactor. A 401 in a test that expected 200 means SecurityConfig was imported but no identity was supplied. jsonPath failing with “No value” while the body looks right is usually a @JsonProperty or snake-case naming strategy difference between test expectation and production ObjectMapper; the slice uses the real Boot-configured mapper, so the fix is in the expectation. Tests passing locally and failing in CI often depend on the JVM default Locale or time zone in date formatting.

Important consideration: MockMvc cannot see behaviour that lives in the servlet container, so at least one real-port test per deployable keeps TLS, compression and filter order honest.

45

Explain WebFlux versus MVC in the context of Spring / Spring Boot.

Spring MVC is the servlet-based, blocking web stack: one thread per request, synchronous controllers, RestClient / RestTemplate for outbound calls, JDBC and JPA underneath. Spring WebFlux is the reactive stack built on Project Reactor and a non-blocking runtime (Netty by default): a small event-loop thread pool serves many connections, controllers return Mono and Flux, and I/O must be non-blocking end to end (WebClient, R2DBC, reactive Redis or Mongo drivers).

AspectSpring MVCSpring WebFlux
Concurrency modelThread per requestEvent loop, non-blocking
Return typesObjects, ResponseEntityMono<T>, Flux<T>
Data accessJDBC, JPA, blocking clientsR2DBC, reactive drivers
DebuggabilityPlain stack tracesAssembly traces, operator chains
Best fitCRUD services, JPA-heavy appsStreaming, high fan-out gateways

The annotation model is almost identical (@RestController, @GetMapping), and WebFlux adds functional routing (RouterFunction). Both stacks are first-class in Boot 3; Boot chooses MVC when spring-boot-starter-web is present and WebFlux when only spring-boot-starter-webflux is.

Java 21 virtual threads change the calculation. With spring.threads.virtual.enabled=true (Boot 3.2+), MVC keeps its simple blocking code yet no longer ties up platform threads while waiting on I/O, which removes most of the scalability argument for WebFlux in ordinary services. WebFlux still wins for true streaming (server-sent events, backpressure over Kafka), for gateways built on Spring Cloud Gateway, and when the whole chain is already reactive.

46

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot WebFlux versus MVC?

Apply. The default for a new service with a relational database is MVC with virtual threads enabled: JPA, Flyway and RestClient work unchanged and the team debugs ordinary stack traces. The API gateway and a notification fan-out service that holds thousands of SSE connections are WebFlux, with WebClient and reactive Redis so no blocking call enters the event loop. The two never mix inside one deployable; where a WebFlux service must call a blocking library, the call is wrapped in Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()).

Test. MVC controllers use MockMvc; WebFlux controllers use WebTestClient bound to the RouterFunction or the application context, with StepVerifier for service-level Flux logic including expectNextCount and virtual time for retries. A Gatling load test compares p99 latency and thread count for both implementations before a stack decision is made, since the choice should rest on measured behaviour rather than fashion. BlockHound runs in the WebFlux test suite to fail on any blocking call detected on a non-blocking thread.

Troubleshoot. A WebFlux service that stalls under load with a few busy threads is blocking on the event loop: a thread dump shows reactor-http-nio-* threads inside JDBC or Thread.sleep, and BlockHound names the call site. A Mono that “never runs” was never subscribed; returning it from the controller or chaining it fixes the lost subscription. In MVC with virtual threads, a pinned carrier thread (synchronized around I/O, common in older JDBC drivers before Java 24) shows up through -Djdk.tracePinnedThreads=full. Confusing errors such as “No qualifying bean of type WebTestClient” come from having both starters on the classpath, which makes Boot default to MVC.

Important consideration: reactive code is only as non-blocking as its weakest dependency, so one blocking driver negates the entire stack’s benefit.

47

Explain async jobs and scheduling in the context of Spring / Spring Boot.

Spring provides two related facilities. @Async, enabled by @EnableAsync, makes a method run on a separate thread: the proxy submits the call to a TaskExecutor and returns immediately, with void or CompletableFuture<T> as the return type. @Scheduled, enabled by @EnableScheduling, runs a method on a timer defined by fixedRate, fixedDelay, or a cron expression, optionally with zone.

@Component
class ReportJobs {
    @Scheduled(cron = "0 15 2 * * *", zone = "Europe/Berlin")
    void nightlyReconciliation() { reconciler.run(); }

    @Async("emailExecutor")
    CompletableFuture<Void> sendReceipt(UUID orderId) {
        mailer.send(orderId);
        return CompletableFuture.completedFuture(null);
    }
}

Spring Boot auto-configures a ThreadPoolTaskExecutor (applicationTaskExecutor) tuned by spring.task.execution.* and a ThreadPoolTaskScheduler tuned by spring.task.scheduling.*; with spring.threads.virtual.enabled=true on Java 21 both become virtual-thread based. Without Boot, @Async falls back to a SimpleAsyncTaskExecutor that creates a new thread per call, which is a common surprise in plain Spring applications.

Both features are proxy-based, so self-invocation does not run asynchronously. Exceptions from void @Async methods go to an AsyncUncaughtExceptionHandler rather than the caller, and a @Scheduled method that throws is simply logged and rescheduled. Scheduling has no clustering: every instance of a service runs every job, which is where ShedLock, Quartz with a JDBC job store, or Spring Batch with a scheduler enter when exactly-once execution matters.

48

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot async jobs and scheduling?

Apply. In an order service, @Async offloads receipt emails and webhook delivery onto a dedicated, bounded executor (core=4, max=8, queue=500, CallerRunsPolicy) so a slow mail server cannot exhaust the shared pool. @Scheduled drives the outbox publisher every five seconds with fixedDelay, and nightly settlement by cron; both are wrapped in @SchedulerLock from ShedLock with a JDBC lock table so only one of the three replicas runs them. Jobs are idempotent and stateless, reading their work from the database, and each run logs start, duration and processed count with a correlation id. The scheduler pool size is raised from the default of one so a long job cannot delay the outbox.

Test. Unit tests call the job method directly; the schedule is a trigger, not logic. @SpringBootTest with @MockitoBean for the mailer uses Awaitility to assert the asynchronous send occurred within a timeout. For cron expressions, CronExpression.parse(expr).next(LocalDateTime) is asserted against expected instants. A test profile sets spring.task.scheduling.enabled -style custom flags to disable jobs so integration tests are deterministic, and ShedLock is tested with two application contexts contending on one Testcontainers database.

Troubleshoot. A job that “runs twice” is the multi-instance problem; the ShedLock table shows which host held the lock. @Async methods executing synchronously are self-invocation or a missing @EnableAsync. TaskRejectedException means the queue filled; the fix is backpressure or a larger bounded queue, never an unbounded one. Jobs silently stopping are usually a thrown exception in a fixedDelay loop combined with a one-thread scheduler blocked by another job; /actuator/scheduledtasks lists registered tasks and executor metrics show queue depth and active threads.

Important consideration: an @Async call made inside a @Transactional method runs on a different thread and outside the transaction, so it can observe data that has not been committed yet.

49

Explain microservices resilience and retries in the context of Spring / Spring Boot.

Resilience patterns keep a service healthy when its dependencies are slow or failing. In the Spring ecosystem the mainstream implementation is Resilience4j, integrated through Spring Cloud Circuit Breaker or its own resilience4j-spring-boot3 starter, with annotations and properties for each pattern:

  • Timeout (TimeLimiter, or client-level connectTimeout / readTimeout) bounds how long a call may hang.
  • Retry repeats a failed call with exponential backoff and jitter, only for transient errors such as 503 or connection resets, never for 4xx or non-idempotent requests.
  • Circuit breaker tracks failure rate in a sliding window, opens to fail fast, and half-opens to probe recovery.
  • Bulkhead caps concurrent calls per dependency so one slow downstream cannot consume every thread.
  • Fallback returns a cached or degraded response.

This diagram shows the order in which the decorators wrap an outbound call.

Diagram: Order Service, Retry 3 attempts, backoff, Circuit Breaker 50% failure opens, open, Bulkhead max 20 concurrent, Fallback cached stock, …

Spring Retry (@Retryable, @Recover) is an older, retry-only option. Spring Framework 7 and Boot 4 (November 2025) ship a core resilience module with @Retryable and @ConcurrencyLimit enabled by @EnableResilientMethods, which covers retry and bulkhead without a third-party library; circuit breaking still comes from Resilience4j. Retries multiply load on an already struggling dependency, so they are always paired with a breaker and a budget.

50

In a real project using Spring / Spring Boot, how would you apply, test, or troubleshoot microservices resilience and retries?

Apply. The checkout service calls inventory, pricing and payments. Each downstream has its own named Resilience4j instance configured in YAML: inventory gets retry.maxAttempts=3 with exponential backoff on IOException and 503 only, a circuit breaker with a 20-call sliding window and 50 percent threshold, and a fallback that returns the last cached availability flagged as stale. Payments gets no retry (captures are not idempotent unless an Idempotency-Key header is sent, which it is, so one retry is permitted) and a strict 3-second time limiter. RestClient timeouts are set explicitly because the defaults are infinite. Breaker state changes are published as events and logged.

Test. WireMock stubs simulate 503s, delays and connection resets; tests assert the exact number of attempts (verify(3, postRequestedFor(...))), that a 400 is not retried, and that the fallback is returned when the breaker is forced open via circuitBreaker.transitionToOpenState(). A chaos test in staging uses Toxiproxy to add latency to inventory and checks that checkout p99 stays under budget and the breaker opens within the configured window. /actuator/circuitbreakers and /actuator/circuitbreakerevents are checked during the test.

Troubleshoot. A retry storm shows as downstream traffic spiking to three times normal during an incident; the resilience4j.retry.calls metric with kind=failed_with_retry confirms it, and the fix is tighter retry conditions plus a breaker that opens sooner. A breaker that never opens usually has minimumNumberOfCalls higher than the traffic in the window. Fallbacks that throw NoFallbackAvailableException have a method signature mismatch; the fallback must accept the exception type. Duplicate orders after retries mean a missing idempotency key on the downstream.

Important consideration: resilience configuration is per dependency and per operation, not global; one timeout for everything is always wrong for something.

Answers tailored to your resume and job description

Add your resume and the job description in CrackItX's Settings. When the interviewer asks a Spring / Spring Boot question, Claude suggests an answer using your real projects and the role's requirements, in real time.

See pricing →