Senior Spring Boot Interview Questions – Top 20 with Answers

Senior Spring interviews often test whether you can explain framework behavior rather than merely recall annotations. Production-only bean differences, startup ordering, proxy boundaries, and transaction outcomes all require reasoning about what Spring creates, when it creates it, and which object receives a call.

This article frames those issues through Spring Boot auto-configuration, the bean lifecycle, Spring AOP proxy mechanics, and transaction propagation and rollback rules. It focuses on diagnostic techniques and the implementation details that help experienced Java backend developers explain surprising behavior clearly.

All 20 answers below are free. Want the full set, every answer with a worked example?

Java Spring Boot & Microservices Interview Q&A (200 Qs)

Get the guide

Section 1: Auto-Configuration

1. A bean is missing only in production. How would you use ConditionEvaluationReport to explain it?

I would compare the production ConditionEvaluationReport with a working environment and find the auto-configuration whose condition did not match. The report explains both the condition outcome and the reason, such as a missing class, property, bean, resource, or profile, so it turns “the bean is missing” into a specific configuration decision.

The report is especially useful because it shows:

  • The auto-configuration source that would have created the bean.
  • Positive matches and negative matches, including messages from conditions such as @ConditionalOnClass, @ConditionalOnProperty, and @ConditionalOnMissingBean.
  • Unconditional configuration classes and exclusions, which can explain why a configuration was never considered.
  • Differences caused by production-only profiles, environment variables, dependencies, or an earlier user-defined bean.

I would diagnose it in this order:

  1. Enable the Actuator conditions endpoint temporarily, or start with --debug to obtain the condition evaluation delta. Treat that output as sensitive because it can reveal configuration details.
  2. Search for the expected bean type or auto-configuration class, then read the negative outcome and its message.
  3. Compare the relevant property sources, classpath, active profiles, and bean definitions with the working environment. Check whether a production bean caused @ConditionalOnMissingBean to back off.
  4. Fix the actual cause: correct the property or profile, add the missing dependency, remove an unintended exclusion, or define the bean explicitly.
management.endpoints.web.exposure.include=conditions
# Or for startup diagnostics:
java -jar app.jar --debug

A condition report is a diagnosis, not a guarantee that a bean with the expected name exists: later registration failures, component scanning, scopes, and bean post-processors can still matter. Also compare the exact Spring Boot version, since condition messages and endpoint details can vary.

Interview takeaway: I would use the report to identify the precise condition that did not match in production, then fix that input rather than overriding the symptom.

2. A starter creates a duplicate bean. Which @ConditionalOnMissingBean condition failed?

The failed condition is normally @ConditionalOnMissingBean: it did not match because Spring already found a bean satisfying its value, type, name, or annotation constraint. That causes the auto-configuration to back off; if a duplicate still appears, I would verify whether the conflict is actually a bean-name collision, multiple auto-configurations, or a condition evaluated before the relevant bean was visible.

@Bean
@ConditionalOnMissingBean(CacheClient.class)
CacheClient defaultCacheClient(CacheProperties properties) {
    return new DefaultCacheClient(properties);
}

Important details when interpreting the result:

  • The condition can be satisfied by a user bean, a scanned component, or another auto-configuration.
  • Its search can be limited by the condition's search setting; the default behavior is not necessarily equivalent to searching every parent context in every arrangement.
  • Conditions are evaluated while configuration classes are being processed. Auto-configuration ordering and bean-definition visibility therefore matter, especially when a condition is placed on a @Bean method.
  • A bean of the wrong type may not satisfy the condition, while a bean with the expected type but a different name usually does. Conversely, a name-based condition can behave differently from a type-based one.

To diagnose the duplicate:

  1. Read the ConditionEvaluationReport and locate the starter's auto-configuration. Confirm the exact @ConditionalOnMissingBean outcome and its matched bean type or name.
  2. List bean definitions with Actuator or a targeted ApplicationContext inspection, including their declaring configuration classes.
  3. Check whether two versions of the starter or two auto-configurations are present, and inspect auto-configuration ordering.
  4. Prefer the application bean when supported. Otherwise remove the unintended dependency, exclude one auto-configuration, or deliberately allow and qualify multiple beans.

Do not enable bean-definition overriding merely to hide the problem; it can make startup order decide which implementation wins. If multiple implementations are intentional, use explicit @Qualifier or @Primary semantics instead of relying on registration order.

Interview takeaway: I would prove that @ConditionalOnMissingBean saw an existing matching bean, then fix ownership or qualification rather than blindly permitting overriding.

3. How can @AutoConfigureBefore change ordering between auto-configurations?

@AutoConfigureBefore adds an ordering constraint to the auto-configuration import process: the named auto-configuration is sorted after the configuration declaring the annotation. It changes configuration-class processing order, not the order of ordinary bean instantiation and not whether either auto-configuration is imported.

@AutoConfiguration
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class CustomDataSourceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    DataSource customDataSource() {
        return createDataSource();
    }
}

This matters when:

  • One auto-configuration defines beans or metadata that another condition must see while it is being processed.
  • A custom configuration needs to establish a default before a later auto-configuration evaluates @ConditionalOnMissingBean.
  • The relationship is between auto-configuration classes, rather than between arbitrary @Configuration classes.

