---
title: "Spring Boot: Java Application Framework Essentials"
description: "Test your knowledge of Spring Boot covering dependency injection, auto-configuration, REST controllers, Spring Data, and production-ready features."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/quizzes/post/spring-boot-fundamentals-quiz
---

# Spring Boot: Java Application Framework Essentials

Spring Boot removed most of the ceremony from Java backend development, but the framework still does a lot of work you cannot see. This quiz walks through dependency injection, auto-configuration, REST controllers, Spring Data JPA, configuration and profiles, security basics, Actuator, and testing. Answer each question and read the explanations to sharpen your mental model of what Spring is really doing under the hood.

## Questions

### 1. What core principle lets the Spring container create and wire your objects instead of you calling `new` yourself?

- **Inversion of Control, where the container owns object creation and wiring.** ✅
  - The container controls the lifecycle and dependencies, inverting who is in charge of construction.
- Reflection, because Spring reads annotations at runtime.
  - Reflection is a mechanism Spring uses, not the design principle behind dependency wiring.
- Aspect-oriented programming, because it intercepts method calls.
  - AOP handles cross-cutting concerns, not the ownership of object creation.
- Lazy initialization, because beans are created on demand.
  - Lazy init is an optional strategy, not the principle that defines the container model.

**Explanation:** Inversion of Control means the framework, not your code, decides when and how collaborators are created and injected.

**Hint:** The container is in charge, not your constructor calls.

### 2. Which injection style does the Spring team recommend for required dependencies?

- Field injection with `@Autowired` on the private field.
  - Field injection hides dependencies and makes the bean hard to test without the container.
- Setter injection so dependencies can change at runtime.
  - Setter injection suits optional dependencies, not mandatory ones that must exist to construct a valid object.
- **Constructor injection, which makes dependencies explicit and final.** ✅
  - Constructor injection guarantees required collaborators are present and enables immutable, easily tested beans.
- Static injection through a shared singleton holder.
  - Spring does not support static injection, and global holders defeat the container.

**Explanation:** Constructor injection produces fully initialized, immutable beans and is trivial to instantiate in unit tests.

**Hint:** Which style lets you mark the dependency `final`?

### 3. What is the default scope of a Spring bean?

- Prototype, so a new instance is created on every injection.
  - Prototype must be requested explicitly with `@Scope("prototype")`.
- **Singleton, one shared instance per application context.** ✅
  - By default the container creates a single shared instance and injects it everywhere.
- Request, one instance per HTTP request.
  - Request scope exists but only in web contexts and must be declared.
- Thread, one instance per thread.
  - Spring has no built-in thread scope by default.

**Explanation:** Singleton scope is the default; the same bean instance is shared across the whole context.

**Hint:** Think "one per context" unless you say otherwise.

### 4. When two beans of the same type exist, how do you tell Spring which one to inject?

- **Mark one with `@Qualifier` (or `@Primary`) to disambiguate.** ✅
  - `@Qualifier` names the exact bean, and `@Primary` marks a default when several candidates match.
- Rename the injection field to match one bean name automatically.
  - Field name matching is fragile and not the intended disambiguation mechanism.
- Delete one of the beans so only one candidate remains.
  - You often legitimately need both beans; removing one is not a general solution.
- Spring picks one at random and logs a warning.
  - Ambiguous injection throws `NoUniqueBeanDefinitionException` instead of guessing.

**Explanation:** Use `@Qualifier` to select a specific bean by name, or `@Primary` to declare the default candidate.

**Hint:** One annotation names the bean, another marks the default.

### 5. What three annotations does `@SpringBootApplication` combine?

- **`@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan`.** ✅
  - It is a convenience meta-annotation bundling configuration, auto-config, and component scanning.
- `@Controller`, `@Service`, and `@Repository`.
  - Those are stereotype annotations for individual beans, not the application entry point.
- `@RestController`, `@RequestMapping`, and `@Bean`.
  - These configure web endpoints and beans, not the bootstrap composition.
