Chapter 16

FAQ and interview questions

Fifty questions, roughly ordered from fundamentals to internals. Useful as a revision pass after the course, and as preparation on either side of an interview table.

⏱ 25 min readLevel: allReference

Fundamentals

1 · What is Spring Boot?

A layer on top of the Spring Framework providing starters, auto-configuration, externalised configuration, an embedded server and production-ready features. It does not replace Spring — it configures it.

2 · Spring vs Spring Boot vs Spring Cloud?

Spring is the core container and programming model. Boot is opinionated setup on top of it. Cloud adds distributed-systems patterns (config server, discovery, gateway, resilience) on top of Boot.

3 · What does @SpringBootApplication do?

It combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. Scanning starts from the annotated class's package.

4 · What is inversion of control?

Objects declare what they need instead of creating it. The container builds and wires them. Dependency injection is how it is delivered.

5 · What is a Spring bean?

Any object instantiated and managed by the container — no special type or interface required.

6 · Difference between @Component, @Service and @Repository?

Technically almost none — all three are component-scanned. @Repository adds persistence exception translation. @Service is purely semantic.

7 · What is a starter?

A dependency-only pom that pulls a curated, version-aligned set of libraries. It contains no code.

8 · Why can I omit versions in my pom?

spring-boot-starter-parent (or the dependency-management BOM) declares managed versions for roughly 400 libraries that are tested together.

Dependency injection

9 · Which injection type should I use and why?

Constructor injection. It allows final fields, makes dependencies explicit, fails fast on circular dependencies, and lets you build the object with new in a test.

10 · Is @Autowired required on a constructor?

No, not since Spring 4.3 — if the class has exactly one constructor it is used automatically.

11 · @Primary vs @Qualifier?

@Primary marks the default when several candidates match. @Qualifier selects a specific one at an injection point and takes precedence.

12 · What happens if two beans match and neither is primary?

NoUniqueBeanDefinitionException at startup, listing the candidates.

13 · What are the bean scopes?

singleton (default), prototype, and the web scopes request, session and application.

14 · Are singleton beans thread-safe?

Spring does nothing to make them so. One instance is shared across all threads, so any mutable state is a race condition. Keep them stateless.

15 · How do I inject a prototype bean into a singleton?

A plain injection resolves once and freezes. Use a scoped proxy (proxyMode = TARGET_CLASS) or inject ObjectProvider<T> and call getObject().

16 · How do I fix a circular dependency?

Extract the shared concept into a third bean, or replace the call with an application event. @Lazy and allow-circular-references=true hide the problem rather than solving it.

17 · Describe the bean lifecycle.

Instantiate → inject dependencies → aware callbacks → BeanPostProcessor before-init → @PostConstruct / afterPropertiesSet → post-processor after-init (proxy created here) → ready → @PreDestroy on shutdown.

Auto-configuration

18 · How does auto-configuration work?

@EnableAutoConfiguration imports a selector that reads AutoConfiguration.imports from every jar, then filters those candidates using their @ConditionalOn… annotations. Survivors register beans.

19 · How do I override an auto-configured bean?

Define your own. Boot's is annotated @ConditionalOnMissingBean and backs off. Prefer a property or a *Customizer first — replacing the bean discards all the other defaults.

20 · How do I find out why a bean was not created?

Run with --debug and read the CONDITIONS EVALUATION REPORT, or hit /actuator/conditions. The negative-match section states the exact reason.

21 · How do I disable an auto-configuration?

@SpringBootApplication(exclude = Xxx.class) or spring.autoconfigure.exclude. Usually a sign you should configure it instead.

22 · How do I write my own starter?

An @AutoConfiguration class with conditions and @ConditionalOnMissingBean beans, listed in META-INF/spring/…AutoConfiguration.imports. Name it xxx-spring-boot-starter, and never use @ComponentScan inside it.

Configuration

23 · What is the property source precedence?

Command line args → OS environment variables → external profile file → external file → packaged profile file → packaged application.yml → defaults in code.

24 · @Value vs @ConfigurationProperties?

@Value for a single value or SpEL. @ConfigurationProperties for everything else: type-safe, validatable, supports nesting and relaxed binding.

25 · What is relaxed binding?

max-page-size, maxPageSize, max_page_size and MAX_PAGE_SIZE all bind to the same property. It applies to @ConfigurationProperties, not to @Value.

26 · How do profiles work?

application.yml always loads; application-{profile}.yml then overrides the keys it declares. Beans can be @Profile-scoped. Activate with spring.profiles.active.

27 · Where should secrets live?

Environment variables, mounted secret files, or a secret manager. Never in a file inside the jar or the repository.

Web layer

28 · @Controller vs @RestController?

@RestController = @Controller + @ResponseBody: return values are serialised into the response body instead of resolved as view names.

29 · Walk through the request lifecycle.

Tomcat → filter chain → DispatcherServlet → HandlerMapping → HandlerAdapter → argument resolvers → your controller → HttpMessageConverter → response. Exceptions go to HandlerExceptionResolver and then your @RestControllerAdvice.

30 · Why not return entities from controllers?

It couples the API contract to the schema, leaks newly added fields, and triggers lazy loading during serialisation. Use DTOs.

31 · How do I handle exceptions globally?

One @RestControllerAdvice with @ExceptionHandler methods returning ProblemDetail. Note it cannot catch 401/403 — those happen in the security filters.

32 · @Valid vs @Validated?

@Valid is the Jakarta annotation, used on @RequestBody and to cascade into nested objects. @Validated is Spring's, goes on the class to enable method-parameter validation, and supports validation groups.