For a reliable change:

  1. Put @AutoConfigureBefore(OtherAutoConfiguration.class) on the auto-configuration that must run first. @AutoConfigureBefore(name = "...") can be used when referring to a class by name.
  2. Confirm both configurations are candidates for the same application. Ordering cannot resurrect an excluded configuration or make an absent class load.
  3. Inspect the condition report and startup logs to confirm the resulting order and condition outcomes.
  4. Use the narrowest relationship possible. If the real requirement is a bean dependency, prefer method-parameter injection or an explicit condition rather than using ordering as a substitute.

Spring Boot builds an ordering graph from @AutoConfigureBefore, @AutoConfigureAfter, and auto-configuration ordering metadata, then sorts the imported candidates. Cycles or contradictory relationships are configuration errors, and ordering does not override explicit exclusions. @AutoConfigureOrder is a coarser fallback, not usually the best way to express a dependency between two configurations.

Interview takeaway: @AutoConfigureBefore changes the auto-configuration sorting graph, so I use it only when one configuration’s conditional decisions genuinely depend on another being processed first.

4. A property has no effect. How can @ConditionalOnProperty's matchIfMissing value explain it?

matchIfMissing controls what @ConditionalOnProperty does when the named property is absent: true means the condition still matches, while false means it does not. Therefore a property can appear to have no effect if the property is missing or misnamed and the condition is configured to match by default.

@Bean
@ConditionalOnProperty(
    prefix = "acme.feature",
    name = "enabled",
    havingValue = "true",
    matchIfMissing = false
)
FeatureClient featureClient() {
    return new FeatureClient();
}

When investigating, distinguish these cases:

  • With matchIfMissing = true and no havingValue, the condition generally matches when the property exists and is not false, and also matches when it is absent.
  • With havingValue = "true", the property must have that value for the condition to match; matchIfMissing only controls absence, not an explicitly supplied false.
  • The complete key is assembled from prefix and name, using Spring Boot’s relaxed property matching. A typo, wrong profile file, or environment-variable spelling can still leave the intended key absent.
  • The condition is evaluated during configuration processing, so setting a property after startup or changing an unrelated similarly named key cannot affect it.

I would check it by:

  1. Reading the condition report for the auto-configuration and its property outcome.
  2. Inspecting effective configuration for the active profile and the actual property source, while avoiding exposure of secrets.
  3. Verifying the assembled key and value, then testing both explicit true and explicit false cases.
  4. Choosing matchIfMissing = true only when the feature should be enabled by default; otherwise keep it false and document the required property.

If a property should accept only an explicit boolean, use havingValue deliberately and test the condition’s disabled path. This avoids silently enabling an integration because a deployment omitted its configuration.

Interview takeaway: I first establish whether the property is absent or present with the wrong value, because matchIfMissing only governs the absent-property case.

5. How does AutoConfigurationImportSelector choose exclusions from spring.autoconfigure.exclude?

AutoConfigurationImportSelector reads spring.autoconfigure.exclude from the environment, parses its comma-separated fully qualified class names, and combines them with exclusions declared through @EnableAutoConfiguration. It removes those names from the auto-configuration candidates before importing the remaining configurations.

spring.autoconfigure.exclude=
com.acme.metrics.MetricsAutoConfiguration,
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

The effective flow is:

  1. Load candidate auto-configurations from the version-specific metadata and imports used by the application.
  2. Read annotation exclusions such as @EnableAutoConfiguration(exclude = ...) and excludeName, then read the spring.autoconfigure.exclude environment property.
  3. Combine the exclusion sets, validate the requested names, and remove matching candidates. The selector publishes the auto-configuration import event with the resulting selection.
  4. Pass the remaining candidates through auto-configuration ordering and import them.

Operational details that commonly matter:

  • Use exact fully qualified class names; this property does not provide wildcard exclusion syntax.
  • The property can be supplied in configuration files, environment variables, command-line arguments, or another higher-precedence Spring property source.
  • An exclusion affects auto-configuration, not a user-defined @Bean or a regular @Configuration class that creates the same infrastructure.
  • If a listed class is not an auto-configuration candidate, Boot treats it as an invalid exclusion; the precise diagnostic behavior can vary by Boot version, so verify the startup message rather than assuming it was accepted.
  • Prefer annotation exclusions for a narrowly scoped application decision and the property for deployment-wide policy, but document property-based exclusions because they are less visible in source code.

The condition report can confirm that the class was excluded, while the import selector’s debug logging helps distinguish exclusion from a condition that simply did not match. In Boot 2 and 3 the surrounding metadata and imports differ, but the practical rule remains: the property removes candidate auto-configurations before their beans are processed.

Interview takeaway: spring.autoconfigure.exclude is an environment-driven exclusion list that AutoConfigurationImportSelector merges with annotation exclusions before sorting and importing candidates.

Section 2: Bean Lifecycle

6. A startup callback skips advice. How does @PostConstruct run before proxy creation?

@PostConstruct normally runs while the bean is still the target instance, before an auto-proxy creator wraps it. It is therefore not a reliable place to call a method expecting @Transactional, @Async, caching, or other proxy advice to apply.

