All interview questions Programming · 2026

Spring Boot Interview Questions

Spring Boot is the most common backend framework in Java interviews, from campus placements to senior roles. These are the questions interviewers actually ask, grouped by theme and tagged by experience level.

100 questions with concise, interview-ready answers.

Spring Boot Fundamentals

1.

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

Fresher

Spring Boot is an opinionated layer on top of Spring that removes most configuration. Plain Spring requires you to declare beans, dispatcher servlets and view resolvers yourself; Spring Boot infers sensible defaults from the classpath, embeds a server, and gives you a runnable jar. It adds no new programming model — it is the same Spring with the setup done for you.

2.

What are the main advantages of Spring Boot?

Fresher

Auto-configuration, starter dependencies that resolve compatible versions, an embedded server so there is no external deployment step, production features via Actuator, externalised configuration with profiles, and no XML. The practical effect is that a working REST service is a few lines rather than a day of configuration.

3.

What does the @SpringBootApplication annotation do?

Fresher

It combines three annotations: @SpringBootConfiguration (marks the class as a configuration source), @EnableAutoConfiguration (turns on auto-configuration), and @ComponentScan (scans the current package and below for components). That last part is why your classes must live under the main application package to be discovered.

4.

What is auto-configuration in Spring Boot?

Fresher

Spring Boot inspects the classpath, existing beans and properties, and configures beans it thinks you need — see a JDBC driver and a datasource URL and it configures a DataSource. It is conditional, driven by annotations like @ConditionalOnClass and @ConditionalOnMissingBean, which is why defining your own bean of that type silently replaces the default.

5.

What are Spring Boot starters?

Fresher

Curated dependency descriptors that pull in a coherent, version-compatible set of libraries — spring-boot-starter-web brings Spring MVC, Jackson and embedded Tomcat. They exist to remove version-conflict debugging, which is what most of pre-Boot Spring setup actually was.

6.

What is an embedded server in Spring Boot?

Fresher

The servlet container runs inside your application rather than the application being deployed into a container. Tomcat is the default; Jetty and Undertow are drop-in alternatives. This is what makes a Spring Boot application a self-contained jar you can run with java -jar, which is essential for containerised deployment.

7.

What is the difference between a jar and a war deployment?

Fresher

A fat jar contains your code, its dependencies and an embedded server, and runs standalone — the default and the right choice for containers. A war is deployed into an external servlet container, which you still see in older enterprise environments with shared application servers. Spring Boot supports both, but jar is the modern default.

8.

How do you disable a specific auto-configuration?

2–5 yrs

Exclude it: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class), or set spring.autoconfigure.exclude in properties. You would do this when an auto-configuration is triggered by a transitive dependency you do not actually want configured — a common cause of an application failing at startup demanding a datasource URL.

9.

How does Spring Boot decide the order of auto-configuration?

2–5 yrs

Auto-configuration classes are registered in META-INF/spring/...AutoConfiguration.imports and ordered with @AutoConfigureBefore, @AutoConfigureAfter and @AutoConfigureOrder. Ordering matters because @ConditionalOnMissingBean depends on whether a bean has been defined yet — which is why user configuration is always processed before auto-configuration.

10.

What is the Spring Boot CommandLineRunner and ApplicationRunner?

2–5 yrs

Interfaces whose run method executes once after the context is ready, used for startup tasks like seeding data or warming a cache. CommandLineRunner receives raw String arguments; ApplicationRunner receives parsed ApplicationArguments. Order several with @Order.

11.

What is the Spring Boot application startup sequence?

Senior

SpringApplication.run creates the environment, applies listeners and initialisers, creates the ApplicationContext, loads bean definitions, processes BeanFactoryPostProcessors, instantiates singletons, applies BeanPostProcessors, publishes ApplicationReadyEvent and runs any runners. Knowing this order is how you explain why a bean is not available in a constructor but is in @PostConstruct.

12.

How do you write your own auto-configuration?

Senior

Create a @AutoConfiguration class with @Conditional annotations guarding its beans, register it in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, and use @ConfigurationProperties for its settings. Always guard with @ConditionalOnMissingBean so a consumer can override you — that is the contract that makes starters composable.