- `@EnableWebMvc`, `@EnableJpaRepositories`, and `@Import`.
  - These enable specific features but are not what the annotation bundles by default.

**Explanation:** `@SpringBootApplication` merges `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan` into one annotation.

**Hint:** It configures beans, enables auto-config, and scans for components.

### 6. How does Spring Boot auto-configuration decide whether to configure a feature?

- It runs everything and disables what fails at startup.
  - Auto-config is selective up front, not trial-and-error at runtime.
- **It uses conditional annotations like `@ConditionalOnClass` and `@ConditionalOnMissingBean`.** ✅
  - Conditions inspect the classpath and existing beans to apply configuration only when it makes sense.
- It reads a mandatory `autoconfig.xml` file you must provide.
  - No such XML file is required; auto-config is annotation and condition driven.
- It asks the developer interactively on first run.
  - Auto-configuration is fully automatic with no interactive prompt.

**Explanation:** Auto-configuration classes are gated by `@Conditional` checks on classpath contents, properties, and existing beans.

**Hint:** It reacts to what is on the classpath and which beans you have not defined.

### 7. What is the main purpose of a Spring Boot "starter" dependency?

- It generates boilerplate controller code for you.
  - Starters do not generate code; they bring in dependencies.
- **It is a curated set of dependencies for a capability, versioned together.** ✅
  - A starter such as `spring-boot-starter-web` bundles compatible libraries so you avoid manual version juggling.
- It replaces the need for a build tool like Maven or Gradle.
  - Starters are declared inside your build tool, not a replacement for it.
- It is a runtime agent that profiles your application.
  - Starters are build-time dependency descriptors, not runtime agents.

**Explanation:** Starters group the libraries needed for a feature into a single, version-aligned dependency.

**Hint:** Think one dependency that pulls in a coherent, compatible bundle.

### 8. How does `@RestController` differ from `@Controller`?

- **It adds `@ResponseBody` semantics so return values are serialized to the response body.** ✅
  - `@RestController` is `@Controller` plus `@ResponseBody`, so methods return data rather than view names.
- It only works with WebFlux, not Spring MVC.
  - `@RestController` works in both stacks; it is not WebFlux-only.
- It automatically secures every endpoint it declares.
  - Security is configured separately; the annotation has no auth behavior.
- It disables JSON serialization in favor of plain text.
  - It relies on message converters, which default to JSON for objects.

**Explanation:** `@RestController` combines `@Controller` and `@ResponseBody`, writing return values straight to the HTTP body.

**Hint:** One returns view names, the other returns serialized data.

### 9. Which annotation binds a JSON request body to a method parameter?

- `@PathVariable`, because it maps URI segments.
  - `@PathVariable` extracts values from the URL path, not the body.
- `@RequestParam`, because it reads query parameters.
  - `@RequestParam` binds query-string or form fields, not the JSON body.
- **`@RequestBody`, which deserializes the body into the parameter type.** ✅
  - `@RequestBody` uses a message converter to map the incoming JSON onto the parameter object.
- `@ModelAttribute`, because it always builds the object from the body.
  - `@ModelAttribute` binds request parameters into an object, not a raw JSON body.

**Explanation:** `@RequestBody` triggers HTTP message conversion, turning the request payload into a Java object.

**Hint:** You want the whole payload, not a path segment or query param.

### 10. Which annotation is the shortcut for handling HTTP GET requests on a path?

- **`@GetMapping`, a specialization of `@RequestMapping` for GET.** ✅
  - `@GetMapping` is a composed annotation equal to `@RequestMapping(method = GET)`.
- `@RequestMapping(method = POST)` with a GET flag.
  - That maps POST; there is no GET flag on it.
- `@HttpGet`, the standard Servlet annotation.
  - No such Spring annotation exists.
- `@Query`, which maps read-only endpoints.
  - `@Query` is a Spring Data annotation for repository queries, not HTTP routing.