create instance
  -> populate properties
  -> BeanPostProcessor.beforeInitialization()
       -> @PostConstruct
       -> InitializingBean / custom init method
  -> BeanPostProcessor.afterInitialization()
       -> create proxy, if needed

The important consequences are:

  • CommonAnnotationBeanPostProcessor invokes @PostConstruct during the initialization callbacks.
  • Auto-proxying generally happens in postProcessAfterInitialization, after @PostConstruct and afterPropertiesSet().
  • A call from one method to another on this also bypasses the proxy, even after startup is complete.
  • Circular-reference handling can expose an early reference, but it does not make lifecycle callbacks a safe proxy boundary.

To diagnose and fix it:

  1. Log the class in the callback and at the injection point; compare the target class with the proxy class and inspect whether the expected advisor is present.
  2. Move work that needs advice to an explicit startup phase, such as a ContextRefreshedEvent listener or SmartInitializingSingleton, while remembering that those callbacks still do not prove an external system is ready.
  3. Alternatively, inject a separate proxied collaborator or obtain the dependency through ObjectProvider after initialization. Avoid injecting the bean's own proxy as a general solution; it complicates design and can create cycles.
  4. Keep @PostConstruct for local, non-advised initialization and make startup actions idempotent.

Interview takeaway: @PostConstruct initializes the target before auto-proxying, so proxy-dependent work belongs in a later lifecycle phase or in another bean.

7. Shutdown leaves worker threads alive. How can SmartLifecycle phase affect destruction order?

SmartLifecycle phases control coordinated startup and shutdown: lower phase values start first, while higher phase values stop first. Put consumers, such as request intake, in a higher phase than the workers they depend on so consumers stop before workers are terminated.

@Component
final class Worker implements SmartLifecycle {
    public int getPhase() { return 100; }
    public boolean isAutoStartup() { return true; }
    public void start() { /* accept work */ }
    public void stop(Runnable done) {
        executor.shutdown();
        executor.execute(() -> {
            awaitTermination();
            done.run();
        });
    }
    public void stop() { executor.shutdown(); }
    public boolean isRunning() { return !executor.isTerminated(); }
}

For example, assign an HTTP or message-ingress component phase 200 and the worker phase 100. On close, phase 200 stops first, allowing no new work while phase 100 drains existing work. DefaultLifecycleProcessor coordinates the phases and waits for asynchronous stop(Runnable) callbacks.

  • A higher phase is not simply a bean-destruction priority. Lifecycle stopping happens before ordinary singleton destruction, and dependency destruction rules still matter afterward.
  • A stop callback must be invoked only when shutdown is actually complete; calling it immediately defeats graceful draining.
  • A worker that blocks forever can delay context shutdown until the lifecycle timeout is reached. In Spring Boot, spring.lifecycle.timeout-per-shutdown-phase can bound waiting for a shutdown phase.

When threads survive shutdown:

  1. Log each component's phase, isRunning() state, and the thread names during context close.
  2. Verify that ingress stops first, executor shutdown is called, queued work has a policy, and every asynchronous stop path invokes done.run().
  3. Choose phases based on dependencies, then make the worker stop idempotent and handle interruption.

Interview takeaway: Use phases to stop dependants before dependencies, and implement stop(Runnable) so Spring can distinguish “shutdown requested” from “shutdown complete.”

8. Why can a BeanPostProcessor miss beans created before it is registered?

A BeanPostProcessor only processes beans created after it has been registered, so it cannot retroactively advise or modify objects that were already instantiated. During startup, the processors themselves and their dependencies may be created early, before the complete processor chain exists.

BeanPostProcessor A registered
    -> creates dependency X
BeanPostProcessor B registered later
    -> X is already in the singleton cache
    -> B never sees X

Typical symptoms include:

  • The log warning that a bean is “not eligible for getting processed by all BeanPostProcessors” during creation of a processor or its dependency.
  • A bean missing an expected proxy, annotation-driven behavior, validation, or custom post-processing despite the processor being present later.
  • A dependency graph in which a @Bean method or constructor of a processor directly requests an application bean.

Diagnose and fix it in this order:

  1. Enable startup logging and inspect the bean-creation stack around the warning. Identify which BeanPostProcessor caused early creation and which dependency it requested.
  2. Keep processor definitions focused on infrastructure. Do not make a processor depend directly on ordinary application beans unless that early creation is intentional.
  3. Break the eager edge with @Lazy, ObjectProvider<T>, or a lookup performed only after processor registration. Use these only when delayed access is semantically safe.
  4. If the processor must affect a bean, ensure it is registered before that bean is obtained; changing @Order changes processing order, not registration timing.
  5. Do not assume calling getBean() later will reprocess an existing singleton. Rebuilding the context or explicitly applying infrastructure is generally safer than trying to mutate an already initialized object.

Interview takeaway: Post-processors are applied at bean creation time, so early processor dependencies can permanently escape processors registered later.

9. A prototype dependency behaves like a singleton. How does ObjectProvider<T> change lookup timing?

Injecting a prototype into a singleton resolves it during singleton construction, so the singleton keeps that one instance forever. Injecting ObjectProvider<T> instead stores a factory-like lookup, and each getObject() call asks the container for a new prototype instance.

@Component
class ReportService {
    private final ObjectProvider<ReportContext> contexts;

    ReportService(ObjectProvider<ReportContext> contexts) {
        this.contexts = contexts;
    }