Dependency Injection & Beans

13.

What is dependency injection and inversion of control?

Fresher

Inversion of control means the framework creates and wires your objects rather than your code doing it with new. Dependency injection is the mechanism — dependencies are supplied from outside. The benefit is testability and loose coupling: you can substitute a fake implementation without touching the class that uses it.

14.

What is the Spring IoC container and what is a bean?

Fresher

The container is the ApplicationContext, which creates, wires and manages object lifecycles. A bean is any object it manages. You declare beans with stereotype annotations on classes it scans, or with @Bean methods in a @Configuration class.

15.

What does @Autowired do, and what are the ways to inject dependencies?

Fresher

It tells Spring to supply a matching bean. Three forms: constructor injection (preferred — dependencies are final, the object cannot exist half-built, and it is trivially testable), setter injection (for genuinely optional dependencies), and field injection (concise but untestable without reflection and hides a growing dependency list). Since Spring 4.3 a single constructor needs no annotation at all.

16.

What are @Component, @Service, and @Repository, and how do they differ?

Fresher

All three are stereotypes that make a class a scanned bean, and functionally they are nearly identical. @Service and @Component behave the same and differ only in intent. @Repository additionally enables exception translation, converting vendor-specific persistence exceptions into Spring's DataAccessException hierarchy — the one real behavioural difference.

17.

What is the difference between @Component and @Bean?

Fresher

@Component goes on your own class and is picked up by component scanning. @Bean goes on a method inside a @Configuration class and registers whatever that method returns — which is how you register a third-party class you cannot annotate, or a bean needing construction logic.

18.

What are the bean scopes in Spring?

Fresher

singleton (one per container, the default), prototype (a new instance per injection point or lookup), and for web applications request, session and application. The critical implication of the singleton default is that beans must be stateless or thread-safe, because one instance serves every concurrent request.

19.

Why is constructor injection preferred over field injection?

2–5 yrs

Dependencies can be final and are guaranteed present, so the object is never in a partially constructed state. It makes the class testable with plain new in a unit test, without a Spring context or reflection. And a constructor with eight parameters is visible pressure to split the class, whereas eight @Autowired fields hide it.

20.

What happens when two beans of the same type exist?

2–5 yrs

Injection fails with NoUniqueBeanDefinitionException. Resolve it with @Primary on the default choice, @Qualifier("name") at the injection point to pick explicitly, or by injecting a List or Map of the type to get all of them — which is the usual approach for strategy patterns.

21.

How do you handle a circular dependency between beans?

2–5 yrs

Spring can resolve some via setter or field injection using a partially built proxy, but constructor-injected cycles fail at startup, and since Boot 2.6 cycles are prohibited by default. The correct fix is design: extract the shared behaviour into a third bean, or use an event, or use @Lazy on one side as a stopgap. Enabling allow-circular-references hides the smell rather than fixing it.

22.

What is the bean lifecycle?

2–5 yrs

Instantiate, populate properties, run BeanNameAware and similar callbacks, apply BeanPostProcessor before-init, run @PostConstruct or InitializingBean.afterPropertiesSet, apply BeanPostProcessor after-init (this is where proxies are created), then on shutdown run @PreDestroy or DisposableBean.destroy. Note that prototype beans are never destroyed by the container.

23.

What is the difference between @PostConstruct and a constructor?

Senior

The constructor runs before dependency injection completes for field or setter injection, so injected fields may still be null. @PostConstruct runs after the bean is fully populated, which makes it the right place for initialisation that depends on injected collaborators. With constructor injection the distinction largely disappears.

24.

How does Spring create proxies, and why does it matter?

Senior

For @Transactional, @Async, @Cacheable and security, Spring wraps the bean in a proxy — JDK dynamic proxy if it implements an interface, CGLIB subclass otherwise. This is why calling an annotated method from another method in the same class bypasses the annotation entirely: the internal call does not go through the proxy. It is one of the most common real Spring bugs.

25.

What is a BeanFactoryPostProcessor versus a BeanPostProcessor?

Senior

A BeanFactoryPostProcessor modifies bean *definitions* before any bean is instantiated — property placeholder resolution works this way. A BeanPostProcessor intercepts each bean *instance* around initialisation, which is how proxies and annotation-driven behaviour get applied. Definitions first, instances second.