**Explanation:** `@GetMapping`, along with `@PostMapping`, `@PutMapping`, and `@DeleteMapping`, are HTTP-method shortcuts for `@RequestMapping`.

**Hint:** It has a matching sibling for POST, PUT, and DELETE.

### 11. What does `ResponseEntity` let a controller method control that a plain return type cannot?

- The database transaction boundary for the request.
  - Transactions are managed by the service layer and `@Transactional`, not `ResponseEntity`.
- **The HTTP status code, headers, and body together.** ✅
  - `ResponseEntity` wraps the body plus explicit status and headers for full response control.
- The bean scope of the controller.
  - Bean scope is unrelated to the response wrapper.
- The order in which filters run.
  - Filter ordering is configured separately, not through the return value.

**Explanation:** `ResponseEntity<T>` gives explicit control of status code, headers, and body in one return value.

**Hint:** Think status plus headers plus body in a single object.

### 12. What do you get by extending `JpaRepository<User, Long>`?

- **A generated proxy providing CRUD and pagination methods without an implementation.** ✅
  - Spring Data creates a runtime proxy implementing `save`, `findById`, `findAll`, paging, and more.
- An abstract class you must subclass and implement manually.
  - You write an interface; Spring supplies the implementation at runtime.
- A raw JDBC connection you manage yourself.
  - JPA repositories abstract away JDBC connection handling.
- A REST endpoint automatically for every entity.
  - That behavior comes from Spring Data REST, a separate module.

**Explanation:** Extending a Spring Data repository interface yields a generated proxy with CRUD, sorting, and paging support.

**Hint:** You declare an interface and never write the implementation.

### 13. How does Spring Data derive a query from a method named `findByEmailAndActiveTrue`?

- **It parses the method name into a query at startup using property and keyword conventions.** ✅
  - Spring Data reads keywords like `findBy`, `And`, and `True` plus property names to build the query.
- It requires a matching stored procedure in the database.
  - No stored procedure is needed for derived queries.
- It executes the method name as literal SQL text.
  - The method name is parsed, not run as SQL verbatim.
- It always needs an explicit `@Query` annotation to work.
  - Derived queries work without `@Query`; that annotation is for custom queries.

**Explanation:** Query derivation parses the method name against entity properties and keywords to generate the query.

**Hint:** The method name itself is the specification.

### 14. What problem does the N+1 select issue describe in JPA?

- A query returns one extra row beyond what was requested.
  - N+1 is about query count, not an off-by-one in rows.
- **One query for the parents plus one additional query per parent to load a relation.** ✅
  - Lazy associations trigger a separate query for each parent, producing N+1 total round trips.
- A deadlock between N transactions competing for one row.
  - That describes lock contention, not the N+1 pattern.
- A cache miss that forces N retries of the same query.
  - N+1 is about redundant distinct queries, not retries of one query.

**Explanation:** N+1 happens when loading a collection lazily issues one query per parent; a fetch join or entity graph fixes it.

**Hint:** Count the queries: one for the list, then one per item.

### 15. Where should `@Transactional` typically be applied in a layered Spring Boot app?

- **On the service-layer method that groups the related repository calls.** ✅
  - The service layer defines the business unit of work, the natural transaction boundary.
- On every repository method individually.
  - That splits a business operation across many transactions, breaking atomicity.
- On the controller method handling the request.
  - Controllers coordinate HTTP concerns; transactions belong to business logic.
- On the main application class.
  - The bootstrap class is not where a unit of work is defined.

**Explanation:** Place `@Transactional` on service methods so a whole business operation commits or rolls back together.

**Hint:** Think business unit of work, not a single query.

### 16. What does a Spring profile let you do?

- **Activate different beans and property values per environment.** ✅
  - Profiles like `dev`, `test`, and `prod` swap configuration and beans depending on the active profile.
- Profile CPU usage of your beans at runtime.
  - Spring profiles are about environment configuration, not performance profiling.