    void generate() {
        ReportContext context = contexts.getObject();
        // A new prototype is obtained for this operation.
    }
}

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ReportContext { }

The distinction is about lookup timing:

  • A direct ReportContext dependency is resolved while ReportService is created, even though the target has prototype scope.
  • getObject() performs a container lookup at call time and therefore creates a new prototype each call.
  • getIfAvailable() and getIfUnique() are useful when absence or multiple candidates are valid; ObjectProvider also supports lazy iteration over matching beans.
  • Prototype destruction is not managed like singleton destruction. If instances own resources, the application must close or release them explicitly.

When correcting this pattern:

  1. Confirm the scope with the bean definition and log identity values from multiple operations.
  2. Replace the direct dependency with ObjectProvider<T> when each operation needs a fresh instance.
  3. Define the ownership boundary: use try/close, an explicit reset method, or another resource policy if the prototype is disposable.
  4. Consider a scoped proxy or @Lookup when declarative injection fits better, but remember that both hide a runtime lookup and can make lifecycle and testing less obvious.

Interview takeaway: A prototype scope affects creation only when the container is asked for the bean, and ObjectProvider postpones that request until use.

10. How does SmartInitializingSingleton differ from @PostConstruct for all-singletons-ready work?

@PostConstruct belongs to one bean's initialization and may run while other singleton beans are still being created. SmartInitializingSingleton.afterSingletonsInstantiated() runs after the container has pre-instantiated all eligible non-lazy singletons, making it the better hook for work that requires the normal singleton set to exist.

@Component
class StartupCoordinator implements SmartInitializingSingleton {
    @Override
    public void afterSingletonsInstantiated() {
        // Eager, non-lazy singleton initialization is complete.
        // Start coordination only after those beans are available.
    }
}

The lifecycle difference matters:

  • @PostConstruct runs during the bean's initialization callbacks, before the bean's afterInitialization post-processors have finished and before the rest of startup necessarily completes.
  • SmartInitializingSingleton is called after preInstantiateSingletons() finishes creating and initializing the regular non-lazy singleton set.
  • Neither callback means every bean in the application is ready: lazy beans, prototype beans, external services, and independently starting infrastructure may still be unavailable.
  • The callback is tied to the bean factory's singleton pre-instantiation process. It is not a general-purpose notification that the whole distributed application is healthy.

Choose and validate the hook deliberately:

  1. Use @PostConstruct for local invariants and state derived from already injected properties.
  2. Use SmartInitializingSingleton for registration or coordination that must see all eagerly created singleton collaborators.
  3. For an application-level signal after context refresh, use ContextRefreshedEvent; for external readiness, add an explicit readiness or health design rather than relying on either callback.
  4. Keep the operation idempotent and avoid long blocking work on the refresh thread.

Interview takeaway: Use @PostConstruct for per-bean initialization and SmartInitializingSingleton when all eagerly created singletons must be available first.

Preparing for a full interview loop? Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)

Section 3: Proxy Mechanics

11. A method is advised through one reference, but not another. How can JDK proxies explain it?

A JDK dynamic proxy advises calls made through the proxy object, not every reference that happens to point at the same target. One reference may be the interface-based proxy, while another is the underlying target or a different path that bypasses the proxy.

public interface PaymentService {
    void charge();
}

@Service
class PaymentServiceImpl implements PaymentService {
    public void charge() { }
}

// JDK proxy: implements PaymentService, delegates to PaymentServiceImpl
PaymentService advised = context.getBean(PaymentService.class);
PaymentServiceImpl raw = /* target obtained outside the proxy */ null;

The common causes are:

  • A caller creates the implementation with new, retrieves it from a non-Spring factory, or unwraps the target.
  • A @Bean method or another container returns an object reference before proxying, then that reference is retained.
  • A self-invocation such as this.charge() uses the target reference and skips the proxy.
  • A JDK proxy is injected through an interface, while some code separately holds the concrete target.

Diagnose and fix it by:

  1. Log getClass() and AopUtils.isAopProxy(object) at both call sites; compare identity with System.identityHashCode if necessary.
  2. Inspect the proxy interfaces and confirm that the advised call is made through one of them.
  3. Keep the bean container-managed and inject its interface rather than constructing or caching the implementation.
  4. For internal calls, move the advised operation to another bean, inject the proxied bean, or use AspectJ weaving when self-invocation must be advised.

With Spring's usual singleton setup, normal dependency injection returns the exposed proxy consistently. The exception is code that has escaped the container or deliberately accesses the target, so fixing the reference path is usually safer than adding another proxy.

Interview takeaway: A JDK proxy advises the reference that points to the proxy, so every caller must use the container-managed proxy rather than a raw or self-reference.

12. Why can a final method prevent Spring AOP from applying its advice?

With class-based Spring AOP, a final method cannot be advised because the generated subclass must override the method to intercept it. A final class has the same problem for all subclass-based advice; this limitation does not apply in the same way to an interface-based JDK proxy.

@Service
class AccountService {
    @Transactional
    public final void closeAccount() {  // CGLIB cannot override this
        // advice is not applied here
    }
}