26.

How would you inject a prototype bean into a singleton correctly?

Senior

Plain injection gives you one instance forever, since the singleton is wired once. Use ObjectProvider or ObjectFactory and call getObject() per use, an @Lookup method, or scoped-proxy mode. The interviewer is checking that you understand injection happens once at wiring time, not per call.

REST APIs & Web Layer

27.

What is the difference between @RestController and @Controller?

Fresher

@Controller returns view names for a template engine. @RestController is @Controller plus @ResponseBody on every method, so return values are serialised straight to the response body as JSON. Use @RestController for APIs and @Controller for server-rendered pages.

28.

What are the common HTTP method mapping annotations?

Fresher

@GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping, all shorthand for @RequestMapping with a method attribute. @RequestMapping at class level sets a shared path prefix. The shorthand forms are preferred because the intent is visible at a glance.

29.

What is the difference between @PathVariable, @RequestParam and @RequestBody?

Fresher

@PathVariable binds a segment of the URL path — /users/{id}. @RequestParam binds a query parameter or form field, and supports required and defaultValue. @RequestBody deserialises the request body, normally JSON, into an object. Using @RequestBody on a GET is a common mistake.

30.

How do you validate request data in Spring Boot?

Fresher

Annotate the DTO with Bean Validation constraints — @NotNull, @Size, @Email, @Min — and put @Valid on the @RequestBody parameter. A violation throws MethodArgumentNotValidException, which you map to a 400 with field-level detail in an exception handler. Validating in the controller rather than deep in the service keeps bad data at the boundary.

31.

How do you handle exceptions in a Spring Boot REST API?

Fresher

A @RestControllerAdvice class with @ExceptionHandler methods per exception type, each returning a ResponseEntity with the right status and a consistent error body. @ResponseStatus on a custom exception is the lightweight option. The goal is that no handler leaks a stack trace or a 500 for a client error.

32.

What is a DTO and why not return entities directly?

2–5 yrs

A DTO is a shape defined for the API rather than for the database. Returning entities couples your public contract to your schema, so a column rename becomes a breaking API change; it can also leak fields you did not mean to expose, and lazy associations serialise unpredictably or throw outside a transaction. Map explicitly at the boundary.

33.

What is ResponseEntity and when do you need it?

2–5 yrs

A wrapper giving full control over status code, headers and body. Return it when the status varies — 201 with a Location header on create, 404 versus 200 on lookup, 204 on delete. Returning a plain object always produces 200, which is wrong for most non-trivial endpoints.

34.

How do you configure CORS in Spring Boot?

2–5 yrs

@CrossOrigin on a controller or method for narrow cases, or a global WebMvcConfigurer addCorsMappings for application-wide rules. With Spring Security in play, CORS must also be enabled there, because the security filter chain runs before the MVC layer — which is why CORS "not working" is usually a Security configuration problem.

35.

What is the difference between filters and interceptors?

2–5 yrs

A Filter is a servlet-level component running before Spring MVC, with access to the raw request and response — right for CORS, logging and authentication. A HandlerInterceptor runs inside MVC and knows the resolved handler, so it can act pre-handle, post-handle and after-completion — right for concerns that need controller context.

36.

How do you version a REST API in Spring Boot?

2–5 yrs

URI versioning (/api/v1/users) is the most common and the most visible. Header or media-type versioning keeps URLs stable but is harder to test and debug. Request-parameter versioning is possible and rarely a good idea. Pick one and apply it consistently; mixing schemes is worse than any single choice.

37.

What is the difference between RestTemplate, WebClient and RestClient?

Senior

RestTemplate is the blocking legacy client, in maintenance mode. WebClient is the reactive non-blocking client from WebFlux, usable in an MVC application and the right choice for high fan-out calls. RestClient, added in Spring 6.1, gives WebClient's fluent API with blocking semantics — the modern default for synchronous code.

38.

How would you implement pagination in a Spring Boot API?

Senior