- Encrypt the application properties file.
  - Encryption is a separate concern; profiles just select configuration sets.
- Restrict which users can call an endpoint.
  - That is authorization, handled by Spring Security, not profiles.

**Explanation:** Profiles group beans and property files so a single build behaves differently per environment.

**Hint:** Think dev vs test vs prod for the same jar.

### 17. Which annotation injects a single property value into a field?

- **`@Value("${app.timeout}")` on the field or constructor parameter.** ✅
  - `@Value` resolves a property placeholder and injects the resulting value.
- `@ConfigurationProperties` on the field.
  - `@ConfigurationProperties` binds a group of properties to a class, not a single field.
- `@Autowired` with the property name.
  - `@Autowired` wires beans by type, not scalar property values.
- `@Bean` on a getter returning the value.
  - `@Bean` declares a bean; it is not the idiomatic way to inject a scalar property.

**Explanation:** `@Value` with a `${...}` placeholder injects one resolved property; use `@ConfigurationProperties` for grouped, type-safe binding.

**Hint:** It uses a `${...}` placeholder for one value.

### 18. What advantage does `@ConfigurationProperties` offer over scattered `@Value` fields?

- **Type-safe binding of a whole group of related properties into one object.** ✅
  - It maps a namespaced set of properties onto a POJO with validation and relaxed binding.
- It disables externalized configuration entirely.
  - It embraces externalized config; it does not disable it.
- It forces all properties to be constants at compile time.
  - Values are still resolved from external sources at runtime.
- It removes the need for any properties file.
  - It still reads from properties or YAML sources.

**Explanation:** `@ConfigurationProperties` binds a prefixed group of settings into a strongly typed, validatable object.

**Hint:** Think one class holding a whole related group of settings.

### 19. What triggers bean validation on an incoming request body in a controller?

- **Adding `@Valid` (or `@Validated`) before the `@RequestBody` parameter.** ✅
  - `@Valid` tells Spring to run the constraint annotations on the bound object before the method runs.
- Annotating the controller class with `@Validated` only.
  - Class-level `@Validated` supports method params, but body validation is triggered per parameter with `@Valid`.
- Nothing; Spring validates every request body automatically.
  - Validation is opt-in and requires the annotation on the parameter.
- Declaring the DTO fields as `final`.
  - Immutability does not trigger validation.

**Explanation:** Mark the `@RequestBody` parameter with `@Valid` so its Jakarta Validation constraints are checked before the handler executes.

**Hint:** One annotation right before the request-body parameter.

### 20. What is the role of `@ControllerAdvice` (or `@RestControllerAdvice`)?

- **To centralize exception handling and response shaping across many controllers.** ✅
  - It defines global `@ExceptionHandler`, `@InitBinder`, and model methods shared by controllers.
- To advise the container on bean creation order.
  - It has nothing to do with bean instantiation order.
- To cache controller responses automatically.
  - Caching is a separate concern handled by `@Cacheable` and friends.
- To generate OpenAPI documentation for controllers.
  - API docs come from tools like springdoc, not this annotation.

**Explanation:** `@ControllerAdvice` groups cross-cutting handler logic, most commonly global `@ExceptionHandler` methods, in one place.

**Hint:** Think one class that handles exceptions for all controllers.

### 21. In Spring Security, what is the difference between authentication and authorization?

- **Authentication verifies identity; authorization decides what that identity may access.** ✅
  - First you prove who you are, then the system checks whether you are allowed to perform an action.
- Authentication checks permissions; authorization logs the user in.
  - That reverses the two concepts.
- They are two names for the same login step.
  - They are distinct phases with different responsibilities.
- Authentication encrypts traffic; authorization compresses it.
  - Neither term relates to transport encryption or compression.

**Explanation:** Authentication answers "who are you?" and authorization answers "what are you allowed to do?".

**Hint:** Identity first, then permissions.

### 22. How is HTTP security most commonly configured in modern Spring Boot?