What happens depends on the proxying mechanism:

  • CGLIB-style proxies create a subclass and override interceptable methods. final, private, and static methods cannot be overridden and therefore cannot receive subclass proxy advice.
  • A JDK proxy intercepts interface method calls at the interface boundary, so a final implementation method can still be reached through an advised interface proxy. The proxy still exposes interfaces, not the implementation class.
  • Spring Boot commonly enables class-based proxies by default, but that default can be changed by spring.aop.proxy-target-class or equivalent configuration.

Diagnose and fix it by:

  1. Check AopUtils.isCglibProxy(bean), AopUtils.isJdkDynamicProxy(bean), and the runtime class name, then inspect whether the method is final.
  2. Prefer removing final from methods that are intentionally advised, or move the operation to a separate service with a normal overridable method.
  3. Use an interface and JDK proxying when the interface boundary is sufficient; callers must then depend on that interface.
  4. Use AspectJ compile-time or load-time weaving when final methods or self-invocation must be advised, accepting more build, runtime, and debugging complexity.

Changing proxy mode is not a universal fix: CGLIB cannot proxy a final class, and forcing class proxies can expose different type and module constraints. The design fix is usually to place the transactional or other cross-cutting boundary on a non-final service method.

Interview takeaway: A final method cannot be overridden by a class-based proxy, so put advice on an overridable service boundary or use weaving when that constraint is unavoidable.

13. A bean cast fails after adding an aspect. How can JDK proxying change the exposed type?

Adding an aspect can replace the object exposed by the container with a JDK proxy that implements only the target's interfaces. A cast to the concrete implementation then fails because the proxy is not an instance of that implementation class.

public interface ReportService {
    void generate();
}

class ReportServiceImpl implements ReportService {
    public void generate() { }
    public void internalOnly() { }
}

ReportService service = context.getBean(ReportService.class);
ReportServiceImpl impl = (ReportServiceImpl) service; // ClassCastException

Useful signals include:

  • The exception names a generated proxy class such as a JDK proxy and says it cannot be cast to the implementation.
  • The bean works when injected as ReportService but fails when injected or cast as ReportServiceImpl.
  • The failure appears after an advisor, @Transactional, @Async, @Cacheable, or another post-processor causes proxy creation.

Choose the correction deliberately:

  1. Inspect the runtime object with AopUtils.isAopProxy, AopUtils.isJdkDynamicProxy, and bean.getClass().getInterfaces().
  2. Prefer injecting and returning the service interface. Keep implementation-only methods out of callers that need to remain proxy-compatible.
  3. If concrete-type access is genuinely required, enable class-based proxies with spring.aop.proxy-target-class=true or @EnableAspectJAutoProxy(proxyTargetClass = true).
  4. Retest final classes and methods: CGLIB-style proxies require a subclassable class and overridable advised methods.

Forcing CGLIB preserves more concrete-type visibility but couples callers to the implementation and can expose final-method or Java module limitations. A cast can also hide an architectural problem: code using an implementation-only operation is bypassing the intended service contract.

Interview takeaway: A JDK proxy is an interface-shaped replacement, so depend on the interface or explicitly choose class-based proxying with its subclassing trade-offs.

14. Why can AopContext.currentProxy() fail when exposeProxy is false?

AopContext.currentProxy() works only when the current proxy interceptor has bound that proxy to the calling thread. If proxy exposure is disabled, no proxy is placed in that thread-local context, so the call throws IllegalStateException instead of returning a usable proxy.

@EnableAspectJAutoProxy(exposeProxy = true)
@Configuration
class AopConfig { }

class OrderService {
    public void outer() {
        ((OrderService) AopContext.currentProxy()).inner();
    }

    @Transactional
    public void inner() { }
}

The failure is especially easy to trigger when:

  • The bean is not currently executing through a Spring AOP proxy, even if the class is normally proxied.
  • outer() is called on the raw target, obtained with new, unwrapped from a proxy, or reached through an unproxied object.
  • The call occurs on another thread, such as an @Async task; the proxy context is thread-bound and is not automatically propagated.
  • The proxy factory or auto-proxy creator was configured without exposeProxy = true.

Diagnose and fix it by:

  1. Capture the exception and log the runtime class plus AopUtils.isAopProxy(this) at the entry point; verify that the entry call crosses the proxy.
  2. Enable exposure with @EnableAspectJAutoProxy(exposeProxy = true) when this mechanism is intentionally required.
  3. Prefer injecting another proxied bean or refactoring the advised operation into a collaborator; that makes the dependency explicit and works across cleaner thread boundaries.
  4. Do not use currentProxy() as a general self-invocation solution in asynchronous code; pass required state to a separate worker bean instead.

Proxy exposure uses thread-local state and is available only during an advised invocation. Enabling it adds coupling to Spring AOP and a small per-invocation context cost, so explicit collaboration is normally easier to test and maintain.

Interview takeaway: currentProxy() is a thread-bound convenience that requires an exposed proxy and an active proxied call, not merely a Spring-managed bean.

15. How does proxy order affect @Async and @Transactional on one method?

The outermost interceptor determines which thread sees the other concern. If @Async submits first, @Transactional can start inside the worker thread; if the transaction interceptor runs first, the transaction exists only on the caller thread and normally ends before the asynchronous work executes.

