All 75 Spring Boot quiz questions below come with a short explanation, visible right on the page — no sign-in needed. They're grouped by beginner and intermediate levels and 28 subtopics, so you can revise one part at a time. Choose Try Spring Boot quiz above to take a scored run and review the questions you got wrong.
What the Spring Boot quiz covers
Spring MVC / REST12
IoC & DI7
Spring Data JPA6
Actuator & Monitoring5
Configuration & Profiles5
Data & Transaction5
Bean Scope & Lifecycle4
Validation4
Testing3
Auto-configuration2
Configuration2
Basics2
JPA2
Security Basics2
Actuator1
AOP1
Async & Scheduling1
Bean1
Build1
Caching1
Development1
HTTP Client1
JSON1
Logging1
Migration1
Modern Spring1
Packaging1
Web1
Beginner level — 20 Spring Boot questions
Question 1·IoC & DI
Given the two bean declarations below, which statement about the difference between @Component and @Bean is correct?
A.@Bean and @Component create beans with different scopes: @Bean is always prototype and @Component is always singleton
B.Only @Bean creates a real Spring bean; a @Component class is just a plain POJO not managed by the container
C.@Component works only for classes that ship with the framework, while @Bean is for classes in your own application
D.@Component lets Spring instantiate the class via component scan; @Bean returns an object you build yourself
Answer: D
@Component goes on your class — Spring discovers it via component scan and instantiates it with the default constructor. @Bean goes on a method in @Configuration and returns an object you create yourself, suitable for external library classes (RestTemplate, ObjectMapper) or init needing custom logic. Both default to singleton scope.
Which statement about singleton scope — the default bean scope in Spring — is correct?
A.Singleton scope makes the bean thread-safe automatically: Spring wraps each method in a synchronized block so shared state is fine
B.Singleton means each HTTP request gets its own instance of the bean
C.Exactly one shared instance; keep it stateless because Spring does NOT make it thread-safe for you
D.Spring creates all singleton beans up front but hands out a fresh copy of the instance at each injection point
Answer: C
Singleton is the default scope: the container creates exactly one instance and shares it at every injection point in the app. Because it's shared across threads, singleton beans should be stateless — Spring does NOT synchronize or make it thread-safe. Keeping mutable state in a singleton is a source of race conditions; for per-request state use request scope or local variables.
@SpringBootApplication combines three annotations: @Configuration (the class is a source of bean definitions), @EnableAutoConfiguration (enables auto-configuration based on classpath), and @ComponentScan (scans components from the current package downward). So the main class should be placed in the root package so @ComponentScan can scan all sub-packages.
A client calls GET /api/users/1 against the controller below. What is the response body?
java
@RestController@RequestMapping("/api/users")classUserController {
@GetMapping("/{id}")
User getUser(@PathVariable Long id) {
returnnewUser(id, "Ann");
}
}
A.Spring treats "Ann" as a view name, looks for a user template and renders HTML
B.The JSON of the User object — @RestController = @Controller + @ResponseBody
C.Compile error — a controller method may not return an arbitrary object type, it must be String or ResponseEntity
D.An empty body with status 200 — the method returns an object but lacks @ResponseBody so nothing is written
Answer: B
Returns the JSON of the User object, e.g. {"id":1,"name":"Ann"}. @RestController = @Controller + @ResponseBody, so every method by default writes the return value straight into the response body via a message converter (Jackson) instead of treating it as a view name. This is the core difference from @Controller — which is used for web MVC returning HTML templates.
The app runs with spring.profiles.active=prod. Which config files does Spring load, and how do they take precedence?
A.Only application-prod.yml is loaded; application.yml is ignored entirely when a profile is active
B.application.yml overrides application-prod.yml because the base file always has the highest precedence
C.You must build a separate artifact for prod because Spring cannot pick configuration per environment at runtime
D.It loads application.yml and then application-prod.yml overrides it for identical keys
Answer: D
Spring loads application.yml (base) then merges application-prod.yml on top; for the same key, the value in the active profile file overrides the base. Activation is via spring.profiles.active=prod (or the SPRING_PROFILES_ACTIVE environment variable). This way you deploy ONE JAR for every environment and pick the config at runtime. Beans can also carry @Profile("prod") to exist only in the corresponding environment.
A.@RestController = @Controller + @ResponseBody, so return values go into the response body
B.@RestController adds CORS to every endpoint automatically, @Controller does not
C.@RestController only accepts GET requests, while @Controller accepts every HTTP method
D.@Controller was removed in Spring Boot 3, only @RestController remains
Answer: A
@RestController = @Controller + @ResponseBody. Return values are written directly into the response body via HttpMessageConverter (Jackson by default → JSON). Without @ResponseBody, @Controller interprets the returned string as a view name for the template engine to render.
When should a controller return ResponseEntity<T> rather than the plain object T?
A.When you need to control the response's status code and headers
B.Always — returning a plain object was removed in Spring Boot 3
C.When you want JSON — returning a plain object always makes Spring return XML
D.When the controller must run asynchronously; returning a plain object always blocks the thread
Answer: A
Use ResponseEntity when you need to decide the status yourself or add headers. Returning a plain object always gives 200 OK (unless @ResponseStatus is present). Typical cases for ResponseEntity: 201 Created with a Location header, or branching between 200/404 right inside the method.
A.Spring silently resets the email to an empty string and continues
B.Spring throws MethodArgumentNotValidException and returns 400 before entering the method
C.The method runs normally; to find out about errors you must call a validator yourself inside the body
D.It returns 500 Internal Server Error because the exception is uncaught
Answer: B
It returns 400 Bad Request, and service.create is never called. @Valid triggers Bean Validation as soon as @RequestBody is bound; a constraint violation raises MethodArgumentNotValidException, which Spring Boot maps to 400 out of the box. The spring-boot-starter-validation library must be on the classpath.
A.It calls a stored procedure of the same name in the database
B.Spring Data parses the method name by convention and generates the query at runtime
C.JpaRepository already declares this method in a parent interface
D.An annotation processor generates a .java file at build time, visible under generated-sources
Answer: B
Spring Data reads the method name and generates the corresponding query at runtime, then creates a proxy as the implementation. findByEmailAndActiveTrue is parsed into where email = ?1 and active = true. A typo in a field name makes the application fail at startup, not at call time.
What do you get by adding spring-boot-starter-actuator to a project?
A.Every endpoint exposed publicly by default, including /actuator/env and /actuator/heapdump
B.A set of ready-made operational endpoints: /actuator/health, /metrics, /info
C.Automatic caching and load balancing for every application endpoint
D.A full web admin UI for editing configuration at runtime
Answer: B
Actuator adds operational endpoints: health for liveness/readiness probes, metrics for Prometheus/Micrometer, info, env, loggers, httpexchanges. By default only health is exposed over HTTP; the rest must be enabled explicitly via management.endpoints.web.exposure.include.
How do @Component, @Service and @Repository differ?
A.They all register a bean; @Repository additionally translates data-layer exceptions
B.Only @Component is scanned automatically, the other two must be declared manually
C.Each annotation creates a bean with a different default scope
D.They determine the order in which beans are created at startup
Answer: A
All three register beans and are all scanned automatically — the latter two are meta-annotations of the first. The only technical difference: the data-layer annotation triggers translation of vendor exceptions into Spring's common exception hierarchy.
What makes a Spring Boot application runnable with java -jar?
A.Spring Boot installs an application server into the operating system at startup
B.The JVM finds and downloads the dependencies from a central repository at runtime
C.The configuration file declares a port so the jar opens a listening socket by itself
D.A fat jar containing both the dependencies and an embedded web server
Answer: D
The jar package contains both the dependent libraries and an embedded web server. Previously you had to package as a WAR and deploy to an externally installed application server — now the application is self-contained with everything it needs.
How do application.properties and application.yml differ?
A.One is for development and the other for production
B.One is read at build time and the other at runtime
C.Only the format differs; both are read into the same configuration
D.One supports environment variables and the other does not
Answer: C
Only the format differs; both resolve to the same set of configuration. The hierarchical form is more compact with many nested keys; the key-value form is simpler and has no indentation pitfalls.
A Spring Boot app runs on port 8080. How do you change it to 9000?
A.Pass the port into the startup call in the main class
B.Set the server's port property in the configuration
C.Edit the configuration of a Tomcat installed on the system
D.Declare the port in the application's deployment descriptor
Answer: B
Set the server port property in the configuration. It can be read from a config file, an environment variable, or a command-line argument, so it can be changed per environment without editing code or rebuilding.
A.Only the annotations used for controllers and routing
B.A code generator for REST endpoints
C.An embedded server, the MVC layer and a JSON library
D.A web server that must be installed separately on the system
Answer: C
It brings an embedded server, the MVC layer, and a JSON processing library along with their dependencies. This lets the app run with a single command without installing a separate web server.
How does @GetMapping("/users") differ from the equivalent @RequestMapping?
A.The shorthand only works in a class that returns data
B.The general form supports several paths while the other does not
C.It is merely shorthand with identical behaviour
D.The shorthand routes more efficiently
Answer: C
It's just shorthand; the behavior is identical. The HTTP-method-specific annotations are defined on top of the general one, so they're shorter and clearer about intent.
Spring Boot dependencies usually omit version numbers. Why?
A.Spring's libraries have no version numbers of their own
B.The build tool always fetches the newest version at build time
C.The version is decided by Spring Boot's dependency management
D.The version is taken from the runtime environment at startup
Answer: C
Because Spring Boot's dependency management already declares versions for hundreds of common libraries, and they're verified to be compatible with each other. Bumping the Spring Boot version upgrades that whole set at once.
It automatically restarts the app when code changes, disables template caching, and enables some development-friendly settings. It disables itself when the app runs as a packaged build in production.
A @Service outside the main class package is not detected. Why?
A.That annotation only works in the project's root package
B.Component scanning starts from the main class's package
C.The other packages must be compiled separately first
D.The class must also be declared in a configuration file
Answer: B
Because component scanning starts from the package containing the main class and only descends into subpackages. A class outside that scope isn't detected, and the app reports a missing-bean error wherever it's needed.
B.A corresponding repository interface declared in advance
C.Getter and setter methods for every field
D.A primary key and a no-argument constructor
Answer: D
A primary key and a no-argument constructor. The mapping library creates objects via reflection and then sets the fields, so it needs the empty constructor — this is why entity classes can't use immutable record types.
Which statement about dependency injection and @Autowired in Spring is FALSE?
A.@Autowired requires a matching bean by default, and the app fails to start when one is missing
B.Field injection makes unit testing easier because you do not have to declare a constructor
C.Setter injection suits optional dependencies (ones that may be absent)
D.For a class with exactly one constructor, since Spring 4.3+ you no longer need to write @Autowired on it
E.Constructor injection allows final fields (immutability) and makes required dependencies explicit
Answer: B
Constructor injection allows final fields and makes dependencies explicitly required; a class with exactly one constructor doesn't need @Autowired since Spring 4.3+; setter injection suits optional dependencies. Conversely, field injection is harder to test (needs reflection), and @Autowired defaults to required=true so a missing bean prevents the app from starting.
A.Yes — since Task is a prototype, Spring creates a new Task every time Worker touches it
B.Startup error — you may not inject a prototype bean into a singleton bean
C.No — Worker is a singleton, so Task is injected exactly once at construction time
D.Yes — Spring detects the prototype and injects a provider, so each handle() gets a fresh Task with no extra work
Answer: C
No. Worker is a singleton so Spring injects Task only once — at Worker initialization. Even though Task is declared prototype, every later handle() call reuses that same injected instance. Prototype only creates a new one at injection/getBean time, not on each access. To get a new Task each time, use ObjectProvider<Task>, a @Lookup method, or call getBean().
A.All three come from the query string, because every controller method parameter comes from a query parameter
B.id and page both come from the path; body is read from the query string as an encoded JSON string
C.id from the path {id}, page from the query string, body from the request body
D.id from the query string, page from the path, body from a header — the declaration order decides the source
Answer: C
@PathVariable Long id comes from the path segment of the URL (/users/42/notes → 42). @RequestParam int page comes from the query string (?page=2), optional because of defaultValue. @RequestBody NoteDto body comes from the request body content — Jackson deserializes JSON into the object. The data source is determined by the annotation, not the parameter declaration order.
A.Startup error — you may not put @Transactional on a method that is called internally within the same class
B.Yes — Spring rewrites the method's bytecode at compile time to insert transaction logic, so self-invocation is still covered
C.No — calling this.processOne() bypasses the AOP proxy, so @Transactional is ignored
D.Yes — @Transactional is on the method itself so it always takes effect no matter where the call comes from
Answer: C
No. Spring applies @Transactional through an AOP proxy wrapping the bean: only calls coming from OUTSIDE the proxy trigger begin/commit. Calling this.processOne() is self-invocation — it goes straight into the object, bypassing the proxy — so @Transactional is ineffective and processOne runs without a transaction. Fix: extract processOne into another service and inject it, or self-inject the proxy.
When should you use @ConfigurationProperties instead of @Value to read configuration?
A.@ConfigurationProperties is mandatory for every property; @Value was deprecated in Spring Boot 3
B.@ConfigurationProperties is faster at runtime because it reads the property straight from the file on each access, bypassing the Environment
C.When you need to bind a GROUP of properties into a type-safe class/record, with validation
D.Only @Value can read from application.yml; @ConfigurationProperties reads only from environment variables
Answer: C
Use @ConfigurationProperties when you need to bind a GROUP of related properties (usually ≥3 keys) into a class/record: type-safe, full type conversion, validatable via @Validated + Bean Validation, plus IDE autocomplete/navigation. Use @Value for a single property or when you need a SpEL expression. Both read from the same Environment; the difference is in bind scope and type-safety.
In Spring AOP, what are the roles of a Pointcut and of @Around advice?
A.The pointcut is the cross-cutting logic that executes; @Around is where you declare the method-selection pattern
B.@Around can only run AFTER the method finishes and cannot alter the return value
C.The pointcut selects which methods are intercepted; @Around wraps them and must call proceed()
D.Pointcuts and @Around work only on static methods and must be declared in a separate XML file
Answer: C
A Pointcut is an expression selecting which join points (methods) get intercepted, e.g. execution(* com.example.service.*.*(..)). @Around is advice wrapping the method: it receives a ProceedingJoinPoint, runs logic before, calls proceed() to execute the real method, then runs logic after — controlling both the return value and exceptions. AOP is used to separate cross-cutting concerns (logging, security, transaction) from business logic.
In Spring Security, how do authentication and authorization differ?
A.Authorization happens first to filter permissions, and authentication then verifies the user's identity
B.Authentication checks roles and scopes; authorization checks the password and login token
C.Authentication is "who are you", authorization is "what may you do"; authentication comes first
D.The two words mean the same thing — checking username and password — they are just different names
Answer: C
Authentication ("Who are you?") verifies identity — password login, JWT, OAuth. Authorization ("What are you allowed to do?") checks permissions — role, scope. Authentication always happens first. In Spring Security: authentication builds an Authentication and stores it in the SecurityContextHolder; authorization reads from it and applies rules per URL (authorizeHttpRequests) or per method (@PreAuthorize).
A.500, because any unhandled exception becomes an Internal Server Error
B.404 but with an empty body, because @ResponseStatus always strips the body
C.200, because the handler returns an object successfully so the request counts as processed
D.404 with an ApiError JSON body — @ResponseStatus decides the status
Answer: D
404 with a JSON body of ApiError. @RestControllerAdvice = @ControllerAdvice + @ResponseBody, centralizing exception handling for all controllers. @ExceptionHandler picks the exception type, @ResponseStatus sets the status, and the return value becomes the response body.
A.You must NOT call save — it would insert a duplicate record
B.Required — without save the change stays in memory and is lost
C.Not required — a managed entity is dirty-checked at commit time
D.Required, because findById always returns a detached copy
Answer: C
Not required. Inside a transaction, the entity from findById is managed — the persistence context compares state at commit and issues an UPDATE for the changed parts automatically. Calling save is redundant. Outside a transaction the entity is detached, and only then is save actually needed.
Why is constructor injection recommended over field injection (@Autowired on the field)?
A.Field injection was removed in Spring Boot 3 so it no longer works
B.You can declare final fields, tests need no Spring, and circular dependencies surface at startup
C.Only constructor injection can inject prototype-scoped beans
D.Constructor injection is faster at runtime because Spring avoids reflection
Answer: B
Three reasons: dependencies can be final, so they are immutable and the object is always valid right after creation; unit tests can new the service directly with mocks, no Spring context needed; and circular dependencies surface at startup instead of being hidden by field injection.
A.After the constructor and after every dependency has been injected
B.In parallel with the constructor on another thread
C.Before the constructor, to prepare data for the constructor to use
D.Only when the first request reaches the application
Answer: A
Order: constructor → inject the remaining dependencies → @PostConstruct → bean ready for use. So @PostConstruct is the right place for initialization that needs dependencies. @PreDestroy runs symmetrically when the context closes, good for cleaning up resources.
application.yml sets app.timeout=30 while the container has environment variable APP_TIMEOUT=60. Which value does the application read?
A.30 — the application's own configuration file always wins because it is more specific
B.60 — environment variables outrank files, and relaxed binding matches the name
C.The application fails to start because two configuration sources conflict
D.30, because an uppercase underscore environment variable name does not match a lowercase dotted key
Answer: B
60. Spring Boot orders configuration sources by precedence, and environment variables rank above the application.yml packaged in the jar. Relaxed binding maps APP_TIMEOUT to app.timeout. This is exactly what lets the same image run across multiple environments.
Which statement about Spring Boot test annotations is correct?
A.@DataJpaTest keeps the data around after each test
B.@WebMvcTest loads only the web layer, so services and repositories must be mocked
C.All three annotations start a real web server on a random port
D.@SpringBootTest loads only the web layer so it is the fastest of the three
Answer: B
@SpringBootTest loads the full context (slow, complete). @WebMvcTest loads only the web layer and mocks the rest. @DataJpaTest loads only the JPA layer, running each test in a transaction and rolling it back. Slice tests are much faster, so they should be the default; reserve @SpringBootTest for flows that need cross-layer checks.
In Spring Security, why store passwords with BCryptPasswordEncoder rather than hashing with SHA-256?
A.BCrypt is deliberately slow, has an adjustable cost factor, and salts automatically
B.BCrypt is two-way so you can recover the original password when a user forgets it
C.SHA-256 has been shown to have collisions so it can no longer be used
D.BCrypt produces a shorter hash so it saves database space
Answer: A
Because passwords need a SLOW hash. BCrypt has a cost parameter to tune its slowness and embeds a random salt into each hash, so two users with the same password still get different values and rainbow tables are useless. SHA-256 is fast, so a GPU can try billions of guesses per second.
Two beans implement the same interface. What error does injecting that interface cause, and how is it fixed?
A.No error; Spring picks whichever bean was declared first during scanning
B.An ambiguous-bean error; fix it with @Primary or @Qualifier
C.An error on the first request rather than at startup
D.No error; both beans are injected as a list
Answer: B
An ambiguous bean error at startup. Fix it by marking one bean as primary, or by using the annotation that names a specific bean at the injection point. The container doesn't guess — it refuses to start.
When must you use @Bean in a @Configuration class rather than @Component?
A.When the bean must be created before other beans
B.When the bean must be injected by constructor rather than by field
C.When the class you need a bean of belongs to a third-party library you cannot modify
D.When the bean needs singleton scope instead of prototype
Answer: C
When the bean being created comes from a third-party library whose source you can't modify — you can't add an annotation to someone else's class. Also use it when bean creation needs logic: reading configuration, calling a builder, or choosing settings conditionally.
A.A class that runs at application startup to initialize resources
B.A configuration file declaring the application's default beans
C.A build-tool plugin that packages the application
D.A dependency that bundles the set of libraries needed for one capability
Answer: D
A dependency that bundles the libraries needed for a feature, with versions already checked for compatibility. It usually contains no code itself — the value is that you declare one line instead of ten and don't have to figure out versions yourself.
A.One property accepts several name spellings: kebab-case, camelCase, uppercase with underscores
B.The property's data type is checked more loosely than usual
C.Properties can be changed at runtime without restarting
D.A property with no value gets a default instead of raising an error
Answer: A
A property accepts multiple name spellings: kebab-case, camelCase, or uppercase with underscores all point to the same property. This lets you set it via a YAML file as well as via environment variables, which have a very different naming convention.
A.The bean is loaded only when running automated tests
B.The bean is created only while that profile is active
C.The bean is preferred when several beans of the same type exist
D.The bean is created with configuration specific to that profile
Answer: B
The bean is only created when that profile is active. This is how you swap settings per environment — a real email service in production and a log-only implementation on your local machine.
The filter chain at the servlet layer runs first, then DispatcherServlet receives the request, looks up the mapping table to find the handler method, runs the interceptors, and only then reaches your method. The response travels back through those layers in reverse.
Should token authentication logic go in a Filter, an Interceptor, or AOP?
A.Directly in each controller for fine-grained control
B.An Interceptor — it knows which handler method is about to run
C.A Filter — it sees every request before it reaches the MVC layer
D.AOP — it is fully decoupled from the web layer so it is reusable
Answer: C
In a filter, because it sees every request before it enters the MVC layer. Placing it at a later layer means requests that don't match any handler — wrong paths, static resources — slip through unchecked.
With no handling, what status does an uncaught exception in a controller return?
A.400, because Spring infers that the input data was at fault
B.500, even when the real cause is bad data sent by the client
C.404, because no handler could be found for the request
D.503, to tell the client the service is temporarily unavailable
Answer: B
Status 500. Even when the cause is a bad request from the client. The problem is the client can't tell a client error from a server error, so it may retry a request that will never succeed.
C.The format of the error response body, per RFC 7807
D.A retry mechanism for requests that fail with transient errors
Answer: C
A standard shape for error responses, following the Problem Details spec (RFC 9455), with fields for type, title, status, detail, and instance. You can extend it with your own fields.
Three reasons: it exposes the table structure, exposes sensitive fields like passwords, and lazy-loaded relations fail when serialized outside the transaction scope. Adding a column to the table also changes the API contract.
Where should CORS be configured in Spring Boot when Spring Security is present?
A.On the client side, by declaring which origins may be called
B.Declare a CORS configuration source and enable it in the Security filter chain
C.Just an origin-allowing annotation on each controller
D.In the configuration file, via a built-in Spring Boot property
Answer: B
Declare a CORS configuration source and enable it in the Security filter chain. That chain runs before the MVC layer, so configuring it only at the MVC layer won't apply to the preflight request in time and the browser reports an error.
Spring 6 introduced RestClient. How does it differ from RestTemplate and WebClient?
A.A fluent API like WebClient but synchronous, with no reactive dependency
B.It is a rename of the older API with identical behaviour
C.It can only be used in reactive WebFlux applications
D.It replaces both, and the other two have been removed from the framework
Answer: A
It has a fluent API like a non-blocking one but runs synchronously and doesn't pull in reactive dependencies. It fills the gap between an old API no longer evolving and an asynchronous API that's overkill for ordinary HTTP calls.
How does @Valid on a controller parameter differ from @Validated on a service class?
A.MVC uses @Valid; @Validated adds groups and method validation.
B.The latter works only with custom constraint annotations
C.The former validates nested objects deeply while the latter does not
D.The former throws an exception while the latter only logs a warning
Answer: A
The first is handled by Spring MVC at the web layer and throws a dedicated exception the error handler can catch. The second triggers validation through a proxy, so it applies to any bean, not just controllers — but only when the method is called from outside.
What does writing a custom constraint annotation require?
A.A class extending the framework's base constraint class
B.Just an annotation carrying a regular expression describing the rule
C.A bean registered into a global validator list
D.An annotation @Constraint plus an accompanying ConstraintValidator class
Answer: D
Two parts: an annotation carrying the constraint meta-annotation and pointing to the validation class, plus a validation class implementing the standard interface with a method returning whether the value is valid.
A.The proxy checks the cache by key; on a hit it returns immediately, on a miss it calls the method and stores the result
B.The result is shared across every instance of the application
C.The method is re-run periodically in the background to refresh the cached value
D.The result is kept in JVM memory and lives until memory runs out
Answer: A
A proxy intercepts the call, derives the key from the arguments, and checks the cache. On a hit it returns without running the method; on a miss it runs and stores the result. Because it goes through a proxy, calling from within the same bean bypasses the cache entirely.
What happens with @Scheduled when the application runs 3 instances?
A.Spring rotates the runs among the instances automatically
B.Only the instance elected leader runs the job
C.The job runs only on the instance that started first
D.All 3 instances run the job, causing duplicates
Answer: D
All three run — each process has its own scheduler and knows nothing about the others. For tasks like sending email or computing payroll, that means three duplicate executions. You need a distributed lock or an external scheduler.
A.It defers creation until the bean is first used instead of at startup
B.The bean is created anew each time it is injected somewhere
C.The bean is created only when the corresponding profile is active
D.The bean is released from memory when nothing uses it any more
Answer: A
It defers initialization until the bean is first used instead of creating it at startup. In exchange, that bean's configuration errors don't surface at startup but appear when a real request comes in — so use it selectively.
An application needs to run code right after startup completes. What should it use?
A.A scheduled task set to run a few seconds after startup
B.A method marked to run after the bean is created
C.A static block in the class holding the main method
D.ApplicationRunner or CommandLineRunner
Answer: D
Either of the two interfaces that run after startup. They run once the container is fully ready, so every bean is available — unlike a bean's init method, which runs when only that bean is ready.
Modifying a managed entity inside a @Transactional method without calling save(). What happens?
A.The change is still written to the DB thanks to dirty checking
B.The application throws an exception because the entity was modified outside the repository
C.The change only takes effect after calling the find method again
D.The change is lost because it was never written into the persistence context
Answer: A
The change is still written to the database. The persistence context keeps a snapshot of the state when the entity was loaded, and when the transaction ends it compares them — any differing field generates the corresponding update statement.
How good a solution is switching every relation to FetchType.EAGER to avoid lazy loading errors?
A.Neutral — the performance is the same since the data has to be read eventually
B.Good — it eliminates a whole class of runtime errors
C.Bad — it causes N+1 and drags whole object graphs into every query
D.Good if you also enable JPA's second-level cache
Answer: C
Bad. It treats the symptom but makes every query pull in the whole data tree, and for one-to-many relations it creates N+1 problems. The right approach is to keep lazy loading and explicitly fetch the relations each query needs.
In a bidirectional @OneToMany / @ManyToOne relation, which side is the owning side?
A.The @OneToMany side — the one holding the list of children
B.The @ManyToOne side — the one holding the foreign key column
C.Both sides own it and both update the relation
D.Whichever side is declared first in the entity source code
Answer: B
The many-to-one side, because that is the side holding the foreign key column in the table. The one-to-many side is the inverse side, declared with a property pointing to the field name on the other side. Only changes on the owning side are written down.
What does adding a Pageable parameter to a repository method give?
A.The whole result is loaded and then sliced in memory
B.The result is cached per page
C.Spring adds LIMIT/OFFSET and the ordering to the query automatically
D.The repository returns a stream read incrementally from the database
Answer: C
Spring automatically adds limit, offset and order by clauses to the query. A page-typed return also runs an extra count query to know the total number of records and total pages.
How does @Query with JPQL differ from nativeQuery = true?
A.JPQL works only for reads, native works for writes too
B.JPQL is syntax-checked at runtime while native is checked at compile time
C.Native is faster because it bypasses JPA's mapping layer
D.JPQL is written against entity names and is DB-independent; native is raw SQL for one specific DB
Answer: D
JPQL is written with entity names and Java field names, independent of the DBMS, and is syntax-checked at startup. Pure SQL is written directly with table and column names, uses DBMS-specific features but locks the application to that system.
A.Marking the schema version for migration purposes
B.Storing a history of the record's versions for later review
C.Optimistic locking — concurrent overwrites are detected and an exception is thrown
D.Locking the row in the database when the entity is loaded
Answer: C
Optimistic locking. JPA adds a version condition to the update statement and increments that value; if no row was affected — meaning someone wrote first — it throws an exception instead of silently overwriting.
What benefit does @Transactional(readOnly = true) bring?
A.The transaction runs at the lowest isolation level to be faster
B.The database rejects every write statement inside that transaction
C.Query results are cached automatically
D.Hibernate skips dirty checking, and the driver may route to a read replica
Answer: D
Hibernate skips keeping the state snapshot for dirty checking, reducing memory and time when a query returns many entities. And with read-replica infrastructure, this attribute is a signal to route there.
By default, which exceptions cause @Transactional to roll back?
A.Only when you explicitly call the rollback-marking method
B.Only unchecked exceptions; a checked exception still commits
C.Only exceptions thrown by the database layer
D.Every exception, both checked and unchecked
Answer: B
Only unchecked exceptions. Checked exceptions still commit — so a method throwing a checked exception midway will still write its incomplete changes. To change this, declare the attribute specifying the exception types.
Why should spring.jpa.hibernate.ddl-auto=update not be used in production?
A.It works only with certain database engines
B.It infers schema changes automatically, uncontrolled and impossible to roll back
C.It requires a database account with the highest administrative privileges
D.It slows application startup significantly
Answer: B
It infers schema changes from entities automatically — nothing is reviewed beforehand, nothing can be rolled back, and renames or data migrations are not handled. Migration tools with versioned files are the correct approach.
A.It does not need the controller class under test to be specified
B.It loads only the web layer, so other beans must be mocked
C.It can only test endpoints that return JSON
D.It runs against a real server on a random port
Answer: B
It loads only the web layer — controllers, message converters, data validation config — while other beans must be mocked. The test starts much faster and focuses precisely on the layer under test.
How does @MockBean (now @MockitoBean) differ from Mockito's @Mock?
A.It creates a mock with default behaviour instead of returning null
B.It works only with beans that have an interface
C.It records every call automatically to compare against the previous run
D.It replaces the bean in the application context, not just creates a fake object
Answer: D
It replaces the bean in the container rather than merely creating a mock. Every other bean injecting that dependency then receives the fake — something a pure mocking library's annotation cannot do.
A.A distributed tracing tool following a request across several services
B.A metrics collection abstraction that can export to many monitoring systems
C.A structured logging library replacing traditional logging
D.A performance harness that benchmarks the application's methods
Answer: B
It is the abstraction layer for metrics collection — similar to the role of a logging facade. You write the instrumentation code once, and which monitoring system it exports to is decided by the dependency on the classpath.
What configuration does graceful shutdown need in Spring Boot?
A.Enable the graceful shutdown property and set a shutdown timeout
B.Switch to the reactive model because the servlet model does not support it
C.Register a custom hook to close resources when the signal arrives
D.Nothing; Spring Boot always waits for requests to finish before shutting down
Answer: A
Enable the corresponding property and set a timeout. On receiving the stop signal, the embedded server stops accepting new connections and waits for in-flight requests to finish within that timeout before shutting down.
Which actuator endpoints should not be exposed publicly?
A.None, because they are all read-only
B.All of them, including the health endpoint
C.Endpoints exposing configuration, environment variables, heap dumps, and beans
D.Only the endpoint that lets you shut the application down remotely
Answer: C
Endpoints exposing config, environment variables, heap dumps, bean listings, and route maps. They leak connection strings, secrets, and internal structure. By default Spring Boot only exposes health endpoints, and opening more is a deliberate decision.
What is the biggest breaking change when upgrading from Spring Boot 2 to 3?
A.Changing the configuration file format from YAML to a new format
B.The namespace change from javax.* to jakarta.*, plus a Java 17 requirement
C.Dropping the servlet model entirely in favour of WebFlux only
D.Dropping auto-configuration, so beans must be declared manually
Answer: B
The namespace change from the old prefix to the new one across the whole servlet, JPA, and data validation API, plus the Java 17+ requirement. Libraries that don't yet support the new namespace won't run.
How do you change a package's log level while the application is running?
A.Call the actuator loggers endpoint with a POST request
B.Send an operating-system signal to the Java process
C.Edit the configuration file and wait for the application to reload it
D.It cannot be changed at runtime; the application must be restarted
Answer: A
Call the actuator loggers management endpoint with a write request, including the desired log level. That lets you turn on verbose logging for a single package during an incident, then turn it back off — no restart and no impact on the rest.
What problem does spring.jpa.open-in-view being enabled cause?
A.It holds a database connection for the whole request lifecycle
B.It turns every lazy relation into an eager one on query
C.It causes errors when accessing a lazy relation outside a transaction
D.It forces every query to run in its own transaction
Answer: A
It holds the database connection for the entire request lifecycle, including while building the response or calling external services. The connection pool runs dry far sooner than expected, and the symptom is connection timeout errors under high load.
How do actuator liveness and readiness probes differ in purpose?
A.One returns detailed status and the other only a status code
B.One runs at startup and the other periodically while serving
C.One decides a restart and the other decides receiving traffic
D.One checks the application and the other its external dependencies
Answer: C
One probe decides whether to restart the application, the other decides whether to send traffic to it. An application that is starting up or has a temporary connection loss isn't ready to serve but is still healthy, so restarting it is the wrong response.
Returning per-field errors instead of one generic message — how?
A.Declare a custom message for each constraint annotation
B.Enable detailed error display in the application configuration
C.Check each field manually in the controller before processing
D.Catch the validation exception in the shared error handler
Answer: D
Catch the validation exception in a global error handler. That exception carries the list of per-field errors, so you just iterate over them and map them into the response structure the UI needs.
Tracing all logs of one request across layers — what approach?
A.Attach a trace id to the thread's diagnostic context
B.Pass the trace id as a parameter to every method
C.Log with timestamps and filter by time range
D.Turn the log level up to the most detailed for the whole application
Answer: A
Put a trace id into the thread's diagnostic context in an inbound filter. Every log line from that thread then carries the id, so filtering by id gives you the whole journey of one request.
Calling an external API with Spring HTTP client — what to configure first?
A.The JSON converter for reading the response
B.A logger recording the content of every outbound call
C.The maximum response size accepted
D.The connection timeout and the read timeout
Answer: D
Connect timeout and read timeout. Some clients default to waiting indefinitely, so a hanging external service holds application threads forever and exhausts the thread pool — the incident spreads to unrelated features.
An API returns timestamps as number arrays instead of date strings. Why?
A.The date type used is not one of the language's standard types
B.The date/time module or the corresponding configuration is missing
C.The server's timezone is misconfigured
D.That field lacks a format annotation
Answer: B
A missing date/time type module or the corresponding configuration. The JSON library treats them as plain objects by default and writes out each component. Spring Boot usually configures this out of the box, so this shows up when you build the converter yourself.
A bean holding its own thread pool must clean up at shutdown. What do you use?
A.Register a hook that runs when the virtual machine exits
B.An annotation marking a method to run before the bean is destroyed
C.Nothing is needed because threads end when the process stops
D.Clean up in the main method's finally block
Answer: B
Use the annotation marking a method to run before the bean is destroyed. Spring calls it during application shutdown, so the thread pool is stopped in an orderly way and in-flight work gets a chance to finish.