33 · RestTemplate, WebClient or RestClient?

RestTemplate is in maintenance mode. RestClient for synchronous calls (Boot 3.2+), WebClient for reactive or streaming.

Data and transactions

34 · How does Spring Data generate repository implementations?

A proxy parses the method name into a query at startup, or uses the @Query you supplied. Invalid method names fail at startup, not at runtime.

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

One query for a list plus one per row for a lazy association. Fix with JOIN FETCH or @EntityGraph; prevent regressions by asserting query counts in tests.

36 · Why set open-in-view=false?

The default holds a connection for the entire request including serialisation, hiding N+1 queries and exhausting the pool under load.

37 · How does @Transactional work?

A proxy begins a transaction before the method, commits after it, and rolls back on unchecked exceptions. It only applies to calls that arrive through the proxy.

38 · Why did my @Transactional not roll back?

Self-invocation; a non-public method; a checked exception; the exception was caught; or the class is not a Spring bean.

39 · Explain propagation.

REQUIRED joins or starts. REQUIRES_NEW suspends and starts a fresh one. MANDATORY requires an existing one. NESTED uses a savepoint. SUPPORTS, NOT_SUPPORTED and NEVER cover the rest.

40 · What does readOnly = true actually do?

Sets the Hibernate flush mode to manual, skips dirty-check snapshots, and marks the JDBC connection read-only (which can route to a replica).

41 · Optimistic or pessimistic locking?

Optimistic (@Version) by default — no locks held, conflicts surface as a 409. Pessimistic (SELECT … FOR UPDATE) only when a retry is unacceptable.

Proxies, security, testing

42 · JDK proxy vs CGLIB?

JDK proxies implement interfaces; CGLIB subclasses the class. Boot uses CGLIB by default, which is why private, final and static methods cannot be intercepted.

43 · Why does my @Async method run synchronously?

Self-invocation, or @EnableAsync is missing. Also make sure you defined a bounded executor — the fallback creates unlimited threads.

44 · 401 vs 403?

401 = not authenticated ("who are you?"). 403 = authenticated but not permitted ("I know you, and no").

45 · How do you configure Spring Security 6?

A SecurityFilterChain bean using the lambda DSL. WebSecurityConfigurerAdapter was removed in version 6.

46 · Should CSRF be disabled?

Only for stateless APIs authenticated by a bearer header. If you use session cookies — or a JWT stored in a cookie — keep it enabled.

47 · @SpringBootTest vs a test slice?

@SpringBootTest loads the whole context. Slices such as @WebMvcTest and @DataJpaTest load one layer and are far faster. Use slices by default.

48 · Why is my test suite slow?

Context caching misses. Every distinct combination of profiles, properties and @MockitoBean declarations builds a new context. Standardise on shared base classes.

49 · Liveness vs readiness?

Liveness failure restarts the pod, so it must not depend on external systems. Readiness failure removes it from the load balancer, and is where dependency checks belong.

50 · How do you deploy a Spring Boot app properly?

One layered image built once per commit, promoted by digest across environments, configured by environment variables, with graceful shutdown, distinct probes, MaxRAMPercentage instead of -Xmx, and actuator on an internal port.

Annotation cheat sheet

Container

@Component @Service @Repository
@Configuration @Bean
@Autowired @Qualifier @Primary
@Scope @Lazy @DependsOn @Order
@PostConstruct @PreDestroy
@Profile @ConditionalOnProperty

Web

@RestController @RequestMapping
@GetMapping @PostMapping @PutMapping
@PatchMapping @DeleteMapping
@PathVariable @RequestParam @RequestBody
@RequestHeader @ModelAttribute
@ResponseStatus @RestControllerAdvice
@ExceptionHandler @CrossOrigin

Data

@Entity @Table @Id @GeneratedValue
@Column @Enumerated @Version
@ManyToOne @OneToMany @ManyToMany
@JoinColumn @JoinTable
@Query @Modifying @Param
@EntityGraph @Lock @Transactional

Testing

@SpringBootTest @WebMvcTest
@DataJpaTest @JsonTest @RestClientTest
@MockitoBean @MockitoSpyBean
@ActiveProfiles @TestPropertySource
@Sql @Testcontainers @ServiceConnection
@WithMockUser

Boot-specific

@SpringBootApplication
@EnableAutoConfiguration
@ConfigurationProperties
@ConfigurationPropertiesScan
@AutoConfiguration
@ConditionalOnClass / OnMissingBean
   / OnProperty / OnWebApplication

Cross-cutting

@Aspect @Pointcut @Around @Before
@EnableAsync @Async
@EnableScheduling @Scheduled
@EnableCaching @Cacheable @CacheEvict
@EventListener @TransactionalEventListener
@Retryable @Recover @Observed

The one-line answers worth memorising

SymptomCause
Bean not found at startupClass outside the main class's package tree
Annotation silently does nothingSelf-invocation, or a non-public method
Transaction did not roll backChecked exception, or it was caught
Property ignoredA higher-precedence source overrides it
Everything returns 401Security starter added without configuration
Security rule has no effectanyRequest() was declared before it
Endpoint slow, database fineN+1 queries
Pool exhaustedopen-in-view, or a leaked connection
OOM-killed with a healthy heapNon-heap memory — no MaxRAMPercentage headroom
Test suite very slowContext cache misses
That is the whole course

Sixteen chapters, from main() to Kubernetes probes. If something was unclear or you hit a case we did not cover, tell us — reader questions are where the next chapters come from. If your data access is the interesting part of your problem, the MyBatis course is the natural next step.