// Safer boundary: async delegates to a separately proxied transactional bean
@Service
class OrderAsyncService {
    private final OrderWorker worker;

    @Async
    public void submit(Long id) {
        worker.process(id);
    }
}

@Service
class OrderWorker {
    @Transactional
    public void process(Long id) { }
}

Important consequences are:

  • A transaction is thread-bound; it is not automatically propagated to the executor thread used by @Async.
  • With async outermost, the caller quickly receives a Future or completion result, and the worker then enters the transaction.
  • With transaction outermost, database work performed by the worker may run without the caller's transaction, while the caller transaction commits or rolls back independently.
  • Exceptions and return values also follow async semantics: a void async method cannot report worker exceptions to the caller directly; use a suitable future type or an error handler.

Diagnose and control it by:

  1. Log thread names and transaction state, for example with TransactionSynchronizationManager.isActualTransactionActive(), at both method boundaries.
  2. Inspect advisor ordering and configured @Order values; @EnableAsync and transaction management both have ordering settings, and equal/default order should not be treated as a business guarantee.
  3. Prefer the split shown above: the async entry submits work, and a separate proxied bean owns the transaction.
  4. If one method must carry both annotations, configure and test explicit ordering, but document that the transaction will be created on whichever thread reaches the transactional interceptor.

A separate bean also avoids self-invocation, which would bypass both proxy concerns. It makes transaction scope, executor behavior, retries, and failure handling visible instead of depending on a fragile stack of advisors.

Interview takeaway: For reliable async database work, let the worker thread enter a separate @Transactional bean rather than relying on ambiguous proxy order on one method.

Section 4: Transaction Traps

16. A checked exception reaches the caller, but data is committed. Why does @Transactional allow that by default?

@Transactional rolls back by default for unchecked exceptions (RuntimeException and Error), not for checked exceptions. A checked exception can therefore escape the proxied method after Spring has allowed the transaction to complete normally, so the transaction manager commits.

@Transactional(rollbackFor = PaymentDeclinedException.class)
public void charge(Order order) throws PaymentDeclinedException {
    repository.save(order);
    gateway.charge(order); // checked exception may be thrown
}

This is a policy choice rather than a database limitation. Spring's transaction interceptor applies rollback rules when the method exits exceptionally. The default rule treats checked exceptions as expected, recoverable conditions; older enterprise code often used checked exceptions for business outcomes that should not invalidate all work. If the exception is wrapped in a RuntimeException, the default rule changes. A more specific rollback rule also overrides a broader one.

Production signals include:

  • The exception is checked, and there is no matching rollbackFor rule.
  • Transaction logs show normal completion followed by COMMIT.
  • A downstream caller catches the exception but observes the database changes already persisted.

Diagnose and fix it in this order:

  1. Confirm that the call crossed the transactional proxy and identify the actual exception type at the transaction boundary.
  2. Inspect transaction interceptor logs and database commit/rollback logs; do not infer the outcome from the exception alone.
  3. Declare rollbackFor for the business exception, or use a deliberately designed unchecked exception if that matches the domain contract.
  4. Add an integration test that throws the exception and verifies the database state.

The trade-off is that broad rules such as rollbackFor = Exception.class can roll back recoverable validation or notification failures and make retries harder. Prefer explicit domain exceptions. If only part of the operation should roll back, split it into a separate transactional boundary rather than relying on one global rule.

Interview takeaway: A checked exception is not a rollback signal by default, so declare an explicit rollback rule when that business failure must undo the transaction.

17. Why can a caught RuntimeException still leave a transaction rollback-only?

Catching a RuntimeException does not necessarily clear the transaction's rollback-only marker. Usually the exception escaped an inner transactional boundary, whose interceptor marked the shared transaction rollback-only, and an outer method later caught it; the outer commit then fails with UnexpectedRollbackException.

@Transactional
public void importData() {
    try {
        validatorService.validateAndSave(); // separate proxied call
    } catch (RuntimeException ex) {
        log.warn("Rejected item", ex);
    }
    auditRepository.save(...);
}

With REQUIRED, the inner call normally joins the outer physical transaction. When its runtime exception reaches the inner interceptor, Spring's transaction manager marks that transaction rollback-only. Catching the exception in the outer method changes control flow, but the marker remains. Spring refuses to commit work that an inner participant declared unsafe. This is different from catching an exception entirely inside the same method before any transactional interceptor sees it, although JPA or the database can independently mark a transaction rollback-only after a persistence error.

Useful production signals are:

  • UnexpectedRollbackException at the outer boundary, often with an earlier validation, constraint, or flush exception.
  • Transaction debug logs showing Participating in existing transaction and rollback-only.
  • A database with no committed rows even though the outer method returned normally until its final failure.

Check the boundary and choose an intentional policy:

  1. Find the first exception and the proxied method that handled it; the final UnexpectedRollbackException is often only the symptom.
  2. If the whole operation is invalid, rethrow the original exception and let the transaction roll back.
  3. If the failure is independent, move recovery work to a separate bean using REQUIRES_NEW, accepting its connection and consistency costs.
  4. Use noRollbackFor only when the exception truly must not invalidate the transaction, and test provider-specific flush behavior.

Do not use TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() as a way to undo an earlier decision; it only makes rollback explicit. Also remember that self-invocation bypasses the proxy, so an apparent inner boundary may not exist at runtime.