Accept a Pageable parameter and return a Page from a Spring Data repository, which gives content, total elements and total pages for free. For large offsets prefer keyset pagination with a cursor, because OFFSET still scans and discards skipped rows. Always cap the page size server-side — an unbounded size parameter is a denial-of-service vector.

39.

What is HATEOAS and do you need it?

Senior

Hypermedia as the Engine of Application State — responses include links describing available transitions, so clients discover the API rather than hardcoding URLs. Spring HATEOAS supports it. In practice most APIs skip it: the coupling it removes is rarely the coupling that hurts, and it adds payload size and client complexity.

40.

What is the difference between Spring MVC and Spring WebFlux?

Senior

MVC is thread-per-request on a servlet stack, blocking, and simpler to reason about and debug. WebFlux is event-loop based and non-blocking on Netty, scaling to many concurrent connections with few threads — but every layer must be non-blocking or you lose the benefit and can starve the loop. With virtual threads, MVC now covers much of what WebFlux was needed for.

Data & JPA

41.

What is Spring Data JPA, and what does a repository interface give you?

Fresher

An abstraction over JPA that implements repositories for you. Extend JpaRepository and you get CRUD, paging and sorting with no implementation code; declare a method like findByEmailAndActiveTrue and Spring derives the query from the name. You write the interface, Spring generates the proxy.

42.

What is the difference between JPA and Hibernate?

Fresher

JPA is the specification — annotations and the EntityManager API. Hibernate is an implementation of it, and the default in Spring Boot. Coding against JPA keeps you portable; using Hibernate-specific features ties you to it. Interviewers ask this to see whether you know you are using an interface, not a library.

43.

What do @Entity, @Table, @Id and @GeneratedValue do?

Fresher

@Entity marks a class as a persistent entity; @Table overrides the table name. @Id marks the primary key and @GeneratedValue delegates generation to the database — IDENTITY for auto-increment, SEQUENCE for a sequence, which is preferable in Postgres because IDENTITY prevents JDBC batch inserts.

44.

What is the difference between CrudRepository, JpaRepository and PagingAndSortingRepository?

Fresher

CrudRepository gives basic CRUD. PagingAndSortingRepository adds paging and sorting. JpaRepository extends both and adds JPA specifics like flush, saveAndFlush and batch deletes, and returns List rather than Iterable. JpaRepository is the usual choice.

45.

What is the N+1 select problem and how do you fix it?

2–5 yrs

Fetching a list of N entities then triggering one extra query per entity to load a lazy association — 1 + N queries. Fix it with a JOIN FETCH in a JPQL query, an @EntityGraph on the repository method, or batch fetching. It is the single most common performance bug in JPA applications and interviewers ask it constantly.

46.

What is the difference between FetchType.LAZY and EAGER?

2–5 yrs

LAZY loads the association on first access, via a proxy; EAGER loads it with the parent. Default LAZY for collections and use JOIN FETCH where you need the data, because EAGER associations are loaded on every query whether you need them or not and compound quickly. LAZY's cost is LazyInitializationException if you touch it outside the session.

47.

What causes LazyInitializationException?

2–5 yrs

Accessing a lazy association after the persistence context has closed — typically in a controller or during JSON serialisation, once the transactional service method has returned. The right fixes are fetching what you need inside the transaction with JOIN FETCH or an entity graph, or mapping to a DTO before returning. Enabling open-session-in-view hides it and creates unpredictable query patterns.

48.

How does @Transactional work?

2–5 yrs

Spring proxies the bean and begins a transaction before the method, committing on normal return and rolling back on an unchecked exception. Two consequences catch people out: by default it does *not* roll back on checked exceptions unless you set rollbackFor, and calling a @Transactional method from within the same class bypasses the proxy so no transaction starts.

49.

What are the propagation levels of @Transactional?

2–5 yrs

REQUIRED (join an existing transaction or start one — the default), REQUIRES_NEW (always start a new, suspending the current), SUPPORTS, MANDATORY, NOT_SUPPORTED, NEVER, and NESTED (a savepoint). REQUIRES_NEW is the one to know: it commits independently, which is how you write an audit record that survives a rollback of the main work.

50.

What is the difference between save, saveAll and saveAndFlush?

2–5 yrs

