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 guideI 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:
@ConditionalOnClass, @ConditionalOnProperty, and @ConditionalOnMissingBean.I would diagnose it in this order:
conditions endpoint temporarily, or start with --debug to obtain the condition evaluation delta. Treat that output as sensitive because it can reveal configuration details.@ConditionalOnMissingBean to back off.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.
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:
search setting; the default behavior is not necessarily equivalent to searching every parent context in every arrangement.@Bean method.To diagnose the duplicate:
ConditionEvaluationReport and locate the starter's auto-configuration. Confirm the exact @ConditionalOnMissingBean outcome and its matched bean type or name.ApplicationContext inspection, including their declaring configuration classes.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.
@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:
@ConditionalOnMissingBean.@Configuration classes.For a reliable change:
@AutoConfigureBefore(OtherAutoConfiguration.class) on the auto-configuration that must run first. @AutoConfigureBefore(name = "...") can be used when referring to a class by name.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.
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:
matchIfMissing = true and no havingValue, the condition generally matches when the property exists and is not false, and also matches when it is absent.havingValue = "true", the property must have that value for the condition to match; matchIfMissing only controls absence, not an explicitly supplied false.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.I would check it by:
true and explicit false cases.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.
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:
@EnableAutoConfiguration(exclude = ...) and excludeName, then read the spring.autoconfigure.exclude environment property.Operational details that commonly matter:
@Bean or a regular @Configuration class that creates the same infrastructure.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.
@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.postProcessAfterInitialization, after @PostConstruct and afterPropertiesSet().this also bypasses the proxy, even after startup is complete.To diagnose and fix it:
ContextRefreshedEvent listener or SmartInitializingSingleton, while remembering that those callbacks still do not prove an external system is ready.ObjectProvider after initialization. Avoid injecting the bean's own proxy as a general solution; it complicates design and can create cycles.@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.
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.
spring.lifecycle.timeout-per-shutdown-phase can bound waiting for a shutdown phase.When threads survive shutdown:
isRunning() state, and the thread names during context close.done.run().Interview takeaway: Use phases to stop dependants before dependencies, and implement stop(Runnable) so Spring can distinguish “shutdown requested” from “shutdown complete.”
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:
@Bean method or constructor of a processor directly requests an application bean.Diagnose and fix it in this order:
BeanPostProcessor caused early creation and which dependency it requested.@Lazy, ObjectProvider<T>, or a lookup performed only after processor registration. Use these only when delayed access is semantically safe.@Order changes processing order, not registration timing.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.
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:
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.When correcting this pattern:
ObjectProvider<T> when each operation needs a fresh instance.try/close, an explicit reset method, or another resource policy if the prototype is disposable.@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.
@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.Choose and validate the hook deliberately:
@PostConstruct for local invariants and state derived from already injected properties.SmartInitializingSingleton for registration or coordination that must see all eagerly created singleton collaborators.ContextRefreshedEvent; for external readiness, add an explicit readiness or health design rather than relying on either callback.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)
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:
new, retrieves it from a non-Spring factory, or unwraps the target.@Bean method or another container returns an object reference before proxying, then that reference is retained.this.charge() uses the target reference and skips the proxy.Diagnose and fix it by:
getClass() and AopUtils.isAopProxy(object) at both call sites; compare identity with System.identityHashCode if necessary.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.
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:
final, private, and static methods cannot be overridden and therefore cannot receive subclass proxy advice.spring.aop.proxy-target-class or equivalent configuration.Diagnose and fix it by:
AopUtils.isCglibProxy(bean), AopUtils.isJdkDynamicProxy(bean), and the runtime class name, then inspect whether the method is final.final from methods that are intentionally advised, or move the operation to a separate service with a normal overridable method.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.
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:
ReportService but fails when injected or cast as ReportServiceImpl.@Transactional, @Async, @Cacheable, or another post-processor causes proxy creation.Choose the correction deliberately:
AopUtils.isAopProxy, AopUtils.isJdkDynamicProxy, and bean.getClass().getInterfaces().spring.aop.proxy-target-class=true or @EnableAspectJAutoProxy(proxyTargetClass = true).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.
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:
outer() is called on the raw target, obtained with new, unwrapped from a proxy, or reached through an unproxied object.@Async task; the proxy context is thread-bound and is not automatically propagated.exposeProxy = true.Diagnose and fix it by:
AopUtils.isAopProxy(this) at the entry point; verify that the entry call crosses the proxy.@EnableAspectJAutoProxy(exposeProxy = true) when this mechanism is intentionally required.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.
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:
@Async.Future or completion result, and the worker then enters the transaction.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:
TransactionSynchronizationManager.isActualTransactionActive(), at both method boundaries.@Order values; @EnableAsync and transaction management both have ordering settings, and equal/default order should not be treated as a business guarantee.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.
@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:
rollbackFor rule.COMMIT.Diagnose and fix it in this order:
rollbackFor for the business exception, or use a deliberately designed unchecked exception if that matches the domain contract.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.
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.Participating in existing transaction and rollback-only.Check the boundary and choose an intentional policy:
UnexpectedRollbackException is often only the symptom.REQUIRES_NEW, accepting its connection and consistency costs.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.
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:
getConnection, often inside the REQUIRES_NEW method.connectionTimeout expires, while database sessions show the outer transactions idle or waiting.Diagnose and fix it as follows:
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.
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:
Choose and verify the boundary:
nestedTransactionAllowed configuration where relevant.SAVEPOINT and ROLLBACK TO SAVEPOINT rather than a second connection.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.Interview takeaway: NESTED gives partial rollback within one transaction, while REQUIRES_NEW gives independent commit semantics at the cost of another transaction resource.
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:
UPDATE statements at transaction completion or before a query triggers an automatic flush.Make the intent reliable:
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.
ConditionEvaluationReport shows which auto-configuration conditions matched, failed, or were skipped and why.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.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.@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.readOnly=true is commonly a hint or optimization rather than a universal prohibition against writes.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.
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.
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.
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.
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.
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.
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

0 Comments