Mock Full 05 — Spring Professional (60 Questions)
Exam style: Spring Professional Develop (2V0-72.22) — full 60-question mixed-topic mock.
Time limit: ~130 minutes (about 2 minutes per question).
Instructions:
- Pick an option for each question, then use Check answer to reveal the explanation and score.
- Use Back and Next to move through the set; you can change your selection until you check.
- For every miss, read the explanation and add one memory sentence before moving on.
Topic coverage:
- Q1–10: Spring Core & DI
- Q11–18: Configuration, Profiles & Scopes
- Q19–28: Spring Boot, Auto-Configuration & Actuator
- Q29–36: Spring MVC, REST & Validation
- Q37–44: Data Access, JPA & Transactions
- Q45–50: Spring Security
- Q51–56: Testing
- Q57–60: AOP, Events, Async & Observability
Question 1
A team registers a utility class with new inside a controller instead of injecting it from Spring.
Why is the manually created utility not participating in dependency injection?
- A) Only @Repository classes can receive injected collaborators
- B) Objects created with new are not managed by the IoC container unless explicitly registered as beans
- C) The controller scope prevents any helper object from being wired
- D) Spring only injects dependencies into static methods
Answer & explanation
Correct answer: B
Spring dependency injection applies to objects the container creates and manages. Calling new bypasses bean registration, so no injection, lifecycle callbacks, or proxying occur for that instance.
Why the other options are wrong:
- A) Any stereotype or @Bean can be injected, not only repositories.
- C) Controller scope does not block injection into properly registered beans.
- D) Spring does not inject static methods in normal usage.
Memory sentence: "new() creates non-beans; only container-managed objects get DI."
Study: Book chapter
Question 2
What is the relationship between Inversion of Control (IoC) and Dependency Injection (DI)?
- A) DI replaces IoC entirely in modern Spring
- B) IoC is the principle; DI is a common technique for implementing IoC
- C) IoC applies only to web applications; DI applies only to batch jobs
- D) They are unrelated concepts that happen to share annotations
Answer & explanation
Correct answer: B
IoC means control of object creation and wiring is inverted to a container. DI is one way to achieve IoC by supplying dependencies from outside the class rather than the class constructing them.
Why the other options are wrong:
- A) DI does not replace IoC; it implements the IoC idea.
- C) Both concepts apply across application types.
- D) They are directly related foundational Spring concepts.
Memory sentence: "IoC is the idea; DI is how Spring usually delivers it."
Study: Book chapter
Question 3
How many PaymentGateway collaborators will Spring inject into this single public constructor?
@Component
public class OrderRouter {
@Autowired
public OrderRouter(PaymentGateway gateway) { }
}
- A) Zero, because @Autowired is required on every constructor parameter
- B) One matching PaymentGateway bean from the container
- C) All PaymentGateway beans as a List automatically
- D) A new PaymentGateway instance per HTTP request regardless of scope
Answer & explanation
Correct answer: B
With a single constructor, Spring 4.3+ treats it as an autowiring constructor even without @Autowired. One compatible PaymentGateway bean is injected unless multiple candidates require @Qualifier.
Why the other options are wrong:
- A) @Autowired is optional on a single constructor.
- C) Multiple beans require explicit collection injection or qualifier handling.
- D) Request scope is not implied by constructor injection.
Memory sentence: "Single constructor = autowired by default in Spring."
Study: Book chapter
Question 4
Which stereotype annotation is most appropriate for a class that translates persistence exceptions into Spring DataAccessException hierarchy?
- A) @Service
- B) @Repository
- C) @Controller
- D) @Configuration
Answer & explanation
Correct answer: B
@Repository marks the persistence layer and enables PersistenceExceptionTranslationPostProcessor to convert vendor exceptions into Spring data-access exceptions.
Why the other options are wrong:
- A) @Service is for business logic, not persistence exception translation semantics.
- C) @Controller handles web request dispatching.
- D) @Configuration defines bean factories, not DAO/repository roles.
Memory sentence: "@Repository = persistence layer plus exception translation support."
Study: Book chapter
Question 5
What does @RestController add compared to @Controller alone?
@RestController
public class InvoiceController { }
// vs
@Controller
public class InvoicePageController { }
- A) @ResponseBody semantics on handler methods so return values are written directly to the HTTP body
- B) Automatic transaction management on every handler
- C) Mandatory CSRF token validation on all endpoints
- D) Prototype scope for the controller bean
Answer & explanation
Correct answer: A
@RestController is a composed annotation equal to @Controller plus @ResponseBody, which serializes return values through HttpMessageConverters instead of view resolution.
Why the other options are wrong:
- B) Transactions are not enabled by @RestController.
- C) CSRF is a security concern, not part of @RestController.
- D) Controllers remain singleton-scoped by default.
Memory sentence: "@RestController = @Controller + @ResponseBody."
Study: Book chapter
Question 6
A bean is declared with scope singleton (default). What does singleton mean in Spring?
- A) One instance per HTTP session
- B) One instance per JVM globally across all applications
- C) One shared instance per Spring IoC container
- D) One instance per thread
Answer & explanation
Correct answer: C
Spring singleton scope means one bean instance per container, not per class loader globally or per thread. This is the default for most beans.
Why the other options are wrong:
- A) Session scope creates one instance per HTTP session.
- B) Multiple Spring contexts in one JVM each have their own singleton instance.
- D) Thread scope is separate and uncommon as default.
Memory sentence: "Spring singleton = one instance per container."
Study: Book chapter
Question 7
Startup fails with NoUniqueBeanDefinitionException for DataExporter when two implementations exist.
Which annotation marks one bean as the default when autowiring by type?
- A) @Order
- B) @Primary
- C) @DependsOn
- D) @Lazy
Answer & explanation
Correct answer: B
@Primary selects a preferred bean when multiple candidates match a single injection point by type. Other consumers can still use @Qualifier for a non-primary bean.
Why the other options are wrong:
- A) @Order affects ordering of lists or advice, not autowire preference by default.
- C) @DependsOn controls initialization order.
- D) @Lazy delays creation but does not resolve ambiguity.
Memory sentence: "Type ambiguity default → @Primary on the preferred bean."
Study: Book chapter
Question 8
What does @ComponentScan on a @Configuration class cause during context refresh?
@Configuration
@ComponentScan(basePackages = "com.example.billing")
public class BillingConfig { }
- A) Only @Bean methods in BillingConfig are processed
- B) Classpath scanning registers stereotype-annotated classes under com.example.billing as bean definitions
- C) All classes on the JVM classpath become beans automatically
- D) Component scanning runs only in production profile
Answer & explanation
Correct answer: B
@ComponentScan tells the container to scan the specified packages for @Component, @Service, @Repository, @Controller, and other stereotype annotations, registering them as beans.
Why the other options are wrong:
- A) @Bean methods are processed separately from scanning.
- C) Only annotated classes in scanned packages are registered.
- D) Scanning is not profile-limited unless configured that way.
Memory sentence: "@ComponentScan registers annotated classes in the given packages."
Study: Book chapter
Question 9
BeanFactory versus ApplicationContext: which capability is typically associated with ApplicationContext but not the minimal BeanFactory contract?
- A) Retrieving beans by name
- B) Publishing ApplicationEvents to listeners
- C) Checking bean singleton versus prototype scope
- D) Obtaining bean references by type
Answer & explanation
Correct answer: B
ApplicationContext extends BeanFactory and adds event propagation, MessageSource, resource loading helpers, and automatic registration of BeanPostProcessors during refresh.
Why the other options are wrong:
- A) Bean retrieval exists on BeanFactory.
- C) Scope inspection is available on BeanFactory.
- D) Type-based lookup is a BeanFactory capability.
Memory sentence: "ApplicationContext adds events, i18n, and richer container integration."
Study: Book chapter
Question 10
Why is field injection like this discouraged in Spring applications?
@Service
public class PricingService {
@Autowired
private DiscountPolicy discountPolicy;
}
- A) It prevents the class from being proxied
- B) It hides required dependencies, complicates testing, and cannot enforce immutability easily
- C) It only works with XML configuration
- D) It disables component scanning for the class
Answer & explanation
Correct answer: B
Field injection makes dependencies less visible, harder to unit test without reflection or Spring, and incompatible with final immutable fields. Constructor injection is preferred for required collaborators.
Why the other options are wrong:
- A) Proxies can still wrap field-injected beans.
- C) Field injection works with annotation config.
- D) Component scanning is unaffected.
Memory sentence: "Prefer constructor injection; field injection hides dependencies."
Study: Book chapter
Question 11
What does the @Bean method produce in the Spring container?
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
- A) A static utility class registered by name only
- B) A bean instance whose lifecycle is managed by the container
- C) A prototype controller mapped to /restTemplate
- D) A property placeholder resolved from application.yml
Answer & explanation
Correct answer: B
@Bean methods are factory methods processed by configuration class enhancement. The returned object is registered as a bean with container-managed lifecycle and injection support.
Why the other options are wrong:
- A) The return value is a managed bean, not merely a name alias.
- C) @Bean does not create web endpoints.
- D) Property placeholders use @Value or @ConfigurationProperties.
Memory sentence: "@Bean method return value becomes a Spring-managed bean."
Study: Book chapter
Question 12
A @Configuration class defines two @Bean methods where one calls the other. Why might both calls return the same instance?
- A) @Configuration classes are enhanced so @Bean methods are proxied to respect singleton semantics within the class
- B) The JVM caches all method return values globally
- C) Spring always uses prototype scope for @Bean methods
- D) @Bean methods cannot call each other
Answer & explanation
Correct answer: A
Full @Configuration mode proxies @Bean methods so intra-class calls go through the container, ensuring singleton beans are not accidentally created twice.
Why the other options are wrong:
- B) JVM does not globally cache arbitrary method returns.
- C) Default @Bean scope is singleton unless specified otherwise.
- D) @Bean methods can call each other; proxying is the key behavior.
Memory sentence: "@Configuration proxies @Bean methods to avoid duplicate singletons."
Study: Book chapter
Question 13
How does Spring decide which PaymentClient bean is active?
@Bean
@Profile("staging")
public PaymentClient stagingClient() { return new StagingClient(); }
@Bean
@Profile("production")
public PaymentClient productionClient() { return new ProductionClient(); }
- A) Both beans always load and @Primary picks one
- B) Only the bean whose @Profile matches active profiles is registered
- C) Profiles are ignored for @Bean methods
- D) The last declared @Bean always wins
Answer & explanation
Correct answer: B
@Profile conditionally registers bean definitions. Only profiles matching spring.profiles.active (or equivalent) result in the bean being available in the context.
Why the other options are wrong:
- A) Non-matching profile beans are not registered, avoiding ambiguity in typical setups.
- C) Profiles apply fully to @Bean definitions.
- D) Declaration order does not override profile conditions.
Memory sentence: "@Profile registers beans only when that profile is active."
Study: Book chapter
Question 14
What is the main purpose of @ConfigurationProperties on a type-safe properties class?
- A) To generate SQL from property keys
- B) To bind external configuration under a prefix to Java object fields
- C) To replace @ComponentScan
- D) To enable method security on configuration classes
Answer & explanation
Correct answer: B
@ConfigurationProperties binds environment properties with a given prefix to fields or constructor parameters on a class, giving validated type-safe configuration access.
Why the other options are wrong:
- A) It does not generate SQL.
- C) Component scanning is unrelated.
- D) Security annotations are separate.
Memory sentence: "@ConfigurationProperties = bind prefix properties onto a class."
Study: Book chapter
Question 15
What does the :30 syntax mean in this @Value expression?
@Value("${app.timeout:30}")
private int timeout;
- A) A required property that must exist or startup fails
- B) A default value of 30 used when app.timeout is not set
- C) A profile name activated automatically
- D) A SpEL arithmetic operation
Answer & explanation
Correct answer: B
The colon in ${property:default} supplies a default when the property is missing. This is property placeholder resolution, not profile activation.
Why the other options are wrong:
- A) Required properties without defaults cause failure when missing.
- C) Profiles use @Profile or spring.profiles.active.
- D) This is not SpEL unless wrapped in #{...}.
Memory sentence: "${key:default} = property with fallback default value."
Study: Book chapter
Question 16
A singleton-scoped service injects a prototype-scoped Formatter bean directly. What happens?
- A) A new Formatter is created on every method call automatically
- B) The singleton holds one Formatter instance for its lifetime unless scoped proxy or ObjectProvider is used
- C) Prototype scope is upgraded to singleton silently
- D) Injection fails at startup always
Answer & explanation
Correct answer: B
Prototype beans injected into singletons are resolved once at singleton creation. For per-use instances, use @Lookup, ObjectProvider, or scoped proxies.
Why the other options are wrong:
- A) Direct injection does not recreate prototype on each method call.
- C) Scopes are not silently upgraded.
- D) Injection succeeds but behavior may be wrong for per-operation prototypes.
Memory sentence: "Prototype inside singleton = one instance unless you use ObjectProvider or proxy."
Study: Book chapter
Question 17
Why is proxyMode = TARGET_CLASS used on this request-scoped bean?
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public UserContext userContext() { return new UserContext(); }
- A) To allow a singleton collaborator to inject a proxy that delegates to the current request instance
- B) To make the bean singleton
- C) To disable dependency injection
- D) To run the bean on a background thread
Answer & explanation
Correct answer: A
Scoped proxies let shorter-lived beans (request/session) be injected into longer-lived singletons. The proxy resolves the correct instance per request.
Why the other options are wrong:
- B) Scope remains request; proxy does not change scope to singleton.
- C) Injection still works through the proxy.
- D) Proxy mode is unrelated to async threading.
Memory sentence: "Scoped proxy lets singletons safely use request/session beans."
Study: Book chapter
Question 18
Which callback interface lets a bean run custom logic after all properties are set?
- A) BeanFactoryPostProcessor
- B) InitializingBean or @PostConstruct methods
- C) BeanDefinitionRegistryPostProcessor only
- D) ApplicationListener unconditionally for every bean
Answer & explanation
Correct answer: B
InitializingBean.afterPropertiesSet, custom init methods, and @PostConstruct run after dependency injection completes and before the bean is used.
Why the other options are wrong:
- A) BeanFactoryPostProcessor modifies bean definitions before instantiation.
- C) Registry post-processors operate at definition registration time.
- D) ApplicationListener is for event handling, not generic init of every bean.
Memory sentence: "After properties set → @PostConstruct or InitializingBean."
Study: Book chapter
Question 19
What three annotations does @SpringBootApplication compose?
- A) @Configuration, @EnableAutoConfiguration, and @ComponentScan
- B) @SpringBootConfiguration, @EnableWebMvc, and @EntityScan only
- C) @Controller, @Service, and @Repository
- D) @Import, @PropertySource, and @Profile
Answer & explanation
Correct answer: A
@SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan (with optional attributes). It is the entry point for Boot auto-config and component discovery.
Why the other options are wrong:
- B) @EnableWebMvc opts out of Boot MVC auto-config; not part of the default triad.
- C) Those are stereotypes, not the @SpringBootApplication meta-annotations.
- D) Those annotations are unrelated to @SpringBootApplication composition.
Memory sentence: "@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan."
Study: Book chapter
Question 20
What is the primary role of a Spring Boot starter such as spring-boot-starter-web?
- A) It directly defines every bean in the application
- B) It brings a curated set of transitive dependencies for a feature area
- C) It replaces application.properties
- D) It disables component scanning
Answer & explanation
Correct answer: B
Starters are dependency descriptors that pull compatible libraries onto the classpath. Auto-configuration then creates beans when conditions match.
Why the other options are wrong:
- A) Beans come from user code and auto-configuration, not the starter POM itself.
- C) Properties remain separate configuration.
- D) Scanning is controlled by @SpringBootApplication.
Memory sentence: "Starter = dependency bundle; auto-config = conditional beans."
Study: Book chapter
Question 21
A custom DataSource @Bean already exists. How does @ConditionalOnMissingBean affect auto-configured DataSource creation?
- A) Boot creates a second DataSource anyway
- B) Auto-configuration backs off and does not register its default DataSource bean
- C) It deletes the user bean
- D) It ignores user beans defined outside @SpringBootApplication package
Answer & explanation
Correct answer: B
@ConditionalOnMissingBean prevents auto-config from registering a bean when the user already defined one of that type, avoiding duplicate primary beans.
Why the other options are wrong:
- A) Back-off avoids duplicate beans.
- C) User beans are preserved.
- D) Package location does not exempt beans from condition evaluation.
Memory sentence: "OnMissingBean = auto-config steps aside when user bean exists."
Study: Book chapter
Question 22
How can a developer inspect which auto-configuration classes matched or did not match at startup?
debug=true
# or
logging.level.org.springframework.boot.autoconfigure=DEBUG
- A) Only by decompiling Spring Boot JARs
- B) Enable debug logging or use the /actuator/conditions endpoint when exposed
- C) Auto-configuration decisions are not observable
- D) Add @EnableWebMvc to print the report
Answer & explanation
Correct answer: B
Boot can print a conditions evaluation report when debug is enabled. Actuator exposes /actuator/conditions for the same insight in running apps.
Why the other options are wrong:
- A) Built-in reporting exists without decompilation.
- C) Conditions are explicitly logged or exposed via Actuator.
- D) @EnableWebMvc changes MVC config, not condition reporting.
Memory sentence: "Debug auto-config with debug=true or actuator /conditions."
Study: Book chapter
Question 23
spring-boot-starter-data-jpa is on the classpath but no database driver dependency is declared. What is the typical outcome?
- A) Hibernate auto-connects to an embedded default production database
- B) Application fails at startup because no DataSource can be created without a supported driver
- C) JPA works without any database
- D) Only @WebMvcTest contexts are affected
Answer & explanation
Correct answer: B
The JPA starter provides JPA/Hibernate support but not vendor drivers. Without a driver (or explicit DataSource config), DataSource auto-configuration cannot succeed.
Why the other options are wrong:
- A) No implicit production database is provided.
- C) JPA requires a DataSource in typical setups.
- D) This affects the main application context, not only web slice tests.
Memory sentence: "JPA starter needs a database driver dependency."
Study: Book chapter
Question 24
Which property commonly controls which Actuator endpoints are exposed over HTTP?
- A) management.endpoints.web.exposure.include
- B) server.servlet.context-path.only
- C) spring.jpa.show-sql
- D) logging.pattern.console
Answer & explanation
Correct answer: A
management.endpoints.web.exposure.include (and exclude) determines which actuator endpoints are available on the web port, such as health, info, metrics.
Why the other options are wrong:
- B) Context path affects URL prefix, not endpoint exposure selection.
- C) show-sql is JPA logging, not Actuator.
- D) Logging pattern is unrelated to endpoint exposure.
Memory sentence: "Expose actuator endpoints via management.endpoints.web.exposure.include."
Study: Book chapter
Question 25
What does this setting control?
management.endpoint.health.show-details=when_authorized
- A) Whether health details appear always publicly
- B) Health detail visibility only for authorized Actuator requests when configured
- C) SQL logging for health checks
- D) Disables the health endpoint entirely
Answer & explanation
Correct answer: B
show-details governs how much health information is returned. when_authorized hides sensitive details from anonymous callers while allowing authorized users more detail.
Why the other options are wrong:
- A) always would expose details publicly; this setting is more restrictive.
- C) SQL logging is separate.
- D) The endpoint remains available; visibility of details changes.
Memory sentence: "health show-details controls how much health info callers see."
Study: Book chapter
Question 26
CommandLineRunner beans run at which point in the Boot startup sequence?
- A) Before the ApplicationContext is created
- B) After the context is refreshed and the application has started
- C) Only on HTTP request arrival
- D) Only when actuator /health is called
Answer & explanation
Correct answer: B
CommandLineRunner and ApplicationRunner execute after context refresh during application startup, useful for seeding data or validating configuration.
Why the other options are wrong:
- A) Context must exist first.
- C) They are startup hooks, not request handlers.
- D) Actuator health checks do not trigger runners.
Memory sentence: "CommandLineRunner runs after context refresh at startup."
Study: Book chapter
Question 27
spring.main.lazy-initialization=true changes bean creation how?
- A) All beans are never created
- B) Singleton beans are created when first needed rather than eagerly at refresh
- C) Only prototype beans become lazy
- D) It disables auto-configuration
Answer & explanation
Correct answer: B
Lazy initialization defers singleton bean creation until first dependency on them, speeding startup but delaying failure detection.
Why the other options are wrong:
- A) Beans are still created on demand.
- C) The setting primarily affects singleton eager init behavior.
- D) Auto-configuration still runs.
Memory sentence: "lazy-initialization = create singleton beans on first use."
Study: Book chapter
Question 28
In Spring Boot 3, where are auto-configuration classes listed for imports?
- A) META-INF/spring.factories only
- B) META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
- C) WEB-INF/web.xml
- D) application.yml spring.auto.import section
Answer & explanation
Correct answer: B
Boot 3 moved auto-configuration registration to AutoConfiguration.imports under META-INF/spring/, replacing the older spring.factories mechanism for auto-config.
Why the other options are wrong:
- A) spring.factories is the Boot 2 style for auto-config.
- C) web.xml is not used for Boot auto-config registration.
- D) No such standard application.yml section registers auto-config classes.
Memory sentence: "Boot 3 auto-config imports file under META-INF/spring/."
Study: Book chapter
Question 29
What is the role of DispatcherServlet in Spring MVC?
- A) It compiles JSP files only
- B) Front controller that dispatches requests to handlers and coordinates view resolution or message conversion
- C) It replaces the IoC container
- D) It manages database transactions directly
Answer & explanation
Correct answer: B
DispatcherServlet is the front controller: it maps requests via HandlerMapping, invokes controllers, and resolves views or writes bodies through HttpMessageConverters.
Why the other options are wrong:
- A) JSP compilation is container-specific, not DispatcherServlet core role.
- C) ApplicationContext remains separate.
- D) Transactions are handled by transaction infrastructure, not DispatcherServlet.
Memory sentence: "DispatcherServlet = front controller for Spring MVC."
Study: Book chapter
Question 30
Which annotation binds the {id} URI segment to the method parameter?
@GetMapping("/orders/{id}")
public OrderDto get(@PathVariable Long id) { }
- A) @RequestParam
- B) @PathVariable
- C) @RequestBody
- D) @MatrixVariable only
Answer & explanation
Correct answer: B
@PathVariable maps URI template variables from the path to handler method arguments.
Why the other options are wrong:
- A) @RequestParam binds query parameters.
- C) @RequestBody binds the HTTP body.
- D) @MatrixVariable handles matrix parameters, not standard {id} paths.
Memory sentence: "URI template variables → @PathVariable."
Study: Book chapter
Question 31
What does @Valid trigger here?
@PostMapping("/orders")
public ResponseEntity<OrderDto> create(@Valid @RequestBody CreateOrderRequest request) { }
- A) Database constraint validation only
- B) Bean Validation (Jakarta Validation) on the request object fields
- C) CSRF token verification
- D) Automatic URL encoding
Answer & explanation
Correct answer: B
@Valid triggers JSR-380 validators on the request DTO. Violations typically become 400 responses when combined with @ControllerAdvice exception handling.
Why the other options are wrong:
- A) JPA validation is separate from MVC request validation.
- C) CSRF is security filter responsibility.
- D) URL encoding is unrelated.
Memory sentence: "@Valid on @RequestBody triggers Bean Validation on the DTO."
Study: Book chapter
Question 32
A handler throws MethodArgumentNotValidException. Where should it be translated to a consistent JSON error response?
- A) @ControllerAdvice with @ExceptionHandler
- B) Inside every controller method with try/catch only
- C) web.xml error-page entries only
- D) application.properties
Answer & explanation
Correct answer: A
@ControllerAdvice centralizes exception handling across controllers, mapping validation and business exceptions to consistent HTTP responses.
Why the other options are wrong:
- B) Per-controller try/catch duplicates logic.
- C) Boot apps use @ControllerAdvice rather than web.xml for REST errors.
- D) Properties do not define exception mapping.
Memory sentence: "Central REST errors → @ControllerAdvice + @ExceptionHandler."
Study: Book chapter
Question 33
How does Spring MVC use @ResponseStatus on a custom exception?
@ResponseStatus(HttpStatus.NOT_FOUND)
public class OrderNotFoundException extends RuntimeException { }
- A) It is ignored unless the exception extends Exception
- B) It can map the exception to an HTTP status when thrown from a controller
- C) It only works on controller classes
- D) It enables SQL rollback automatically
Answer & explanation
Correct answer: B
@ResponseStatus on an exception class signals the HTTP status code to use when that exception propagates from a handler, often combined with @ControllerAdvice for bodies.
Why the other options are wrong:
- A) Runtime exceptions are typical for this pattern.
- C) It applies to exception types, not only controllers.
- D) Transaction rollback is separate concern.
Memory sentence: "@ResponseStatus on exception → HTTP status when thrown."
Study: Book chapter
Question 34
Content-Type application/json on a POST request is handled by which Spring MVC component?
- A) HandlerMapping only
- B) HttpMessageConverter such as MappingJackson2HttpMessageConverter
- C) BeanFactoryPostProcessor
- D) TransactionInterceptor
Answer & explanation
Correct answer: B
HttpMessageConverters deserialize request bodies and serialize response bodies. Jackson converter handles JSON for @RequestBody and @ResponseBody.
Why the other options are wrong:
- A) HandlerMapping selects the handler, not body conversion.
- C) BeanFactoryPostProcessor runs at context startup.
- D) Transactions are AOP-based, unrelated to JSON parsing.
Memory sentence: "JSON bodies → HttpMessageConverter (Jackson)."
Study: Book chapter
Question 35
A request arrives as GET /reports without a page parameter. What value does page receive?
@GetMapping("/reports")
public List<ReportDto> list(@RequestParam(defaultValue = "0") int page) { }
- A) null
- B) 0
- C) Startup fails
- D) Random page number
Answer & explanation
Correct answer: B
defaultValue on @RequestParam supplies the value when the query parameter is absent.
Why the other options are wrong:
- A) Primitives cannot be null; default applies.
- C) Missing optional params with defaults do not fail binding.
- D) Spring uses the declared default, not random values.
Memory sentence: "@RequestParam defaultValue applies when query param is missing."
Study: Book chapter
Question 36
@RestControllerAdvice compared to @ControllerAdvice on a class that also uses @ResponseBody on methods is primarily:
- A) Equivalent for REST JSON error handling when combined appropriately
- B) Illegal in Spring Boot
- C) Only for JSP views
- D) Replaces DispatcherServlet
Answer & explanation
Correct answer: A
@RestControllerAdvice equals @ControllerAdvice plus @ResponseBody, making it convenient for REST exception handlers returning JSON directly.
Why the other options are wrong:
- B) Both are supported.
- C) REST advice targets HTTP APIs, not JSP-centric flows.
- D) DispatcherServlet remains the front controller.
Memory sentence: "@RestControllerAdvice = @ControllerAdvice + @ResponseBody."
Study: Book chapter
Question 37
What does Spring Data JPA generate for a repository interface extending JpaRepository?
- A) Only a SQL file on disk
- B) A runtime proxy implementation with CRUD and query method support
- C) A concrete class you must compile manually
- D) A JSP tag library
Answer & explanation
Correct answer: B
Spring Data creates a proxy implementation at runtime from the repository interface, including derived query methods and standard JPA operations.
Why the other options are wrong:
- A) Implementation is runtime-generated, not static SQL files only.
- C) No manual implementation is required for standard repos.
- D) Unrelated to JSP.
Memory sentence: "Spring Data JPA repos = runtime-generated implementations."
Study: Book chapter
Question 38
How does Spring Data interpret this method name?
List<Invoice> findByStatusAndDueDateBefore(String status, LocalDate date);
- A) As a native SQL file named findByStatusAndDueDateBefore.sql
- B) As a derived query on entity properties status and dueDate
- C) As a JPQL string requiring @Query always
- D) As a stored procedure automatically
Answer & explanation
Correct answer: B
Derived query methods parse the method name into queries against entity attributes, here filtering by status and dueDate before the given date.
Why the other options are wrong:
- A) No external SQL file is required.
- C) @Query is optional when derivation succeeds.
- D) Procedure mapping requires explicit annotation.
Memory sentence: "Derived query method names map to entity property predicates."
Study: Book chapter
Question 39
Why might orderRepository.save(order) be unnecessary here?
@Transactional
public void cancelOrder(Long id) {
Order order = orderRepository.findById(id).orElseThrow();
order.cancel();
}
- A) JPA never persists changes
- B) Dirty checking tracks changes to managed entities inside the transaction
- C) cancel() automatically calls save
- D) Repositories auto-commit each findById call outside transactions
Answer & explanation
Correct answer: B
Within a transaction, loaded entities are managed. Mutations are detected by dirty checking and flushed on commit without explicit save for existing entities.
Why the other options are wrong:
- A) JPA persists managed entity changes on flush/commit.
- C) cancel() is domain logic; persistence is automatic for managed entities.
- D) findById participates in the current persistence context when transactional.
Memory sentence: "Managed entity changes flush via dirty checking inside a transaction."
Study: Book chapter
Question 40
Default rollback behavior for this checked IOException is:
@Transactional
public void importRows() throws IOException {
rowRepository.saveAll(rows);
throw new IOException("disk full");
}
- A) Transaction commits because checked exceptions do not roll back by default
- B) Always rolls back all exceptions including checked
- C) Rolls back only Error types
- D) IOException is ignored by JPA
Answer & explanation
Correct answer: A
By default Spring rolls back on unchecked exceptions and Error. Checked exceptions commit unless rollbackFor is configured.
Why the other options are wrong:
- B) Checked exceptions are not rollback triggers by default.
- C) Unchecked RuntimeException also rolls back.
- D) IOException affects transaction commit/rollback semantics, not JPA ignoring.
Memory sentence: "Default rollback = unchecked exceptions and Error, not checked."
Study: Book chapter
Question 41
When are lines typically loaded with LAZY fetch?
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
private List<OrderLine> lines;
- A) At application startup for all orders
- B) When the lines collection is accessed inside a session/transaction
- C) Never; LAZY means no loading
- D) Only during component scanning
Answer & explanation
Correct answer: B
Lazy associations load when first accessed while the persistence context is open. Access outside a transaction causes LazyInitializationException.
Why the other options are wrong:
- A) Lazy does not eager-load everything at startup.
- C) Lazy defers loading until access.
- D) Component scanning is unrelated.
Memory sentence: "LAZY loads on access; need open persistence context."
Study: Book chapter
Question 42
N+1 query problem in JPA often occurs when:
- A) Using @Transactional on services
- B) Loading N parent entities then triggering one query per child association access
- C) Using derived query methods only
- D) Using H2 in tests only
Answer & explanation
Correct answer: B
N+1 happens when one query loads parents and lazy child access issues one additional query per parent unless fetch joins or batch fetching is used.
Why the other options are wrong:
- A) Transactions do not inherently cause N+1.
- C) Derived queries are unrelated to association fetch patterns.
- D) N+1 can occur with any database.
Memory sentence: "N+1 = one query for parents + one per child on lazy access."
Study: Book chapter
Question 43
REQUIRES_NEW propagation means:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void writeAudit() { auditRepository.save(entry); }
- A) Join the caller transaction always
- B) Suspend caller transaction and start a new independent transaction
- C) Never use a transaction
- D) Read-only optimization only
Answer & explanation
Correct answer: B
REQUIRES_NEW suspends any existing transaction, opens a new one, commits independently. Caller transaction is unaffected by inner rollback.
Why the other options are wrong:
- A) REQUIRED joins existing; REQUIRES_NEW is independent.
- C) It still uses a transaction, a new one.
- D) readOnly is separate attribute.
Memory sentence: "REQUIRES_NEW = new independent transaction; outer suspended."
Study: Book chapter
Question 44
Another bean calls outer(). Why may inner() not run transactionally?
public void outer() { inner(); }
@Transactional
public void inner() { repository.save(entity); }
- A) @Transactional never works on services
- B) outer() calls inner() via this, bypassing the proxy
- C) save always runs without transactions
- D) Repository saves start their own mandatory transactions only
Answer & explanation
Correct answer: B
Self-invocation within the same class bypasses Spring AOP proxy, so @Transactional on inner() is not applied when called from outer().
Why the other options are wrong:
- A) @Transactional works when calls go through the proxy.
- C) Persistence requires a context; proxy bypass is the trap.
- D) The issue is proxy entry, not repository-only transactions.
Memory sentence: "Same-class calls bypass proxy → @Transactional may not apply."
Study: Book chapter
Question 45
In Spring Security filter chain architecture, where does authentication typically occur relative to authorization?
- A) Authorization always before authentication
- B) Authentication establishes identity before authorization checks access
- C) They are the same filter
- D) Neither runs for REST APIs
Answer & explanation
Correct answer: B
Security filters authenticate (who are you) then authorize (what may you do). Authentication must populate SecurityContext before access decisions.
Why the other options are wrong:
- A) Access decisions need an authenticated principal context first.
- C) Separate filters handle different responsibilities.
- D) REST APIs still use the security filter chain when enabled.
Memory sentence: "Authenticate first, then authorize."
Study: Book chapter
Question 46
What does permitAll() on /public/** mean?
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated());
- A) Requires ADMIN role
- B) Allows access without authentication for matching paths
- C) Disables HTTPS
- D) Enables CSRF protection only on /public
Answer & explanation
Correct answer: B
permitAll grants unrestricted access to matched requests without requiring an authenticated principal.
Why the other options are wrong:
- A) ADMIN would use hasRole.
- C) Transport security is separate.
- D) CSRF rules are configured elsewhere.
Memory sentence: "permitAll = no authentication required for matched paths."
Study: Book chapter
Question 47
Password storage best practice in Spring Security uses:
- A) Plain text PasswordEncoder
- B) BCryptPasswordEncoder or delegating encoder with strong hashing
- C) MD5 without salt
- D) Base64 encoding only
Answer & explanation
Correct answer: B
Spring Security recommends strong adaptive hashing like BCrypt via PasswordEncoder, never plain text or weak hashes.
Why the other options are wrong:
- A) No plain text encoder is secure.
- C) MD5 is unsuitable for password storage.
- D) Base64 is encoding, not hashing.
Memory sentence: "Store passwords with BCrypt PasswordEncoder, not plain text."
Study: Book chapter
Question 48
A stateless JWT REST API typically should:
- A) Enable session creation for every request
- B) Disable CSRF because browsers do not auto-submit JWTs like cookies in classic form posts
- C) Store JWT only in server HttpSession
- D) Remove all authorization rules
Answer & explanation
Correct answer: B
Stateless token APIs often disable CSRF because CSRF targets cookie-based session auth. JWT in Authorization header is a different threat model.
Why the other options are wrong:
- A) Stateless design avoids server sessions per request.
- C) JWT stateless pattern avoids HttpSession for auth token.
- D) Authorization remains required.
Memory sentence: "Stateless JWT APIs often disable CSRF; still authorize endpoints."
Study: Book chapter
Question 49
When is this authorization enforced for Spring MVC beans?
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { }
- A) Only at compile time
- B) At method invocation via method security AOP after @EnableMethodSecurity
- C) Only in the database layer
- D) Only for static methods
Answer & explanation
Correct answer: B
@PreAuthorize is evaluated by method security interceptors around bean method calls when method security is enabled.
Why the other options are wrong:
- A) Enforcement is runtime via AOP.
- C) It guards the service method, not SQL directly.
- D) Instance methods on Spring beans are advised.
Memory sentence: "@PreAuthorize enforced at runtime by method security AOP."
Study: Book chapter
Question 50
CORS configuration in Spring Security/Boot addresses:
- A) Cross-origin browser requests and preflight OPTIONS handling
- B) SQL injection prevention
- C) Password hashing
- D) JPA lazy loading
Answer & explanation
Correct answer: A
CORS controls which browser origins may call APIs cross-origin, including preflight OPTIONS for non-simple requests.
Why the other options are wrong:
- B) SQL injection is input/parameterization concern.
- C) Passwords use PasswordEncoder.
- D) JPA lazy loading is persistence concern.
Memory sentence: "CORS = cross-origin browser access rules and preflight."
Study: Book chapter
Question 51
@WebMvcTest primarily loads:
- A) Full application context including all repositories and schedulers
- B) Web layer slice: MVC, Jackson, often @Controller under test with mocked collaborators
- C) Only JPA entities without controllers
- D) Production database migrations only
Answer & explanation
Correct answer: B
@WebMvcTest is a narrow slice for controller testing with MockMvc, not full stack integration.
Why the other options are wrong:
- A) Full context is @SpringBootTest.
- C) JPA slice is @DataJpaTest.
- D) Flyway/Liquibase may run in integration tests, not web slice default.
Memory sentence: "@WebMvcTest = MVC slice + MockMvc, not full context."
Study: Book chapter
Question 52
Why is @MockBean used here?
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@MockBean OrderService orderService;
}
- A) To replace a missing dependency in the test ApplicationContext with a Mockito mock bean
- B) To enable production database access
- C) To disable MockMvc
- D) To run tests without Spring
Answer & explanation
Correct answer: A
@MockBean registers a Mockito mock in the Spring test context, replacing or adding a bean needed by the web slice.
Why the other options are wrong:
- B) Web slice avoids real persistence by default.
- C) MockMvc still works.
- D) @WebMvcTest still uses Spring test context.
Memory sentence: "@MockBean puts a mock into the Spring test context."
Study: Book chapter
Question 53
@DataJpaTest typically auto-configures:
- A) Full Spring Security filter chain and all controllers
- B) In-memory DataSource, JPA, TestEntityManager, and repository under test
- C) Only MockMvc
- D) Only @Scheduled tasks
Answer & explanation
Correct answer: B
@DataJpaTest focuses on JPA components with an embedded database and TestEntityManager for persistence tests.
Why the other options are wrong:
- A) Security and controllers are excluded from JPA slice.
- C) MockMvc belongs to web tests.
- D) Scheduling is not the JPA slice focus.
Memory sentence: "@DataJpaTest = JPA + embedded DB + TestEntityManager."
Study: Book chapter
Question 54
@SpringBootTest compared to slice tests:
- A) Loads the complete application context (or near-complete) for integration testing
- B) Always faster because it loads less
- C) Cannot use @Autowired
- D) Disables all beans
Answer & explanation
Correct answer: A
@SpringBootTest boots the full application context, suitable for integration tests verifying wiring across layers.
Why the other options are wrong:
- B) Full context is heavier, not lighter.
- C) @Autowired works in SpringBootTest.
- D) It loads real beans unless mocked.
Memory sentence: "@SpringBootTest = full integration context."
Study: Book chapter
Question 55
This @WebMvcTest test verifies primarily:
@Test
void delegatesToService() {
when(orderService.find(1L)).thenReturn(Optional.of(dto));
mockMvc.perform(get("/orders/1")).andExpect(status().isOk());
}
- A) Database constraint correctness
- B) HTTP mapping and controller delegation with mocked service
- C) Production actuator health
- D) Git commit hooks
Answer & explanation
Correct answer: B
MockMvc exercises the web layer while @MockBean isolates collaborators, proving mapping, status, and JSON without full stack.
Why the other options are wrong:
- A) Database belongs to @DataJpaTest or integration tests.
- C) Actuator is separate test concern.
- D) Unrelated to MVC tests.
Memory sentence: "MockMvc + @MockBean tests controller wiring in isolation."
Study: Book chapter
Question 56
@Mock versus @MockBean: key difference?
- A) @Mock is pure Mockito without Spring context; @MockBean registers mock in Spring test context
- B) They are identical always
- C) @MockBean only works in main application
- D) @Mock loads the full Spring Boot app
Answer & explanation
Correct answer: A
@Mock is for plain unit tests. @MockBean integrates Mockito mocks into Spring TestContext replacing container beans.
Why the other options are wrong:
- B) Integration with Spring context differs.
- C) @MockBean is for tests.
- D) @Mock does not start Spring.
Memory sentence: "@Mock = Mockito only; @MockBean = mock inside Spring test context."
Study: Book chapter
Question 57
In Spring AOP, a join point is typically:
- A) A method execution on a Spring-managed bean
- B) Any line of bytecode in the JVM
- C) Only database trigger execution
- D) Only static initializer blocks
Answer & explanation
Correct answer: A
Spring AOP supports method execution join points on Spring beans. It is not full AspectJ weaving of every possible join point by default.
Why the other options are wrong:
- B) Spring AOP is method-interception based on beans.
- C) Database triggers are outside Spring AOP.
- D) Static blocks are not advised by default Spring AOP.
Memory sentence: "Spring AOP join point = method execution on a Spring bean."
Study: Book chapter
Question 58
What does @Around advice control?
@Aspect
@Component
public class TimingAspect {
@Around("execution(* com.example.service..*(..))")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
Object result = pjp.proceed();
// log duration
return result;
}
}
- A) Only code before the method
- B) Wraps the join point and can run code before, after, and control proceed()
- C) Only after successful return
- D) Only uncaught exceptions
Answer & explanation
Correct answer: B
@Around advice surrounds the join point. It must call proceed() to invoke the target and can modify arguments, return value, or handle exceptions.
Why the other options are wrong:
- A) Before-only is @Before advice.
- C) After return is @AfterReturning.
- D) Exception handling can use @AfterThrowing.
Memory sentence: "@Around wraps the method and calls proceed() to continue."
Study: Book chapter
Question 59
@EnableAsync on a configuration class enables:
- A) Synchronous-only method execution
- B) Proxy-based asynchronous execution for @Async methods via a task executor
- C) Automatic HTTP caching
- D) JPA second-level cache only
Answer & explanation
Correct answer: B
@EnableAsync registers infrastructure that executes @Async methods on a task executor thread instead of the caller thread.
Why the other options are wrong:
- A) It enables async, not sync-only.
- C) HTTP caching is separate.
- D) JPA cache is persistence configuration.
Memory sentence: "@EnableAsync + @Async runs methods on executor threads."
Study: Book chapter
Question 60
Spring application events published via ApplicationEventPublisher are by default:
- A) Persisted to the database automatically
- B) Delivered synchronously to listeners in the publishing thread unless @Async is used on listeners
- C) Sent over HTTP to all clients
- D) Ignored unless the publisher is a @Controller
Answer & explanation
Correct answer: B
Default event delivery is synchronous in the caller thread. @Async listeners with async enabled can process in background threads.
Why the other options are wrong:
- A) Events are in-memory by default.
- C) Events are not HTTP broadcasts.
- D) Any bean can publish and listen for events.
Memory sentence: "Spring events are synchronous by default in the publisher thread."
Study: Book chapter
End of Mock Full 05 — Spring Professional (60 Questions)