save persists or merges and returns the managed instance; the SQL may not run until flush. saveAll does the same for a collection. saveAndFlush forces the flush immediately, which you need when subsequent code in the same transaction reads via native SQL and must see the write. Relying on flush timing is a common source of confusing test failures.

51.

What is the difference between the first and second level cache?

Senior

The first-level cache is the persistence context, scoped to a transaction and always on — it is why loading the same entity twice in one transaction issues one query. The second-level cache is shared across sessions, optional, and requires a provider like Ehcache or Hazelcast. Second-level caching introduces invalidation problems, so it should be a measured decision.

52.

How do you handle optimistic locking in JPA?

Senior

Add a @Version field. Every update includes the version in the WHERE clause and increments it, so a concurrent modification updates zero rows and throws OptimisticLockException. Catch it and either retry or surface a conflict to the user. It is the right default when conflicts are rare; pessimistic locking with @Lock(PESSIMISTIC_WRITE) is for genuinely contended rows.

53.

How do you manage database schema changes?

Senior

A migration tool — Flyway or Liquibase — with versioned, reviewed, forward-only scripts in source control. Never ddl-auto=update in any shared environment: it produces divergent schemas, cannot express data migrations, and will happily do something destructive. Use validate in production so a mismatch fails startup loudly.

54.

When would you use JdbcTemplate or native queries instead of JPA?

Senior

For complex reporting queries, bulk operations, and anything where you want exact control of the SQL and the plan. JPA is optimised for object graphs and identity, not for set-based work — a bulk update through entities loads every row, whereas one UPDATE statement does not. Mixing both deliberately is normal and mature.

Configuration & Profiles

55.

How do application.properties and application.yml work?

Fresher

Both externalise configuration; YAML is preferred for nested structures because it is less repetitive. Spring Boot loads them from the classpath and the working directory, and values are injected with @Value or bound to a @ConfigurationProperties class. Use one format consistently — having both is a reliable source of confusion about which wins.

56.

What are Spring Boot profiles?

Fresher

Named sets of configuration activated with spring.profiles.active, allowing per-environment settings in application-dev.yml, application-prod.yml and so on. @Profile on a bean includes it only under that profile. The profile-specific file overrides the base file rather than replacing it.

57.

What is the difference between @Value and @ConfigurationProperties?

Fresher

@Value injects a single property with SpEL support, which is fine for one-offs. @ConfigurationProperties binds a whole prefix to a typed object, supports validation with @Validated, gives relaxed binding and IDE completion, and fails fast on a missing required value. Prefer it for anything with more than a couple of settings.

58.

What is the property resolution order in Spring Boot?

2–5 yrs

Roughly: command-line arguments, then OS environment variables, then external application.properties beside the jar, then profile-specific files on the classpath, then the base classpath file, then @PropertySource, then defaults. Later sources lose. This is what makes the same artefact deployable everywhere with no rebuild.

59.

How do you manage secrets in a Spring Boot application?

2–5 yrs

Never in a committed properties file. Inject from environment variables, or read from a secret manager — Vault, AWS Secrets Manager, Kubernetes secrets — via Spring Cloud Config or the platform. Validate at startup so a missing secret fails immediately rather than on first use at 3am.

60.

What is relaxed binding?

2–5 yrs

Spring Boot matches property names loosely, so my-property, myProperty, MY_PROPERTY and my_property all bind to the same field. That is what allows environment variables — which cannot contain hyphens or dots — to override YAML keys, which is essential for container deployment.

61.

How would you handle configuration across many microservices?

Senior

Centralise it — Spring Cloud Config backed by Git, or the platform's config primitives (ConfigMaps and Secrets in Kubernetes). Keep per-service overrides small, version the config alongside the code that reads it, and support refresh where a restart is expensive. The failure mode to avoid is configuration drift between environments nobody can reconstruct.

62.

What is @ConditionalOnProperty and when is it useful?

Senior

It registers a bean only when a property has a given value, which is how you build feature flags and optional integrations into the wiring itself rather than into runtime branches. It keeps disabled features from being instantiated at all — so a misconfigured optional dependency cannot break startup.

Security

63.

What does Spring Security do by default when added to a project?

Fresher

