LearnThatStack Ace your next interview

Spring Boot

Spring Boot 4, with notes where Boot 3 differs Checked Nov 2026 131 code snippets

The model

  • The ApplicationContext is the IoC container. It creates your objects, called beans, and injects what each one needs.
  • Auto-configuration creates beans from the libraries on the classpath. Define the same bean yourself and Boot's default backs off.
  • A starter adds a tested set of libraries with one dependency. The embedded server ships in the JAR, so java -jar starts the app.
  • @Transactional, @Async and @Cacheable work through a proxy. A call from inside the same class skips the proxy, and the feature with it.
  • Configuration comes from many sources in a fixed order. Command-line arguments beat environment variables, which beat files.
Your code@Component, @BeanClasspathstarters, librariesContextbeans, some proxiedCallera request, a beanSTARTUPregisters firstif conditions passcreate and injectRUNTIMEcall through proxyruns your method
Your beans register first, so auto-configuration adds only what its conditions allow. At runtime a proxy can wrap each call to a bean.

What Boot adds to Spring

starters, the main class and how an app starts

The main class

Mark a source of beans@SpringBootConfiguration
Turn on auto-config@EnableAutoConfiguration
Scan for components@ComponentScan

Tip@SpringBootApplication combines all three.

TrapScanning starts at the main class's package. Put that class in a root package above your other classes.

What happens at startup

1 Pick servlet, reactive or plain2 Prepare Environment and profiles3 Create context, load definitions4 Refresh: scan, then auto-configure5 Create singletons, start server6 Call ApplicationRunner, CommandLineRunner7 Publish ApplicationReadyEvent

TrapThe server listens from step 5, so a request can arrive while the runners still work.

Beans & injection

how the container builds and wires your objects

IoC and the container

Define IoC and DIA container creates objects (IoC) and passes in what each needs (DI)
Catch bad config earlyApplicationContextCreates singletons at startup, unlike BeanFactory
Layer two contextsSpringApplicationBuilderA child sees its parent's beans, not the reverse

TrapCall new for a dependency and tests can't mock it.

Inject a dependency

Require a dependencyConstructor. A single constructor needs no @Autowired
Make one optionalSetter, or required = false
Choose among matches@Qualifier@Primary
Match by type@Autowired@Inject@Inject is JSR-330, and @Named picks one
Match by name first@ResourceJSR-250, not on a constructor

TipConstructors allow final fields and easy tests. Field injection hides what a class needs, so avoid it.

TrapEvery injection point is required by default, so startup fails when no bean matches.

Bean scopes

Share one or make manysingletonprototype
Use a web scoperequest, session, application, websocket

TipA singleton is shared by every thread, so it should hold no changing state.

TrapA prototype injected into a singleton is injected once. Inject an ObjectProvider to get a fresh one.

Circular dependencies

Predict a constructor cycleIt fails fast with BeanCurrentlyInCreationException
Predict a setter cyclePlain Spring uses an early reference. Boot refuses since 2.6
Break a cycle@LazyA proxy fetches the bean on first call

TipThe better fix removes the cycle. Move shared logic to a third bean, or publish an event.

Properties & profiles

one JAR, configured per environment

Properties and profiles

Read one value@Value("${app.name}")
Bind to a typed class@ConfigurationPropertiesSERVER_PORT then sets server.port
Override per profileapplication-dev.properties
Tie a bean to a profile@Profile("prod")
Pick a profile at start--spring.profiles.active=prodSPRING_PROFILES_ACTIVE=prod

TrapKeep secrets out of profile files. Supply them as environment variables, or from a secret store.

Which setting wins

command-line argumentshighestSPRING_APPLICATION_JSONJava system propertiesOS environment variablesprofile file, outside the JARplain file, outside the JARprofile file, inside the JARplain file, inside the JAR

TrapAn external application.properties beats a packaged application-prod.properties.

Logging with Logback

Set a package's levellogging.level.com.example=DEBUG
Write a log filelogging.file.name=app.log

TrapSpring extensions don't work in plain logback.xml. Use logback-spring.xml.

Auto-configuration

why beans appear, and how to control them

How auto-configuration decides

Apply if a class exists@ConditionalOnClass
Apply if no such bean@ConditionalOnMissingBean
Apply on a property value@ConditionalOnProperty
Turn one offspring.autoconfigure.exclude
See what matched--debugIt prints the conditions report

TipYour configuration runs first, so @ConditionalOnMissingBean sees your bean and backs off.

Fix a slow startup