- **By declaring a `SecurityFilterChain` bean that customizes the `HttpSecurity`.** ✅
  - Recent versions favor a `SecurityFilterChain` bean over extending `WebSecurityConfigurerAdapter`.
- By editing an XML `security-config.xml` file.
  - XML config is legacy; Java configuration is idiomatic today.
- By annotating the main class with `@Secure`.
  - No such annotation drives the security filter chain.
- By setting a single property `security.enabled=true`.
  - Real rules require a configured filter chain, not one flag.

**Explanation:** Modern Spring Security is configured with a `SecurityFilterChain` bean using the lambda `HttpSecurity` DSL.

**Hint:** It is a bean, not the old adapter subclass.

### 23. What does Spring Boot Actuator provide?

- **Production-ready endpoints for health, metrics, and application info.** ✅
  - Actuator exposes operational endpoints such as `/actuator/health` and `/actuator/metrics`.
- A code generator that scaffolds controllers.
  - Actuator is about observability, not scaffolding.
- A replacement for your logging framework.
  - It integrates with logging but does not replace it.
- An embedded database for testing.
  - Test databases like H2 are separate dependencies.

**Explanation:** Actuator adds ready-made monitoring and management endpoints for running applications.

**Hint:** Think health checks and metrics out of the box.

### 24. Which Actuator endpoint is typically wired to a load balancer or orchestrator readiness probe?

- **`/actuator/health`, which reports application and dependency status.** ✅
  - Health indicators aggregate into a status that probes can poll to route or restart traffic.
- `/actuator/beans`, which lists every bean.
  - The beans endpoint is a debugging aid, not a probe target.
- `/actuator/env`, which dumps configuration properties.
  - The env endpoint exposes config, not liveness or readiness.
- `/actuator/mappings`, which lists request mappings.
  - Mappings is informational and unrelated to probes.

**Explanation:** The health endpoint, with its liveness and readiness groups, is the standard target for orchestration probes.

**Hint:** Which endpoint says "am I up and ready?"

### 25. What does `@SpringBootTest` do that a plain unit test does not?

- **It loads a full application context so beans are wired as in production.** ✅
  - It bootstraps the context, enabling integration-style tests with real bean wiring.
- It mocks every bean automatically so nothing real runs.
  - It loads real beans; mocking is opt-in with `@MockBean`.
- It disables the database for all tests.
  - It does not disable the database by default.
- It only compiles the test without executing it.
  - The test still runs; it just starts a context first.

**Explanation:** `@SpringBootTest` starts the Spring context so components collaborate as they would at runtime.

**Hint:** It boots the whole context, not a single class in isolation.

### 26. When would you use a slice test like `@WebMvcTest` instead of `@SpringBootTest`?

- **To load only the web layer for a controller, keeping the test fast and focused.** ✅
  - `@WebMvcTest` loads MVC components and lets you mock the service layer, avoiding a full context.
- To run the test against the real production database.
  - Slice tests deliberately narrow scope rather than exercising the full stack.
- To disable dependency injection completely.
  - DI still works; only a subset of beans is loaded.
- To test only static utility methods.
  - Static utilities need no Spring slice at all.

**Explanation:** `@WebMvcTest` boots just the web slice with `MockMvc`, so controller tests stay fast and isolated from lower layers.

**Hint:** Load only the layer under test, not the whole app.

### 27. What does `@MockBean` do inside a Spring Boot test?

- **It replaces a bean in the context with a Mockito mock.** ✅
  - The mock is injected wherever the real bean would be, letting you stub its behavior.
- It permanently deletes the bean from the application.
  - It only substitutes the bean within the test context.
- It generates a new real implementation of the bean.
  - It supplies a mock, not a real implementation.
- It marks the bean as lazy in production.
  - It affects only tests, not production bean scoping.

**Explanation:** `@MockBean` adds or replaces a bean in the test context with a Mockito mock you can program and verify.

**Hint:** Think Mockito mock, swapped into the context.