It secures every endpoint, generates a default user with a password logged at startup, adds a login form, enables CSRF protection and sets security headers. That is deliberately restrictive — the framework prefers you to explicitly open things up rather than accidentally leave them open.

64.

What is the difference between authentication and authorisation?

Fresher

Authentication establishes who you are; authorisation decides what you may do. In Spring Security, authentication produces an Authentication object in the SecurityContext, and authorisation is enforced by request matchers or method-level annotations against its authorities.

65.

How do you configure a modern Spring Security filter chain?

2–5 yrs

Define a SecurityFilterChain bean using the lambda DSL — authorizeHttpRequests with matchers, then a session policy, then the authentication mechanism. WebSecurityConfigurerAdapter has been removed, so any example extending it is out of date. Order matters: the first matching rule wins, so put specific paths before broad ones.

66.

How would you implement JWT authentication?

2–5 yrs

Issue a signed token on login, then add a filter before the authentication filter that reads the Authorization header, validates the signature and expiry, and populates the SecurityContext. Set session management to STATELESS. Keep the access token short-lived with a refresh token, and remember that a stateless token cannot be revoked before expiry unless you maintain a denylist.

67.

What is CSRF and when do you need protection against it?

2–5 yrs

Cross-site request forgery — a third-party site causing an authenticated request using the browser's cookies. Protection matters when authentication is cookie-based; it is unnecessary for a stateless API authenticated by an Authorization header, because a cross-site request cannot set that header. Disabling CSRF on a cookie-authenticated app is a genuine vulnerability.

68.

What is the difference between @PreAuthorize and @Secured?

2–5 yrs

@Secured takes a plain list of roles. @PreAuthorize takes a SpEL expression, so it can express hasRole, hasAnyAuthority, and conditions referencing method arguments and the principal — @PreAuthorize("#id == authentication.principal.id"). @PreAuthorize is strictly more capable and is the modern choice.

69.

How do you store passwords in a Spring Boot application?

Senior

With a PasswordEncoder — BCryptPasswordEncoder or Argon2 — never plain text, never a bare hash, never MD5 or SHA-1. Use DelegatingPasswordEncoder, the default, which prefixes stored hashes with the algorithm id so you can migrate encoders without invalidating existing passwords.

70.

What are the most common security mistakes you see in Spring Boot APIs?

Senior

Exposing Actuator endpoints publicly; permitAll on a path that turns out to be a prefix match; disabling CSRF on a cookie-authenticated application; returning entities that leak fields; trusting a client-supplied id instead of the authenticated principal; and stack traces in error responses. Most are configuration, not code.

Testing

71.

What does @SpringBootTest do?

Fresher

It bootstraps the full application context for an integration test, optionally with a real or random port web environment. It is thorough and slow — for a single controller or repository, a sliced annotation starts far less and keeps the suite fast.

72.

What are the test slice annotations?

Fresher

@WebMvcTest loads only the web layer with MockMvc, @DataJpaTest only the persistence layer with an in-memory database and a rolled-back transaction per test, @JsonTest only serialisation. Each starts a minimal context, which is what keeps a large suite from taking minutes.

73.

What is the difference between @Mock, @MockBean and @Spy?

2–5 yrs

@Mock is plain Mockito with no Spring involved — right for unit tests. @MockBean replaces a bean in the Spring context with a mock, which also invalidates the cached context and can slow the suite. @Spy wraps a real object so unstubbed methods still execute. Prefer @Mock plus constructor injection wherever you can.

74.

How do you test a REST controller?

2–5 yrs

@WebMvcTest with MockMvc, mocking the service layer with @MockBean, then asserting status, headers and JSON body with jsonPath. It exercises routing, binding, validation and serialisation without a server or database. For a full end-to-end test use @SpringBootTest with a random port and TestRestTemplate.

75.

How do you test the persistence layer?

2–5 yrs

@DataJpaTest gives an isolated context with each test in a transaction rolled back afterwards. Prefer Testcontainers over H2 — an in-memory database has different SQL dialect behaviour, so tests can pass against H2 and fail against the real Postgres. Testing against the engine you deploy on is worth the startup cost.

76.

What is Testcontainers and why use it?

Senior