Interview takeaway: Catching an exception changes Java control flow, not a rollback-only decision already recorded on the shared transaction.

18. A REQUIRES_NEW call hangs under load. How can connection pool sizing cause it?

REQUIRES_NEW suspends the outer transaction and starts an independent one, which commonly requires a second database connection. If every request holds an outer connection while waiting for that second connection, all pool connections can be occupied and the application can deadlock until connection acquisition times out.

outer transaction:  T1 -- holds connection A
                         |
                         +-- REQUIRES_NEW: waits for connection B

pool capacity = active outer transactions
=> every thread waits for a connection it cannot obtain

The exact resource behavior depends on the transaction manager and resource, but with a normal JDBC or JPA DataSource, the suspended transaction keeps its connection associated with the thread. A burst of concurrent outer transactions can therefore consume the whole pool. Each tries to enter REQUIRES_NEW; no connection is free to start the inner transaction. Increasing only request threads makes this worse.

Look for these signals:

  • Pool active count equals maximum while pending acquisition count rises.
  • Thread dumps show calls blocked in getConnection, often inside the REQUIRES_NEW method.
  • The inner transaction's timeout or the pool's connectionTimeout expires, while database sessions show the outer transactions idle or waiting.

Diagnose and fix it as follows:

  1. Measure the maximum number of simultaneous outer transactions and the number of nested connections each request can require.
  2. Enable pool metrics and transaction logging, then correlate connection leases with thread names and request IDs.
  3. Remove the nested boundary when independent commit is not required, or publish work asynchronously through a durable mechanism.
  4. If REQUIRES_NEW is required, reserve pool headroom, bound concurrency with a semaphore or queue, and configure timeouts so saturation fails quickly.

A larger pool is not a universal fix: it can overload the database and does not solve unbounded nesting. Size it against database capacity and the worst legitimate nesting pattern, then load-test the boundary. Separate pools can isolate an audit or notification path, but they add operational complexity and do not make the business operation atomic.

Interview takeaway: Treat every REQUIRES_NEW call as a possible extra connection lease, or pool exhaustion can turn transaction suspension into a wait cycle.

19. How does NESTED differ from REQUIRES_NEW when the database supports savepoints?

NESTED uses a savepoint inside the existing physical transaction, whereas REQUIRES_NEW suspends that transaction and runs on a separate physical transaction, normally with a separate connection. Rolling back NESTED returns to its savepoint; rolling back REQUIRES_NEW affects only its independent commit.

outer transaction
  ├─ NESTED: savepoint S1; failure -> rollback to S1; outer continues
  └─ outer commit decides the final outcome

REQUIRES_NEW
  ├─ suspend outer transaction
  ├─ inner commit/rollback is independent
  └─ resume outer transaction

With NESTED, an inner success is not durable yet: the outer transaction can still roll everything back. With REQUIRES_NEW, an inner commit remains committed even if the outer transaction later fails. NESTED also avoids the extra connection and the associated pool deadlock risk. Its scope is database and transaction-manager dependent: JDBC savepoint support is required, and it is most predictably supported with DataSourceTransactionManager. JpaTransactionManager can expose nested JDBC behavior when configured with nestedTransactionAllowed, but JPA itself does not standardize nested transactions.

Important caveats include:

  • A database or driver may not support savepoints, or DDL may implicitly commit and invalidate the model.
  • The inner method must actually cross a Spring proxy; self-invocation does not apply propagation advice.
  • After a savepoint rollback, a JPA persistence context may still contain in-memory state that needs careful clearing or reloading; savepoints are not a general JPA entity-state isolation mechanism.

Choose and verify the boundary:

  1. Confirm the transaction manager, driver, database savepoint support, and nestedTransactionAllowed configuration where relevant.
  2. Enable transaction and SQL logging and look for SAVEPOINT and ROLLBACK TO SAVEPOINT rather than a second connection.
  3. Use NESTED for partial JDBC work whose final fate should follow the outer transaction; use REQUIRES_NEW only for genuinely independent outcomes such as an audit record.
  4. Test outer rollback, inner rollback, inner success, and persistence-context behavior with the actual database.

Interview takeaway: NESTED gives partial rollback within one transaction, while REQUIRES_NEW gives independent commit semantics at the cost of another transaction resource.

20. Why can readOnly=true fail to prevent writes through JPA dirty checking?

readOnly=true is primarily a transaction hint, not a universal write prohibition. Spring may configure the JDBC connection or ORM flush behavior, but JPA still has managed entities and dirty checking, and explicit flushes, bulk operations, native SQL, or another connection can still write unless the database enforces read-only mode.

@Transactional(readOnly = true)
public AccountView find(long id) {
    Account account = repository.findById(id).orElseThrow();
    account.setLastViewed(Instant.now()); // mutates managed state
    entityManager.flush();                // may issue an UPDATE
    return AccountView.from(account);
}

JPA does not define readOnly as a portable write-blocking semantic. Spring's transaction manager and Hibernate integration can select provider-specific flush modes; behavior and optimizations have varied across Spring and Hibernate versions, including Hibernate 5 and 6. Suppressed automatic flushing does not make a managed object immutable, and an explicit flush or a native statement can still expose a write. Database behavior also varies: some drivers treat Connection.setReadOnly(true) as a hint, while databases configured for read-only transactions may reject writes. That protection applies only to that database transaction and connection.