Find the slow stepsBufferingApplicationStartupRead Actuator's startup endpoint
Create beans on first usespring.main.lazy-initialization=true
Reuse a training runAOT cache on Java 25+. A GraalVM native image is faster still

TipHeavy @PostConstruct work blocks startup. Move it to first use or a background task.

TrapWith lazy initialization, a misconfigured bean fails on first use, not at startup.

REST & Spring MVC

from HTTP request to JSON response

Controllers and mappings

Render an HTML page@ControllerIt returns a view name
Return JSON or XML@RestController@Controller plus @ResponseBody
Declare routes in codeRouterFunction
Read, create, replace@GetMapping@PostMapping@PutMapping
Patch or delete@PatchMapping@DeleteMapping

Trap@RequestMapping with no method matches every HTTP method. Keep it for a class's path prefix, and use the shortcuts on methods.

WebFlux and HTTP clients

Make blocking callsRestClient
Read old codeRestTemplateDeprecated in Spring 7.1
Make reactive callsWebClient
Block a thread per requestSpring MVC, on a servlet container
Use event loop threadsMono<User>Flux<User>WebFlux, on Netty by default

TrapOne blocking call, such as plain JDBC, stalls an event loop thread and delays every request on it.

Data & transactions

repositories, queries and schema changes

Query, page and sort

Derive it from the namefindByLastNameexistsByEmail
Write JPQL by hand@Query("SELECT u FROM User u")nativeQuery = true runs plain SQL
Update or delete@ModifyingRun it in a transaction
Page from the requestPageableSpring MVC reads page, size, sort
Count, or skip the countPage<User>Slice<User>

TipSpring checks property names when it creates the repository, so a typo fails at startup.

TrapSpring doesn't validate sort values. Check them against allowed property names.

Transactions

Mark as read-only@Transactional(readOnly = true)Hibernate skips dirty checking
Join, or run on its ownREQUIREDREQUIRES_NEW

TrapOnly unchecked exceptions roll back by default. A checked exception commits unless rollbackFor names it.

Migrate the schema

Add Flyway on Boot 4spring-boot-starter-flyway
Add it before Boot 4flyway-core
Name a scriptV2__Add_phone.sql

TipWith migrations, set ddl-auto to validate or none, so Hibernate never changes the schema.

TrapNever edit a script after it has run, because Flyway compares checksums. Add a new script.

Proxies, caching & async

features that wrap your bean in a proxy

How a proxy works

callerproxybean
from outsideThe proxy runs the transaction or cache logic, then calls the bean.
proxya()b()
from insidea() calls b() directly, so the proxy never sees the call to b().
Proxy an interfaceJDK dynamic proxy. Inject it by interface type
Subclass the classCGLIB, Boot's default. It can't intercept final methods

TrapA final method runs on the proxy itself and skips the advice.

Spring Security

who the user is, and what they may do

Log in and check access

Verify who the user isAuthentication. SecurityContextHolder keeps the result
Decide what they may doAuthorization, by URL or by method
Log in on a pageformLogin
Send a password each timehttpBasicIt needs HTTPS
Send a signed tokenJWT, for stateless APIs
Sign in through GoogleOAuth2 login

TipThe starter alone locks every endpoint behind a generated password.

TrapA logged-in user without the role gets 403 Forbidden, not a login redirect.

Set access rules

Open or restrict a pathpermitAll()hasRole("ADMIN")
Hash and load usersBCryptPasswordEncoderUserDetailsService
Secure one method@PreAuthorize

TipTurn CSRF off only for a stateless API that doesn't use cookies.

TrapSpring checks requestMatchers in order, so put specific paths before anyRequest().

Filter chain and JWT

Split API and UI rulesFilterChainProxyIt runs only the first SecurityFilterChain that matches
Handle security errorsExceptionTranslationFilter
Let Spring check tokensoauth2ResourceServerA JwtDecoder checks signature and expiry
Check tokens yourselfOncePerRequestFilterUse STATELESS sessions

TipAdd your own filter with addFilterBefore.

TrapSpring Boot also registers a @Component filter with the servlet container. Turn that off with setEnabled(false) on a FilterRegistrationBean.

Test at every layer

unit tests, slices and the full context

Production & microservices

monitoring, and what Spring Cloud adds
Found this useful? Pass it on.
Pro · $10/mo

This sheet stays free. With Pro, you can:

  • Every answer on this sheet. Read the full answer to all 72 questions it links, not just the 10 free ones.
  • My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
  • PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
  • The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.