A library that starts real dependencies in Docker containers for the duration of a test — Postgres, Kafka, Redis. It removes the fidelity gap between an in-memory substitute and production, which is where a whole class of bugs hides. Spring Boot has first-class support via @ServiceConnection, which wires the container into the context automatically.

77.

Why is a Spring test suite slow, and how do you fix it?

Senior

Almost always context reloading. Spring caches contexts by configuration, so every distinct combination of annotations, @MockBean set or property override creates a new one. Standardise on a small number of configurations, avoid @MockBean where a plain Mockito mock will do, and use test slices rather than @SpringBootTest by default.

Actuator, Production & Microservices

78.

What is Spring Boot Actuator?

Fresher

A module exposing operational endpoints over HTTP or JMX — /health, /info, /metrics, /env, /loggers, /threaddump. It is how a container orchestrator knows whether your application is alive and ready. Only /health and /info are exposed by default, and that default exists for a reason.

79.

What is the difference between a liveness and a readiness probe?

Fresher

Liveness answers "is this process broken and in need of a restart"; readiness answers "should traffic be routed here right now". Actuator exposes /health/liveness and /health/readiness. Conflating them is a classic outage: a readiness failure caused by a slow dependency triggers a restart loop if wired to liveness.

80.

How do you secure Actuator endpoints?

2–5 yrs

Expose only what you need with management.endpoints.web.exposure.include, put the management endpoints on a separate port not routed publicly, and require authentication and an admin role for anything beyond health. /env and /heapdump leak configuration and memory contents, so an unsecured Actuator is a serious exposure.

81.

How do you add custom metrics?

2–5 yrs

Inject MeterRegistry and register counters, gauges, timers or distribution summaries — Micrometer is the abstraction, with exporters for Prometheus and others. Keep tag cardinality low: a tag with a user id or a request path containing an id explodes the metric count and can take down your metrics backend.

82.

How do you implement scheduling in Spring Boot?

2–5 yrs

@EnableScheduling plus @Scheduled with a fixedDelay, fixedRate or cron expression. Two production caveats: the default scheduler is single-threaded, so one long job delays every other; and in a multi-instance deployment every instance runs the job, so you need a distributed lock (ShedLock) or a leader election.

83.

What does @Async do and what are its pitfalls?

2–5 yrs

It runs a method on a separate thread and returns immediately or gives a CompletableFuture. Pitfalls: it works via a proxy so self-invocation is ignored; the default executor is unbounded in some versions, so define your own with a bounded queue; and exceptions in a void @Async method vanish unless you register an AsyncUncaughtExceptionHandler.

84.

How do you implement a circuit breaker?

Senior

Resilience4j via Spring Cloud, with @CircuitBreaker plus a fallback. The breaker opens after a failure-rate threshold, short-circuits calls for a wait period, then half-opens to probe. Pair it with a timeout and a bulkhead — a breaker alone does not help if the calls hang, because you still exhaust the thread pool.

85.

How would you trace a request across microservices?

Senior

Distributed tracing with Micrometer Tracing and an OpenTelemetry or Zipkin exporter, propagating a trace id and span id in headers. Include the trace id in every log line so logs and traces correlate. Without it, debugging a slow request across six services means guessing.

86.

What is service discovery and do you always need it?

Senior

A registry — Eureka, Consul — where services register and look each other up instead of using hardcoded hosts. On Kubernetes you generally do not need it: the platform provides DNS-based service discovery and load balancing already, so adding Eureka duplicates it. That is the answer interviewers are usually probing for.

87.

How would you make a Spring Boot service idempotent?

Senior

Accept a client-supplied idempotency key, store it with the result of the first successful request, and return that stored result for repeats rather than reprocessing. Enforce it with a unique constraint so two concurrent duplicates cannot both proceed. This matters because any retrying client — and every payment integration — will eventually send the same request twice.

88.

How do you reduce Spring Boot startup time and memory footprint?

Senior

Trim unused starters and exclude auto-configurations you do not need, use lazy initialisation selectively, and switch from JVM to a native image with Spring AOT and GraalVM where startup latency genuinely matters — serverless, for instance. Measure with the startup endpoint rather than guessing; the cost is usually a small number of heavy auto-configurations.