Common signals are:

  • Unexpected UPDATE statements at transaction completion or before a query triggers an automatic flush.
  • A repository read method changes an entity and the change appears after the request.
  • Writes bypass the JPA connection through JDBC, a bulk query, stored procedure, or another data source.

Make the intent reliable:

  1. Capture SQL and bind parameters, and inspect Hibernate flush/transaction logs rather than assuming the annotation worked.
  2. Return DTOs or projections for read paths and avoid exposing mutable managed entities to code that can change them.
  3. Enforce read-only access with database permissions or a database-enforced read-only transaction when rejection is required.
  4. Keep write operations in explicitly writable service methods and test that accidental mutations fail or remain uncommitted.

Database enforcement is stronger but may break legitimate framework operations, sequences, temporary tables, or provider behavior, so validate it against the actual workload. A separate read data source can isolate writes, but it introduces routing and consistency concerns.

Interview takeaway: Use readOnly=true to communicate and optimize read intent, but use immutable read models and database enforcement when preventing writes is a requirement.

Key Takeaways

  • ConditionEvaluationReport shows which auto-configuration conditions matched, failed, or were skipped and why.
  • Auto-configuration ordering changes which definitions are processed first, but it does not automatically resolve every bean conflict.
  • A missing property can produce different behavior depending on matchIfMissing and the property's actual value.
  • @PostConstruct runs during bean initialization, before later proxy wrapping can affect calls made from that callback.
  • SmartLifecycle phases coordinate startup and shutdown, with lower phases stopping later than higher phases.
  • A BeanPostProcessor only affects beans processed after it is registered, so early-created infrastructure can be missed.
  • ObjectProvider<T> performs dependency lookup when requested, making prototype retrieval different from injecting one instance directly.
  • Spring AOP advice depends on proxy boundaries, exposed types, method visibility, and the order of multiple advisors.
  • By default, @Transactional rolls back for unchecked exceptions and Error, not for every checked exception.
  • REQUIRES_NEW needs an additional database connection while the outer transaction is suspended, making pool capacity part of correctness.
  • NESTED usually uses a savepoint within the existing transaction, so it does not provide the same independent-commit semantics as REQUIRES_NEW.
  • JPA readOnly=true is commonly a hint or optimization rather than a universal prohibition against writes.

Frequently Asked Questions

Which Spring Boot version should interview answers target?

State the Spring Boot and Spring Framework versions when behavior may differ, especially around auto-configuration internals and proxy infrastructure. The public concepts are stable, but implementation classes, logging details, and supported configuration options can change. A strong answer separates guaranteed framework contracts from observations tied to a particular Boot, Framework, Hibernate, or JDK version.

How should I investigate a surprising Spring behavior in a real service?

Start with the effective configuration, bean names, bean types, and relevant logs rather than changing annotations immediately. For auto-configuration, inspect condition outcomes; for proxies, inspect the runtime class and interfaces; for transactions, trace propagation, connection usage, and rollback state. A minimal reproduction with the same framework and database versions often distinguishes application behavior from framework assumptions.

Does calling another method on the same Spring bean go through advice?

Usually not. A call made through this stays inside the target object and does not cross the Spring proxy, so proxy-based annotations such as @Transactional, @Async, and many custom aspects are not applied to that call. Moving the operation to another bean, calling through an injected proxy, or redesigning the boundary is generally clearer than relying on proxy exposure.

Are Spring proxies always visible as the bean's runtime type?

No. JDK dynamic proxies expose interfaces, while class-based proxies typically expose a subclass of the target when that is possible. Code that depends on a concrete implementation type can therefore fail after proxying, even though interface-based injection works. Prefer stable interfaces at boundaries, and inspect the actual runtime class when diagnosing casting or reflection problems.

Does a transaction marked read-only guarantee that no database write can occur?

No. In Spring, readOnly is primarily a transaction hint passed to the transaction manager and, for JPA, often influences flush behavior or the persistence provider's handling of the session. It is not a universal write firewall. Database permissions, provider behavior, explicit flushes, native statements, and framework versions determine how strongly writes are prevented or merely discouraged.

Conclusion

The useful interview skill across these topics is tracing boundaries: condition evaluation determines whether configuration is imported, lifecycle callbacks determine when objects are ready, proxies determine which calls receive advice, and transaction rules determine what the database ultimately commits. When behavior is surprising, identify the runtime object, the creation order, the active conditions, and the transaction context before proposing a fix. That approach produces explanations that remain accurate across common Spring Boot configurations and exposes the trade-offs behind each solution.

Which question would you find the hardest? Tell me in the comments.

Explore More Java Interview Resources

Java Spring Boot & Microservices Interview Q&A (200 Qs)
https://topmate.io/logicbrace/2278363

Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
https://topmate.io/logicbrace/2294498

Complete Java Full Stack Developer Kit (900 Qs: Core Java, Spring Boot & Microservices, Cloud/DevOps/System Design, React & Angular)
https://topmate.io/logicbrace/2306382

Senior Spring Boot Interview Questions – Top 20 with Answers

Post a Comment

0 Comments

Close Menu