89.

How would you debug a memory leak in a running Spring Boot service?

Senior

Confirm the heap after full GC is trending up, take a heap dump (Actuator /heapdump or jmap), and open it in Eclipse MAT to find the dominator tree and leak suspects. In Spring applications the usual culprits are unbounded caches, ThreadLocals on pooled request threads, listeners never deregistered, and classloader leaks from repeated redeploys.

90.

What is the /info endpoint and how do you populate it?

Fresher

It exposes arbitrary application metadata — build version, git commit, environment. Populate it with info.* properties, or automatically by adding the build-info and git-commit-id goals to your build so the deployed artefact reports exactly which commit it came from. That single detail saves a lot of time during an incident.

91.

How do you configure logging in Spring Boot?

Fresher

Logback by default, configured with logging.level.* properties per package, logging.file.name for a file appender, or a full logback-spring.xml when you need custom appenders. logback-spring.xml (rather than logback.xml) is the one to use, because it supports Spring profiles and property placeholders.

92.

What is caching in Spring Boot and how do you enable it?

2–5 yrs

@EnableCaching plus @Cacheable, @CachePut and @CacheEvict on methods, backed by a provider — Caffeine for in-process, Redis for shared. Two caveats: it works via a proxy so self-invocation is not cached, and a cache with no TTL or eviction policy is a memory leak with extra steps.

93.

How do you handle retries for a flaky downstream call?

2–5 yrs

Spring Retry with @Retryable and @Recover, or Resilience4j's retry module, configured with a bounded attempt count and exponential backoff plus jitter. Only retry idempotent operations, and only on transient failures — retrying a 400 just multiplies the same error and retrying a non-idempotent POST can double-charge someone.

94.

What is the difference between @ControllerAdvice and @RestControllerAdvice?

2–5 yrs

@RestControllerAdvice is @ControllerAdvice plus @ResponseBody, so handler return values are serialised to the response body. Use the Rest variant for APIs. Both can be scoped to particular packages, annotations or controller types rather than applying globally.

95.

How do you connect a Spring Boot service to Kafka or RabbitMQ?

2–5 yrs

spring-kafka with @KafkaListener, or spring-amqp with @RabbitListener, both configured through properties. The interview substance is usually the delivery semantics: at-least-once means duplicates, so consumers must be idempotent, and you need a dead-letter destination for messages that will never succeed.

96.

How would you structure a Spring Boot codebase as it grows?

Senior

Package by feature rather than by layer — an order package containing its controller, service and repository — so a change touches one directory and the boundaries are visible. Layer-first packaging (controllers, services, repositories) looks tidy at ten classes and becomes a flat dumping ground at two hundred.

97.

What is the saga pattern and when would you need it?

Senior

A way to maintain consistency across services without a distributed transaction: a sequence of local transactions, each with a compensating action to undo it if a later step fails. Orchestrated (a coordinator drives it) or choreographed (services react to events). You need it because two-phase commit across HTTP services is impractical.

98.

How do you deal with the dual-write problem?

Senior

Writing to a database and publishing an event are two operations that can partially fail, leaving them inconsistent. The standard fix is the transactional outbox: write the event to an outbox table in the same transaction as the data, then have a separate process publish and mark it sent. Change data capture over the outbox is the same idea at lower latency.

99.

How would you performance-tune a slow Spring Boot endpoint?

Senior

Measure first — a timer around the endpoint plus tracing to see where the time goes. Most of the time it is the database: an N+1, a missing index, or a connection pool too small so requests queue. Then check serialisation of large payloads, external calls without timeouts, and synchronous work that could be deferred. Tuning the JVM is almost never the answer.

100.

How do you size a HikariCP connection pool?

Senior

Smaller than people expect. Pool size should be driven by the database's capacity for concurrent work, not by expected request concurrency — a common starting point is around (cores × 2) + effective spindle count, then measured. An oversized pool moves the queue from your application into the database, where it is harder to see and more damaging.

Get these answered live in your real interview

NostrobeAI is a real-time AI interview copilot — it hears the question and drafts a strong answer on your screen, invisible on Zoom, Meet, and Teams. One-time pricing, no subscription.

Try NostrobeAI free