Mock Full 01 — 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 legacy monolith is being migrated to Spring. The team wants loose coupling between services but keeps seeing NullPointerException when collaborators are not wired.
Which Spring mechanism directly addresses the problem of objects creating their own dependencies and failing when collaborators are missing?
- A) Component scanning only
- B) Bean lifecycle callbacks
- C) Dependency Injection via the IoC container
- D) Property placeholder resolution
Answer & explanation
Correct answer: C
Dependency Injection (DI) is the core IoC pattern where the container supplies collaborators instead of classes using new or static lookups. This removes tight coupling and ensures required dependencies are provided at creation time, which is exactly what prevents ad-hoc null collaborators in a Spring application.
Why the other options are wrong:
- A) Component scanning discovers beans but does not by itself inject dependencies into arbitrary objects.
- B) Lifecycle callbacks run after a bean exists; they do not replace the wiring of dependencies.
- D) Property placeholders inject configuration values, not arbitrary object collaborators.
Memory sentence: "DI means the container wires collaborators; objects do not new their dependencies."
Study: Book chapter
Question 2
During startup debugging, a developer compares BeanFactory and ApplicationContext behavior in a web application.
Which statement about ApplicationContext compared to BeanFactory is correct?
@Configuration
public class AppConfig {
@Bean
public PaymentService paymentService() {
return new PaymentService();
}
}
- A) BeanFactory eagerly initializes all singleton beans at refresh time while ApplicationContext is lazy
- B) Only BeanFactory supports @Configuration class processing
- C) ApplicationContext cannot load bean definitions from Java configuration
- D) ApplicationContext is a superset that adds enterprise features such as event publication and internationalization
Answer & explanation
Correct answer: D
ApplicationContext extends BeanFactory and adds higher-level container capabilities including application event propagation, MessageSource access, resource loading patterns, and automatic BeanPostProcessor registration. BeanFactory is the minimal contract; ApplicationContext is what Spring Boot uses in practice.
Why the other options are wrong:
- A) The opposite is closer to the truth: ApplicationContext eagerly creates singletons by default during refresh.
- B) @Configuration processing is handled by configuration-class post-processors registered in the ApplicationContext.
- C) ApplicationContext fully supports @Configuration and @Bean definitions.
Memory sentence: "ApplicationContext = BeanFactory plus events, i18n, and richer startup integration."
Study: Book chapter
Question 3
A bean definition specifies class com.example.ReportService and scope singleton. Two different @Autowired fields in the same application both receive a ReportService. What is guaranteed?
@Service
public class ReportService { }
@Autowired ReportService a;
@Autowired ReportService b; // same instance as a
- A) Each injection point receives a distinct instance because fields are separate
- B) A new instance is created per injection point
- C) Prototype scope is implied whenever @Autowired is used
- D) Both injection points receive the same singleton instance managed by the container
Answer & explanation
Correct answer: D
Default singleton scope means one shared instance per bean definition in the container. Every injection point referencing that bean name/type receives the same object reference unless an explicit narrower scope or provider indirection is used.
Why the other options are wrong:
- A) Separate fields do not imply separate bean instances under singleton scope.
- B) Singleton beans are not created per injection site.
- C) @Autowired does not change scope; scope comes from the bean definition.
Memory sentence: "Singleton = one container-managed instance shared by all injection points."
Study: Book chapter
Question 4
An OrderService constructor requires a PaymentGateway. The team adds @Autowired on the constructor after introducing a second constructor for testing.
What happens when OrderService has two constructors and only one is annotated with @Autowired?
@Service
public class OrderService {
private final PaymentGateway gateway;
public OrderService(PaymentGateway gateway) {
this.gateway = gateway;
}
public OrderService() {
this.gateway = null;
}
}
- A) Spring always chooses the no-arg constructor
- B) Spring uses the @Autowired constructor for dependency injection
- C) Spring fails startup because multiple constructors are illegal
- D) Spring injects into fields instead when multiple constructors exist
Answer & explanation
Correct answer: B
When multiple constructors exist, Spring 4.3+ can autowire a single constructor without annotation if it is the only one, but if more than one constructor exists you must mark the intended one with @Autowired (or use @Required on older versions). The annotated constructor becomes the injection target.
Why the other options are wrong:
- A) With multiple constructors Spring does not default to no-arg unless it is the only autowirable candidate.
- C) Multiple constructors are supported when the intended one is explicitly selected.
- D) Constructor ambiguity is resolved by constructor selection, not automatic field injection.
Memory sentence: "Multiple constructors: mark the injection constructor with @Autowired."
Study: Book chapter
Question 5
Which injection style is generally preferred in Spring for required immutable dependencies and testability?
@Service
public class InvoiceService {
private final TaxService taxService;
public InvoiceService(TaxService taxService) {
this.taxService = taxService;
}
}
- A) Field injection with @Autowired
- B) Setter injection only
- C) Constructor injection
- D) Static factory lookup from ApplicationContextHolder
Answer & explanation
Correct answer: C
Constructor injection makes dependencies explicit, enables immutable fields, simplifies unit testing without Spring, and avoids hidden dependencies on fields. Spring documentation and exam materials consistently treat constructor injection as the preferred style for required collaborators.
Why the other options are wrong:
- A) Field injection hides dependencies and complicates testing.
- B) Setter injection is useful for optional dependencies but is not the general best practice for required ones.
- D) Static context lookups are an anti-pattern that tightly couples code to the framework.
Memory sentence: "Prefer constructor injection for required, immutable collaborators."
Study: Book chapter
Question 6
A library module is added under com.vendor.integration, but beans in that package are not created at runtime.
The main application class is in com.example.app and uses @SpringBootApplication. Beans in com.vendor.integration are annotated with @Component but never register. What is the most likely cause?
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- A) Component scanning starts at the @SpringBootApplication class package and does not include com.vendor.integration by default
- B) @Component cannot be used outside the main application package
- C) Spring Boot disables scanning unless spring.scan.enabled=true
- D) Only @Bean methods can register beans outside the main package
Answer & explanation
Correct answer: A
@SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan with default base package equal to the declaring class package. Classes outside that package tree are not scanned unless you add @ComponentScan basePackages or use @Import.
Why the other options are wrong:
- B) @Component works in any package that is scanned.
- C) There is no standard spring.scan.enabled switch; scanning is on by default via @SpringBootApplication.
- D) @Component scanning is a normal way to register beans outside the main package when scan paths include them.
Memory sentence: "@SpringBootApplication scans its own package subtree only unless you widen @ComponentScan."
Study: Book chapter
Question 7
What is the effect of @Primary on a bean of type NotificationSender when multiple NotificationSender beans exist?
@Bean @Primary
public NotificationSender emailSender() { return new EmailSender(); }
@Bean
public NotificationSender smsSender() { return new SmsSender(); }
- A) It marks the bean as the only allowed implementation and disables others
- B) It gives the bean higher @Order for AOP advice
- C) It changes the bean scope to singleton
- D) It makes that bean the preferred candidate when autowiring by type without @Qualifier
Answer & explanation
Correct answer: D
@Primary resolves ambiguity when multiple beans match an injection point type. If no @Qualifier is present, the primary bean is chosen. Other beans remain valid and can still be injected with @Qualifier or @Resource name.
Why the other options are wrong:
- A) @Primary does not disable other beans.
- B) @Order affects ordered lists and some infrastructure ordering, not @Primary selection.
- C) @Primary does not alter scope.
Memory sentence: "@Primary breaks type ambiguity; @Qualifier picks a specific bean explicitly."
Study: Book chapter
Question 8
A reporting module needs the latest ExchangeRateService implementation, but two beans implement the interface.
A field is declared as @Autowired ExchangeRateService service. Two beans exist: exchangeRateServiceLegacy and exchangeRateServiceV2. How do you inject exchangeRateServiceV2 explicitly?
- A) Add @Lazy to the field
- B) Use @Qualifier("exchangeRateServiceV2") or equivalent bean name qualifier
- C) Mark exchangeRateServiceV2 with @Controller
- D) Remove @Autowired and call getBean manually in @PostConstruct
Answer & explanation
Correct answer: B
When multiple beans match a type, @Qualifier (or @Resource with name) selects the intended bean by name or custom qualifier annotation. This is the idiomatic Spring solution for explicit disambiguation.
Why the other options are wrong:
- A) @Lazy only delays initialization; it does not choose between candidates.
- C) Stereotype annotations do not resolve injection ambiguity by themselves.
- D) Manual getBean works but is not the declarative injection approach the exam expects.
Memory sentence: "Multiple beans of one type: use @Qualifier or @Primary."
Study: Book chapter
Question 9
Which statement about @Autowired required semantics is correct by default?
- A) Injection is optional unless @Autowired(required = false) is specified
- B) Primitive dependencies are always optional
- C) All dependencies are lazy-initialized regardless of annotation
- D) If no matching bean exists, the context fails to start with a NoSuchBeanDefinitionException
Answer & explanation
Correct answer: D
By default @Autowired is required=true. If Spring cannot resolve a unique matching bean for a required injection point, application context initialization fails fast with NoSuchBeanDefinitionException or related ambiguity exception.
Why the other options are wrong:
- A) Required is true by default; optional injection needs required=false.
- B) Missing primitive collaborators still fail because null cannot be injected.
- C) @Autowired does not force lazy initialization of the dependency.
Memory sentence: "Default @Autowired is required; use required=false only for optional collaborators."
Study: Book chapter
Question 10
A team debates whether to use XML, Java config, or component scanning for a small internal utility library consumed by Spring Boot apps.
Which approach lets Spring discover classes annotated with stereotype annotations without writing explicit @Bean methods for each class?
@Service
public class PricingService { }
- A) Declaring every class in beans.xml
- B) Using BeanFactoryPostProcessor manually for each type
- C) Component scanning with @Component, @Service, @Repository, or @Controller
- D) Registering classes only through @PropertySource
Answer & explanation
Correct answer: C
Component scanning detects classpath candidates annotated with stereotype annotations and registers them as bean definitions automatically. This removes boilerplate @Bean factory methods for straightforward classes.
Why the other options are wrong:
- A) XML can declare beans but does not auto-discover annotated classes unless component-scan is configured.
- B) BeanFactoryPostProcessor is a low-level extension point, not the normal discovery mechanism.
- D) @PropertySource loads properties, not component classes.
Memory sentence: "Stereotype annotations plus component scanning auto-register beans."
Study: Book chapter
Question 11
In a @Configuration class, what does @Bean on a method tell Spring to do?
@Configuration
public class AppConfig {
@Bean
public Clock systemClock() {
return Clock.systemUTC();
}
}
- A) Instantiate the return type immediately when the class is loaded
- B) Register the method return value as a bean managed by the container
- C) Expose the method as a REST endpoint
- D) Run the method on every HTTP request
Answer & explanation
Correct answer: B
@Bean methods are processed by configuration class enhancement so Spring invokes them to produce beans registered in the container. The container controls lifecycle and injection of that returned object.
Why the other options are wrong:
- A) The JVM loading the class does not create the bean; the container does during context refresh.
- C) REST exposure requires web mapping annotations, not @Bean.
- D) @Bean has no request scope behavior by itself.
Memory sentence: "@Bean method = factory method whose return value becomes a Spring bean."
Study: Book chapter
Question 12
A payment client should point to sandbox in non-production and production URL when profile prod is active.
Which combination is the idiomatic way to provide different PaymentClient beans per environment?
@Bean
@Profile("prod")
public PaymentClient prodClient() { return new ProdPaymentClient(); }
@Bean
@Profile("!prod")
public PaymentClient sandboxClient() { return new SandboxPaymentClient(); }
- A) Two @Bean methods with @Profile conditions selecting different environments
- B) One bean and manual if statements inside main
- C) Changing scope to prototype only
- D) Using @Order on both beans without profiles
Answer & explanation
Correct answer: A
@Profile conditionally registers bean definitions based on active profiles. This keeps environment-specific wiring declarative and integrates cleanly with Spring Boot profile activation through properties or environment variables.
Why the other options are wrong:
- B) Manual branching in main bypasses the container and is not idiomatic Spring configuration.
- C) Prototype scope creates new instances but does not select environment-specific implementations.
- D) @Order does not activate beans by environment.
Memory sentence: "Use @Profile to register environment-specific beans declaratively."
Study: Book chapter
Question 13
What does @ConfigurationProperties(prefix = "app.mail") on a class primarily enable?
@ConfigurationProperties(prefix = "app.mail")
public record MailProperties(String host, int port) {}
- A) Creating a JPA entity mapped to the mail table
- B) Enabling method-level transaction management for mail code
- C) Binding external configuration properties with the app.mail prefix onto the class fields
- D) Scanning the classpath for mail templates only
Answer & explanation
Correct answer: C
@ConfigurationProperties binds structured configuration from property files, environment variables, and other PropertySources onto a typed object. This is preferred over many separate @Value injections for grouped settings.
Why the other options are wrong:
- A) It is unrelated to JPA entity mapping.
- B) Transaction management comes from @EnableTransactionManagement, not @ConfigurationProperties.
- D) It does not perform template classpath scanning.
Memory sentence: "@ConfigurationProperties groups and binds external config into a typed bean."
Study: Book chapter
Question 14
A singleton DashboardService injects a request-scoped UserContext bean. Users report all requests see the same user data.
What is the correct fix when a singleton bean needs a fresh UserContext per HTTP request?
- A) Change DashboardService to prototype scope only
- B) Mark UserContext with @RequestScope and inject a proxy into the singleton using scoped-proxy
- C) Store UserContext in a static ThreadLocal manually without Spring support
- D) Disable singleton scope globally in application.properties
Answer & explanation
Correct answer: B
A shorter-lived scoped bean injected into a longer-lived singleton must use a scoped proxy so the singleton holds a proxy that delegates to the current scope instance per request. Spring provides this via @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) or @RequestScope on a bean consumed through injection proxy.
Why the other options are wrong:
- A) Making the singleton prototype would create many service instances and usually breaks intended architecture.
- C) Manual static ThreadLocal bypasses Spring scope management and is an anti-pattern here.
- D) Singleton is the default and cannot be globally disabled that way.
Memory sentence: "Singleton injecting request/session bean needs scoped proxy."
Study: Book chapter
Question 15
Which bean scope creates a new instance every time the bean is requested from the container?
- A) Singleton
- B) Prototype
- C) Request
- D) Application
Answer & explanation
Correct answer: B
Prototype scope tells Spring to create a new bean instance for each getBean or injection point resolution depending on context, unlike singleton where one instance is shared.
Why the other options are wrong:
- A) Singleton returns the same shared instance.
- C) Request scope is one instance per HTTP request, not every injection.
- D) Application scope is one per ServletContext in web apps.
Memory sentence: "Prototype = new instance per retrieval/injection cycle."
Study: Book chapter
Question 16
Operations activates spring.profiles.active=prod,cloud on deployment. Some beans still load from the default profile set.
How does Spring evaluate @Profile("prod") on a @Bean method when active profiles are prod and cloud?
- A) The bean is not registered because multiple active profiles invalidate @Profile
- B) The bean is registered because prod is among the active profiles
- C) The bean registers only if cloud is also named in @Profile
- D) Profiles must be mutually exclusive or startup fails
Answer & explanation
Correct answer: B
Multiple active profiles coexist. A @Profile condition matches if any listed profile expression is satisfied. @Profile("prod") matches when prod is active, regardless of additional profiles like cloud.
Why the other options are wrong:
- A) Multiple active profiles are normal and supported.
- C) @Profile("prod") does not require every active profile to appear in the annotation.
- D) Profiles are not required to be mutually exclusive.
Memory sentence: "Multiple profiles can be active; @Profile matches if its expression is satisfied."
Study: Book chapter
Question 17
What is the purpose of a BeanPostProcessor in the Spring container lifecycle?
- A) To replace PropertySource files at runtime
- B) To intercept bean initialization and modify or wrap beans before and after initialization callbacks
- C) To compile @Configuration classes to bytecode faster
- D) To map HTTP requests to controller methods
Answer & explanation
Correct answer: B
BeanPostProcessor is an extension point invoked before and after bean initialization for each bean. Spring uses many internal BPPs for annotation processing, AOP proxy creation, and @Autowired injection.
Why the other options are wrong:
- A) PropertySource changes are handled by Environment and PropertySource mechanisms.
- C) Configuration class processing uses ConfigurationClassPostProcessor, a specialized BPP, but generic BPP purpose is bean customization.
- D) Handler mapping is part of Spring MVC, not BeanPostProcessor.
Memory sentence: "BeanPostProcessor hooks before/after bean initialization for every bean."
Study: Book chapter
Question 18
A @Configuration class defines two @Bean methods where one calls the other directly within the same class.
What does Spring do to @Bean method inter-calls inside the same @Configuration class?
@Configuration
public class BillingConfig {
@Bean
public InvoiceService invoiceService(TaxCalculator taxCalculator) {
return new InvoiceService(taxCalculator);
}
@Bean
public TaxCalculator taxCalculator() {
return new TaxCalculator();
}
}
- A) Each call creates a fresh object because they are plain Java method calls
- B) Spring proxies the configuration class so @Bean method calls go through the container and respect singleton semantics
- C) Inter-calls are forbidden and cause BeanCurrentlyInCreationException
- D) Only XML configuration can share beans between factory methods
Answer & explanation
Correct answer: B
Full @Configuration classes are enhanced so inter-bean method calls are proxied through the container. This ensures singleton beans are reused rather than accidentally recreated by direct Java calls.
Why the other options are wrong:
- A) Plain @Configuration without full mode would recreate beans, but full @Configuration proxies prevent that.
- C) Inter-calls are supported by design.
- D) Java @Configuration is the standard approach for related @Bean methods.
Memory sentence: "Full @Configuration proxies @Bean method calls so singletons stay singleton."
Study: Book chapter
Question 19
Which three annotations are meta-composed into @SpringBootApplication?
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
- A) @EnableWebMvc, @EnableJpaRepositories, @EnableScheduling
- B) @Controller, @Service, @Repository
- C) @Transactional, @Validated, @CrossOrigin
- D) @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan
Answer & explanation
Correct answer: D
@SpringBootApplication combines @SpringBootConfiguration (specialized @Configuration), @EnableAutoConfiguration, and @ComponentScan (with optional attributes). This is the bootstrap annotation for Spring Boot apps.
Why the other options are wrong:
- A) Those are separate opt-in annotations, not part of @SpringBootApplication.
- B) Stereotype annotations are not meta-composed into @SpringBootApplication.
- C) Those annotations serve other concerns and are not the Boot bootstrap trio.
Memory sentence: "@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan."
Study: Book chapter
Question 20
A team adds spring-boot-starter-data-jpa but wants to supply a custom DataSource bean from corporate library code.
If you define your own DataSource @Bean, what does Spring Boot auto-configuration typically do?
- A) It fails because two DataSource beans are never allowed
- B) It backs off and does not auto-configure a default DataSource
- C) It always creates the default HikariCP DataSource anyway
- D) It deletes the custom bean and keeps only the auto-configured one
Answer & explanation
Correct answer: B
Spring Boot auto-configuration uses @ConditionalOnMissingBean so user-defined beans take precedence. When you provide your own DataSource, DataSource auto-configuration steps aside, which is the back-off pattern tested frequently.
Why the other options are wrong:
- A) Multiple definitions are allowed when auto-config backs off.
- C) Auto-config respects existing user beans via missing-bean conditions.
- D) Spring never silently removes user beans.
Memory sentence: "User @Bean of a type causes matching auto-configuration to back off."
Study: Book chapter
Question 21
Which property helps generate a report of auto-configuration decisions showing what matched and what did not?
# application.properties
debug=true
- A) spring.main.banner-mode=off
- B) logging.level.root=ERROR
- C) debug=true
- D) spring.jpa.show-sql=true
Answer & explanation
Correct answer: C
Setting debug=true (or --debug) enables the auto-configuration report printed at startup and in the logs, listing positive and negative matches. This is the primary tool for understanding why a Boot auto-config did or did not apply.
Why the other options are wrong:
- A) Banner mode only affects the startup banner.
- B) Root log level does not emit the condition evaluation report by itself.
- D) show-sql logs SQL statements, not auto-configuration conditions.
Memory sentence: "debug=true prints the auto-configuration condition evaluation report."
Study: Book chapter
Question 22
A microservice exposes management endpoints on a separate port for the platform team.
Which configuration moves Actuator HTTP endpoints to port 9090 while keeping the main app on 8080?
management.server.port=9090
- A) server.port=9090 only
- B) management.endpoints.web.exposure.include=* only
- C) spring.application.name=actuator
- D) management.server.port=9090 on a separate management listener
Answer & explanation
Correct answer: D
management.server.port creates a separate management server/port for Actuator endpoints in servlet-based apps, allowing network isolation from the main application port configured by server.port.
Why the other options are wrong:
- A) server.port moves the main application, not just Actuator.
- B) Exposure settings control which endpoints are web-visible, not the port.
- C) Application name does not bind Actuator to another port.
Memory sentence: "management.server.port runs Actuator on its own HTTP port."
Study: Book chapter
Question 23
By default in Spring Boot 2.x/3.x, which Actuator endpoint is exposed over HTTP without additional configuration?
- A) env
- B) beans
- C) health
- D) shutdown
Answer & explanation
Correct answer: C
Default web exposure historically includes only health (and info in some versions with details hidden). Sensitive endpoints like env, beans, and shutdown require explicit exposure configuration for security reasons.
Why the other options are wrong:
- A) env is not exposed by default over the web.
- B) beans is not in the default web exposure set.
- D) shutdown is disabled and not exposed by default.
Memory sentence: "Default exposed Actuator web endpoint is health unless you widen exposure."
Study: Book chapter
Question 24
Production health checks must report DOWN when the app cannot reach its required database, but still start the JVM.
Which approach integrates database availability into the application health endpoint correctly?
- A) Write a custom main method try/catch around SpringApplication.run only
- B) Rely on HealthContributor or DataSource health indicator auto-configuration for the health endpoint
- C) Disable all Actuator endpoints in production
- D) Use @PostConstruct in every repository class
Answer & explanation
Correct answer: B
Spring Boot Actuator health groups infrastructure checks through HealthContributor beans. DataSourceHealthContributor auto-configuration reports database status on /actuator/health, which orchestrators can use without custom shutdown logic.
Why the other options are wrong:
- A) try/catch in main does not produce structured health endpoint results.
- C) Disabling Actuator removes the standard health signal operators expect.
- D) Repository @PostConstruct does not integrate with Actuator health aggregation.
Memory sentence: "Health contributors aggregate component status into /actuator/health."
Study: Book chapter
Question 25
What is the primary purpose of Spring Boot starters such as spring-boot-starter-web?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- A) They replace the need for an ApplicationContext
- B) They automatically write controller code from OpenAPI files
- C) They disable auto-configuration to keep apps minimal
- D) They bundle curated dependencies with versions aligned by spring-boot-dependencies BOM
Answer & explanation
Correct answer: D
Starters are dependency descriptors that pull in a sensible set of libraries with versions managed by the Boot BOM. They reduce manual dependency wiring while staying compatible with Boot auto-configuration.
Why the other options are wrong:
- A) The container still manages beans; starters only affect classpath dependencies.
- B) Starters do not generate application code.
- C) Starters usually enable related auto-configuration when on the classpath.
Memory sentence: "Starters = curated dependencies with BOM-managed versions."
Study: Book chapter
Question 26
Startup is slow and the team suspects beans that are never used still initialize eagerly.
Which Spring Boot feature delays creation of singleton beans until first use?
- A) spring.main.lazy-initialization=true
- B) @RefreshScope on every bean
- C) spring.jpa.defer-datasource-initialization only
- D) server.tomcat.max-threads=1
Answer & explanation
Correct answer: A
Global lazy initialization tells the application context to create singleton beans when first requested rather than at refresh time. This can shorten startup when many beans are unused early, with trade-offs in fail-fast timing.
Why the other options are wrong:
- B) @RefreshScope is for Cloud refreshable beans, not general lazy startup.
- C) Defer datasource initialization affects SQL init timing, not all bean creation.
- D) Tomcat thread settings do not control bean initialization timing.
Memory sentence: "spring.main.lazy-initialization=true creates singletons on first use."
Study: Book chapter
Question 27
A class implements ApplicationRunner and is registered as a Spring bean. When does its run method execute?
- A) Before the ApplicationContext is created
- B) After the context is refreshed and the application has started, as part of startup callbacks
- C) On every HTTP request after DispatcherServlet mapping
- D) Only when actuator/refresh is called
Answer & explanation
Correct answer: B
ApplicationRunner and CommandLineRunner beans execute after context startup is complete, offering a safe point to run logic when the application is ready. Spring Boot collects and invokes them during startup.
Why the other options are wrong:
- A) The context must exist and be refreshed first.
- C) Runners are startup hooks, not per-request handlers.
- D) Refresh endpoints are unrelated to standard ApplicationRunner execution.
Memory sentence: "ApplicationRunner runs once after the Spring context has started."
Study: Book chapter
Question 28
An auto-config class should apply only when class org.apache.catalina.startup.Tomcat is present on the classpath.
Which condition annotation expresses classpath-based auto-configuration guards?
- A) @ConditionalOnBean(Tomcat.class)
- B) @ConditionalOnWebApplication only
- C) @Profile("tomcat")
- D) @ConditionalOnClass(name = "org.apache.catalina.startup.Tomcat")
Answer & explanation
Correct answer: D
@ConditionalOnClass checks for the presence of specified classes on the classpath without requiring the class to be loaded into the configuration class itself. Auto-configuration modules use it heavily to activate servlet, Tomcat, or library-specific config.
Why the other options are wrong:
- A) @ConditionalOnBean checks for existing beans, not mere classpath presence.
- B) @ConditionalOnWebApplication checks app type, not a specific Tomcat class.
- C) Profiles are orthogonal to classpath conditions.
Memory sentence: "@ConditionalOnClass gates auto-config on classpath presence safely."
Study: Book chapter
Question 29
A browser form POST and a mobile JSON client both hit the same endpoint. The team wants one controller method to handle binding appropriately.
In Spring MVC, which component is the front controller that receives all HTTP requests and delegates to handler mappings and controllers?
Client -> DispatcherServlet -> HandlerMapping -> Controller
- A) HttpServletRequestWrapper
- B) BeanFactory
- C) DispatcherServlet
- D) HandlerInterceptor only
Answer & explanation
Correct answer: C
DispatcherServlet is the Spring MVC front controller. It routes requests through HandlerMapping, HandlerAdapter, controller invocation, view resolution or message conversion, and exception handling.
Why the other options are wrong:
- A) RequestWrapper is a servlet API decoration, not the MVC front controller.
- B) BeanFactory is the core IoC container, not the web dispatcher.
- D) HandlerInterceptor participates in the chain but does not replace DispatcherServlet.
Memory sentence: "DispatcherServlet is the Spring MVC front controller entry point."
Study: Book chapter
Question 30
Which annotation on a controller method maps HTTP GET requests to /api/orders/{id} and binds the path variable id?
@GetMapping("/api/orders/{id}")
public OrderDto get(@PathVariable Long id) { return orderService.find(id); }
- A) @RequestParam("id") on the method
- B) @PostMapping("/api/orders")
- C) @GetMapping with @PathVariable for {id}
- D) @ResponseStatus only without mapping
Answer & explanation
Correct answer: C
@GetMapping on /api/orders/{id} combined with @PathVariable extracts the URI template variable. This is the standard REST pattern for resource retrieval by identifier.
Why the other options are wrong:
- A) @RequestParam reads query parameters, not URI path segments.
- B) POST is the wrong HTTP method for idempotent retrieval by id.
- D) @ResponseStatus sets status codes but does not define the route.
Memory sentence: "Path variables use {name} in the mapping plus @PathVariable."
Study: Book chapter
Question 31
A POST endpoint accepts JSON but clients sometimes send XML. The team wants JSON by default without custom parsers.
How does Spring MVC typically serialize and deserialize request/response bodies in @RestController methods?
- A) Through HttpMessageConverter implementations selected by content type and method return type
- B) By writing directly to ServletOutputStream in every controller
- C) Using JDBC ResultSet mapping
- D) Only through JSP view rendering
Answer & explanation
Correct answer: A
RequestResponseBodyMethodProcessor uses HttpMessageConverter beans such as MappingJackson2HttpMessageConverter to convert bodies to objects and back based on Content-Type, Accept, and method signatures with @RequestBody and @ResponseBody semantics.
Why the other options are wrong:
- B) Controllers normally stay declarative; converters handle IO.
- C) JDBC is persistence layer concern, not MVC body conversion.
- D) JSP views are for view resolution, not typical @RestController JSON APIs.
Memory sentence: "HttpMessageConverters bind request/response bodies in Spring MVC."
Study: Book chapter
Question 32
What is the effect of @RestController on a class compared to @Controller?
- A) It combines @Controller and @ResponseBody, writing return values through message converters
- B) It disables DispatcherServlet for that class
- C) It forces all methods to return ModelAndView only
- D) It automatically adds Spring Security filters
Answer & explanation
Correct answer: A
@RestController is a composed annotation equivalent to @Controller plus @ResponseBody at the class level, meaning method return values are serialized to the HTTP response body instead of resolved as view names.
Why the other options are wrong:
- B) DispatcherServlet still dispatches to the controller.
- C) ModelAndView is the opposite of typical REST JSON return style.
- D) Security is configured separately, not by @RestController.
Memory sentence: "@RestController = @Controller + @ResponseBody."
Study: Book chapter
Question 33
A client sends POST /api/users with missing email. The API should return 400 with validation details.
Which setup enables automatic validation of request body fields annotated with Jakarta Bean Validation constraints?
public record CreateUserRequest(
@NotBlank String name,
@Email String email
) {}
- A) @Valid or @Validated on the @RequestBody parameter plus constraints on the DTO
- B) @Transactional on the controller method
- C) @EnableScheduling on the application class
- D) @CrossOrigin alone on the controller
Answer & explanation
Correct answer: A
Spring MVC triggers Bean Validation when @Valid or @Validated is present on the @RequestBody argument and the object contains constraint annotations. Failures become MethodArgumentNotValidException handled by exception handlers or default problem responses.
Why the other options are wrong:
- B) Transactions do not perform MVC request validation.
- C) Scheduling is unrelated to validation.
- D) CORS controls cross-origin access, not validation.
Memory sentence: "@Valid on @RequestBody activates Bean Validation on the DTO."
Study: Book chapter
Question 34
A controller advice class should handle validation failures globally and return a consistent JSON error structure. Which annotation is appropriate on that class?
- A) @RepositoryAdvice
- B) @ControllerAdvice
- C) @ConfigurationProperties
- D) @ImportResource
Answer & explanation
Correct answer: B
@ControllerAdvice is a specialization of @Component that allows @ExceptionHandler, @InitBinder, and @ModelAttribute methods to apply across controllers. It is the standard global MVC exception handling mechanism.
Why the other options are wrong:
- A) @RepositoryAdvice is not a standard Spring MVC annotation.
- C) @ConfigurationProperties binds config values.
- D) @ImportResource loads XML bean definitions.
Memory sentence: "Global MVC exception handling belongs in @ControllerAdvice."
Study: Book chapter
Question 35
An API must return 201 Created with a Location header pointing to the new resource.
Which combination best expresses HTTP 201 semantics for a created resource in Spring MVC?
- A) @ResponseStatus(HttpStatus.CREATED) and returning ResponseEntity with Location header
- B) @GetMapping and status 200 always
- C) @Deprecated on the controller class
- D) Manual thread sleep then 500 response
Answer & explanation
Correct answer: A
ResponseEntity or @ResponseStatus(HttpStatus.CREATED) communicates 201. ResponseEntity is ideal when you also set Location and body headers explicitly for REST create operations.
Why the other options are wrong:
- B) GET with 200 is incorrect for resource creation.
- C) @Deprecated has no HTTP semantics.
- D) Artificial delay and server error are wrong behavior.
Memory sentence: "Use 201 CREATED and Location header when creating resources."
Study: Book chapter
Question 36
What does @RequestParam(defaultValue = "10") do when query parameter page is absent?
- A) Throws MissingServletRequestParameterException immediately
- B) Binds page to the string value 10 for the method parameter
- C) Redirects the client to /error
- D) Ignores the parameter and leaves it null for int primitives
Answer & explanation
Correct answer: B
defaultValue supplies a fallback when the request parameter is missing. For String parameters this works directly; for optional types it prevents absence errors while preserving explicit values when provided.
Why the other options are wrong:
- A) Missing parameter exceptions occur when required=true and no default exists.
- C) No automatic redirect occurs.
- D) Primitive int cannot be null; defaultValue avoids absence issues.
Memory sentence: "@RequestParam defaultValue applies when the query parameter is missing."
Study: Book chapter
Question 37
A service layer uses Spring Data JPA repositories. Developers are unsure where transaction boundaries should live.
Where should @Transactional boundaries most commonly be placed in a layered Spring application using JPA?
@Service
public class OrderService {
@Transactional
public void placeOrder(OrderRequest request) {
orderRepository.save(toEntity(request));
}
}
- A) On every entity getter method
- B) Only on REST controller methods always
- C) On service-layer methods that coordinate repository operations and business rules
- D) On the main method only
Answer & explanation
Correct answer: C
Transactional boundaries belong at the service layer where business operations coordinate multiple repository calls and enforce atomicity. Controllers should stay thin; entities should not own transaction demarcation.
Why the other options are wrong:
- A) Entity methods are persistence model details, not transaction orchestration points.
- B) Controllers may be transactional in rare cases but it is not the primary design.
- D) main is outside the request/service transaction model.
Memory sentence: "Put @Transactional on service methods that orchestrate data changes."
Study: Book chapter
Question 38
What does Spring Data JPA derive from a method named findByEmailAndActiveTrue?
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByEmailAndActiveTrue(String email);
}
- A) A stored procedure call named sp_findByEmailAndActiveTrue
- B) A native SQL script in schema.sql automatically
- C) A query selecting entities where email equals the parameter and active is true
- D) Nothing; method names are ignored by Spring Data
Answer & explanation
Correct answer: C
Spring Data JPA parses method names against the domain model property paths to generate queries. findByEmailAndActiveTrue maps to WHERE email = ?1 AND active = true for the entity managed by the repository.
Why the other options are wrong:
- A) Procedure execution requires @Procedure and explicit configuration.
- B) schema.sql initializes schema; it does not define derived query methods.
- D) Derived query methods are a core Spring Data feature.
Memory sentence: "Derived query method names encode property conditions after By."
Study: Book chapter
Question 39
A read-only report endpoint calls a service that queries repositories. The team wants to avoid accidental flush of dirty entities and optimize read paths.
Which @Transactional attribute is appropriate for a read-only query service method?
- A) readOnly = true
- B) propagation = REQUIRES_NEW always for reads
- C) rollbackFor = Exception on every read
- D) timeout = -1 only
Answer & explanation
Correct answer: A
readOnly=true hints the transaction is read-only, enabling optimizations and reducing risk of unintended state changes in some providers. It is the standard choice for query-only service methods.
Why the other options are wrong:
- B) REQUIRES_NEW creates a new transaction; it is not the default read optimization.
- C) rollbackFor configures write failure behavior, not read semantics.
- D) timeout alone does not mark a transaction read-only.
Memory sentence: "Use @Transactional(readOnly = true) for query-only service methods."
Study: Book chapter
Question 40
A method annotated @Transactional calls another @Transactional method in the same class. What happens to transaction advice on the internal call?
@Service
public class TransferService {
@Transactional
public void transfer() {
debit();
credit();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void debit() { accountRepository.debit(); }
}
- A) REQUIRES_NEW always starts a new transaction because the annotation is present
- B) Spring AOP proxy is bypassed on self-invocation, so debit runs without the expected new transaction boundary
- C) Both methods automatically run without any transaction
- D) Spring converts the call into a JMS message
Answer & explanation
Correct answer: B
@Transactional is applied via Spring AOP proxies. A direct this.debit() call inside the same target object bypasses the proxy, so nested transactional settings like REQUIRES_NEW do not take effect unless you refactor to call through the proxy or inject self interface.
Why the other options are wrong:
- A) Annotation presence is not enough without proxy interception.
- C) The external transfer call can still be transactional via proxy.
- D) Transaction demarcation is unrelated to messaging conversion.
Memory sentence: "Self-invocation skips the proxy, so @Transactional may not apply internally."
Study: Book chapter
Question 41
Which JPA annotation marks a field as the primary key with database-generated values in most relational databases?
- A) @Column(unique = true) only
- B) @GeneratedValue with @Id
- C) @Transient
- D) @Embeddable only
Answer & explanation
Correct answer: B
@Id designates the primary key and @GeneratedValue configures identity, sequence, or table generation strategies. Together they define surrogate keys common in Spring Data JPA entities.
Why the other options are wrong:
- A) Unique column constraint does not define primary key generation.
- C) @Transient excludes a field from persistence.
- D) @Embeddable composes value types, not primary key identity by itself.
Memory sentence: "@Id plus @GeneratedValue defines an auto-generated primary key."
Study: Book chapter
Question 42
An Order entity has a lazy @OneToMany collection. A REST controller returns the Order entity directly and clients see LazyInitializationException.
What is the root cause and a proper architectural fix?
- A) Jackson cannot serialize integers; switch to XML
- B) Lazy collection was accessed outside an open persistence context; map to a DTO inside a transactional read or use fetch join where appropriate
- C) Remove @Entity annotation from Order
- D) Disable all transactions globally
Answer & explanation
Correct answer: B
Lazy associations load only inside a Session. Serializing entity graphs in the web layer often occurs after the transaction ends, triggering LazyInitializationException. DTO projection or fetch strategy within the service transaction fixes the boundary issue.
Why the other options are wrong:
- A) The failure is lazy loading timing, not integer serialization.
- C) Removing @Entity breaks persistence mapping entirely.
- D) Transactions are required; the issue is session boundary and API design.
Memory sentence: "Do not expose lazy JPA graphs in the web layer; use DTOs or fetch within the transaction."
Study: Book chapter
Question 43
What is the default transaction propagation when @Transactional has no propagation attribute?
@Transactional // propagation = Propagation.REQUIRED by default
public void updateAccount() { accountRepository.save(changes); }
- A) REQUIRED
- B) NOT_SUPPORTED
- C) NEVER
- D) MANDATORY
Answer & explanation
Correct answer: A
Propagation REQUIRED joins an existing transaction or creates a new one if none exists. It is the default and the behavior developers encounter unless they explicitly choose REQUIRES_NEW, SUPPORTS, or other modes.
Why the other options are wrong:
- B) NOT_SUPPORTED suspends transactions; it is not the default.
- C) NEVER forbids transactional context; not default.
- D) MANDATORY requires an existing transaction; not default.
Memory sentence: "Default propagation is REQUIRED: join or create."
Study: Book chapter
Question 44
A bulk update deletes inactive users with a single JPQL statement. Repository users expect automatic persistence context synchronization.
Which Spring Data JPA feature executes a JPQL UPDATE/DELETE statement without loading entities into memory?
- A) @Modifying query method with @Query JPQL update/delete
- B) findAll then delete in a for-loop only
- C) @Entity graph on a finder method
- D) @Version field alone
Answer & explanation
Correct answer: A
@Modifying on a @Query method executes bulk UPDATE or DELETE JPQL/SQL directly. Developers must also consider clearAutomatically and transactional boundaries because the persistence context may be stale after bulk operations.
Why the other options are wrong:
- B) Loading every entity only to delete one by one defeats the purpose of bulk operations and scales poorly.
- C) Entity graphs control fetch graphs for queries, not bulk update/delete execution.
- D) @Version enables optimistic locking on entities but does not execute bulk JPQL statements.
Memory sentence: "@Modifying @Query runs bulk updates/deletes outside entity-by-entity loading."
Study: Book chapter
Question 45
A stateless REST API must authenticate bearer tokens on every request without server-side HTTP sessions.
Which Spring Security configuration direction best matches a stateless JWT-backed API?
http.sessionManagement(s -> s.sessionCreationPolicy(STATELESS));
http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
- A) formLogin with default success URL /home
- B) rememberMe always enabled with persistent tokens in JDBC
- C) sessionManagement sessionCreationPolicy STATELESS plus a filter that validates tokens before UsernamePasswordAuthenticationFilter
- D) csrf enabled with HttpSession requirement for every request
Answer & explanation
Correct answer: C
Stateless APIs disable session creation for authentication state and rely on per-request token validation in the security filter chain. A custom OncePerRequestFilter or resource-server support validates credentials and populates the SecurityContext each request.
Why the other options are wrong:
- A) Form login is browser-session oriented, not typical for bearer token APIs.
- B) Remember-me still centers on session/cookie patterns unsuitable for pure stateless JWT APIs.
- D) CSRF protection matters for cookie sessions; stateless bearer setups commonly disable CSRF for pure APIs while still protecting session-based apps.
Memory sentence: "Stateless APIs use STATELESS sessions and per-request token authentication filters."
Study: Book chapter
Question 46
In Spring Security filter chain architecture, where is the SecurityContext typically stored for a request?
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
- A) Only in the database user table
- B) Inside the JPA EntityManager permanently
- C) In application.properties
- D) In SecurityContextHolder, often backed by ThreadLocal for servlet requests
Answer & explanation
Correct answer: D
SecurityContextHolder holds the authenticated principal and authorities for the current thread during request processing. Servlet filters populate and clear it around the chain to avoid leaking credentials across requests.
Why the other options are wrong:
- A) User tables store credentials or accounts, not per-request context.
- B) EntityManager is persistence infrastructure, not security context storage.
- C) Properties files do not hold runtime authentication state.
Memory sentence: "SecurityContextHolder carries authentication for the current request thread."
Study: Book chapter
Question 47
Administrators need /admin/** endpoints restricted to ROLE_ADMIN while other authenticated users may access /app/**.
Which expression on an authorizeHttpRequests rule grants access only to users with ROLE_ADMIN?
- A) permitAll() for /admin/**
- B) hasRole("ADMIN") for /admin/** requests
- C) anonymous() for /admin/**
- D) csrf().disable() only
Answer & explanation
Correct answer: B
hasRole("ADMIN") checks for ROLE_ADMIN authority, following Spring Security role naming convention. Method and HTTP authorization rules use such expressions to enforce role-based access control.
Why the other options are wrong:
- A) permitAll allows everyone including anonymous users.
- C) anonymous restricts to unauthenticated users, opposite of admin-only access.
- D) CSRF settings do not define authorization roles.
Memory sentence: "hasRole("ADMIN") maps to authority ROLE_ADMIN."
Study: Book chapter
Question 48
What does PasswordEncoder do in Spring Security authentication architecture?
- A) Maps URLs to controller methods
- B) Hashes and verifies passwords without storing plain text
- C) Generates JWT signing keys automatically for all apps
- D) Replaces the need for HTTPS
Answer & explanation
Correct answer: B
PasswordEncoder provides one-way encoding and matches raw passwords to stored hashes during authentication. DelegatingPasswordEncoder supports multiple algorithms and is the recommended approach in modern Spring Security.
Why the other options are wrong:
- A) URL mapping is MVC concern.
- C) JWT keys are configured separately; PasswordEncoder handles password hashing.
- D) Transport security still requires TLS.
Memory sentence: "Never store plain passwords; verify with PasswordEncoder.matches."
Study: Book chapter
Question 49
A browser-based app uses cookie sessions and form login. Developers expose a REST POST endpoint consumed by the same origin.
Why is CSRF protection relevant in this application?
- A) Because browsers may automatically send session cookies on cross-site requests, allowing forged state-changing operations unless CSRF tokens are validated
- B) Because JWT signatures expire after one second by default
- C) Because @Transactional requires CSRF tokens
- D) Because CSRF replaces password hashing
Answer & explanation
Correct answer: A
Session cookie authentication is vulnerable to cross-site request forgery when browsers attach cookies automatically. Spring Security CSRF tokens verify intentional client requests for state-changing operations in session-based apps.
Why the other options are wrong:
- B) JWT expiry is unrelated to CSRF for cookie-session apps.
- C) Transactions are persistence concern.
- D) CSRF does not replace credential storage protections.
Memory sentence: "Cookie-session apps need CSRF protection on state-changing requests."
Study: Book chapter
Question 50
Which annotation enables method-level security expressions such as @PreAuthorize("hasAuthority('INVOICE_READ')")?
- A) @EnableMethodSecurity
- B) @EnableWebMvc
- C) @EnableJpaRepositories
- D) @EnableScheduling
Answer & explanation
Correct answer: A
@EnableMethodSecurity activates method interception for @PreAuthorize, @PostAuthorize, @Secured, and related annotations using Spring AOP around secured beans.
Why the other options are wrong:
- B) @EnableWebMvc configures MVC infrastructure, not authorization on service methods.
- C) @EnableJpaRepositories scans repository interfaces only.
- D) @EnableScheduling enables scheduled task execution, unrelated to method security.
Memory sentence: "@EnableMethodSecurity turns on @PreAuthorize and related checks."
Study: Book chapter
Question 51
Unit tests for OrderService should isolate business logic from database and HTTP concerns.
What is the primary goal of a Spring service unit test using Mockito?
- A) Boot the full servlet container and hit real endpoints
- B) Test the service class in isolation by mocking collaborators with @ExtendWith(MockitoExtension.class) or @Mock/@InjectMocks
- C) Require @SpringBootTest for every service test
- D) Load production PostgreSQL for each test method
Answer & explanation
Correct answer: B
Unit tests focus on one class behavior by substituting dependencies with mocks. Mockito integrates with JUnit 5 to verify interactions and return controlled responses without starting Spring unless necessary.
Why the other options are wrong:
- A) Full container tests are integration tests, not unit tests.
- C) @SpringBootTest is heavier than needed for pure unit tests.
- D) Production databases make tests slow and brittle.
Memory sentence: "Unit-test services with mocks; reserve Spring context for integration tests."
Study: Book chapter
Question 52
Which annotation starts the full Spring application context including auto-configuration for an integration test?
- A) @WebMvcTest
- B) @DataJpaTest
- C) @MockBean only without context
- D) @SpringBootTest
Answer & explanation
Correct answer: D
@SpringBootTest loads the complete application context (or a configured slice via attributes) and is used for integration tests that need real wiring across layers, often with TestRestTemplate or @Autowired collaborators.
Why the other options are wrong:
- A) @WebMvcTest loads MVC slice only.
- B) @DataJpaTest loads JPA slice with in-memory DB typically.
- C) @MockBean requires a Spring test context; it does not bootstrap alone.
Memory sentence: "@SpringBootTest = full integration context bootstrap."
Study: Book chapter
Question 53
A controller test should verify JSON response status and body without starting a real server on a random port.
Which test slice is appropriate for testing a @RestController with MockMvc?
- A) @WebMvcTest(controllers = InvoiceController.class)
- B) @SpringBootTest webEnvironment RANDOM_PORT only
- C) @JdbcTest
- D) @JsonTest alone for entire MVC flow
Answer & explanation
Correct answer: A
@WebMvcTest auto-configures Spring MVC infrastructure and MockMvc while limiting the context to web-layer beans, letting you test controller mappings, status codes, and JSON with lightweight setup.
Why the other options are wrong:
- B) RANDOM_PORT works but is heavier than necessary for controller slice tests.
- C) @JdbcTest targets JDBC components only.
- D) @JsonTest focuses on JSON serializers, not full controller request mapping.
Memory sentence: "@WebMvcTest plus MockMvc tests controllers without full Boot startup."
Study: Book chapter
Question 54
In a @WebMvcTest, a service dependency must be replaced with a mock implementation. Which annotation registers the mock in the test context?
- A) @MockBean
- B) @Mock only without Spring context
- C) @Entity
- D) @Profile
Answer & explanation
Correct answer: A
@MockBean tells Spring Test to add a Mockito mock as a bean in the application context, replacing or supplementing existing beans. This is required when the controller under test autowires collaborators during @WebMvcTest.
Why the other options are wrong:
- B) @Mock alone does not register a bean in the Spring test ApplicationContext.
- C) @Entity is a JPA mapping annotation, not a test mock registration mechanism.
- D) @Profile selects beans by environment; it does not create mock implementations.
Memory sentence: "Use @MockBean to inject Mockito mocks into Spring test contexts."
Study: Book chapter
Question 55
Repository integration tests should run against an in-memory database with only JPA components loaded.
Which Spring Boot test annotation is designed for JPA repository slice tests?
- A) @DataJpaTest
- B) @WebMvcTest
- C) @SpringBootConfiguration only
- D) @ControllerAdvice
Answer & explanation
Correct answer: A
@DataJpaTest configures JPA-related beans, typically with an embedded database, and is ideal for testing repository query methods without loading the entire application.
Why the other options are wrong:
- B) @WebMvcTest limits the context to the web layer, not repositories.
- C) @SpringBootConfiguration marks a config class but does not define a repository test slice.
- D) @ControllerAdvice is for MVC exception handling, not repository integration tests.
Memory sentence: "@DataJpaTest loads a minimal JPA test slice with embedded DB."
Study: Book chapter
Question 56
What does @Transactional on a Spring Boot integration test method typically do to database changes made during the test?
- A) Commits them permanently to production schema
- B) Rolls back after the test by default, keeping tests isolated
- C) Disables the database entirely
- D) Runs the test without any DataSource
Answer & explanation
Correct answer: B
Spring Test Framework transactional test support rolls back transactions after each test method by default, preventing test data pollution while still exercising real transactional code paths.
Why the other options are wrong:
- A) Default test transactions roll back, not commit to production schema.
- C) The DataSource remains active; transactional tests use it within a rolled-back transaction.
- D) Integration tests with @Transactional still require a configured DataSource.
Memory sentence: "Test @Transactional methods roll back by default for isolation."
Study: Book chapter
Question 57
A logging aspect should run before every public method in the service package, but only methods on Spring beans.
Why must the target service be a Spring-managed bean for Spring AOP advice to apply?
- A) Because advice is applied via proxies or subclass weaving around beans created by the container
- B) Because Java does not support methods on classes
- C) Because only @Entity classes can be proxied
- D) Because aspects compile into application.properties
Answer & explanation
Correct answer: A
Spring AOP wraps beans with JDK dynamic proxies or CGLIB subclasses so interceptors can run around join points. Objects created with new outside the container are not proxied and therefore bypass advice.
Why the other options are wrong:
- B) Plain Java methods exist; the issue is proxy registration.
- C) Entities are unrelated to AOP proxy requirements.
- D) Aspects are beans/advice definitions, not property files.
Memory sentence: "Spring AOP applies to container-managed beans through proxies."
Study: Book chapter
Question 58
SRE needs a custom counter for failed payment attempts exposed through Actuator and compatible with Prometheus scraping.
Which Spring Boot approach registers a custom application metric collected by Micrometer and exposed via Actuator?
@Service
public class PaymentService {
private final Counter failedPayments;
public PaymentService(MeterRegistry registry) {
this.failedPayments = registry.counter("payments.failed");
}
}
- A) Declare a Counter through MeterRegistry and increment it in business code
- B) Add @Entity on the service class so JPA tracks metrics automatically
- C) Store metric values only in a static HashMap without MeterRegistry
- D) Disable management.endpoints.web.exposure to create custom metrics
Answer & explanation
Correct answer: A
Spring Boot Actuator integrates Micrometer so beans can register counters, timers, and gauges through MeterRegistry. Those meters appear on /actuator/metrics and can be exported to Prometheus when the registry and exporter are configured.
Why the other options are wrong:
- B) JPA entity mapping has no relationship to application metrics registration.
- C) Ad-hoc static maps are not integrated with Actuator endpoints or standardized metric registries.
- D) Hiding Actuator endpoints prevents observability rather than enabling custom metrics.
Memory sentence: "Register custom metrics with MeterRegistry; Actuator exposes them via Micrometer."
Study: Book chapter
Question 59
When an order is placed, multiple modules must react: send email, update inventory, and audit. The order service should stay focused on persistence.
Which Spring feature decouples side effects by notifying listeners when OrderCreatedEvent is published?
publisher.publishEvent(new OrderCreatedEvent(orderId));
@EventListener
void onOrderCreated(OrderCreatedEvent event) { emailService.sendReceipt(event); }
- A) Changing all logic into one giant @Transactional method with switch cases
- B) Using static singleton event bus outside Spring
- C) ApplicationEventPublisher and @EventListener methods
- D) Disabling the ApplicationContext
Answer & explanation
Correct answer: C
Spring application events let a publisher emit domain events and listeners react asynchronously or synchronously via @EventListener. This keeps the core workflow cohesive while extensibility lives in listeners.
Why the other options are wrong:
- A) A monolithic method tightly couples side effects and hurts maintainability.
- B) A static bus bypasses Spring lifecycle and testability benefits.
- D) Disabling the context removes the event infrastructure entirely.
Memory sentence: "Publish domain events; handle side effects with @EventListener."
Study: Book chapter
Question 60
Which configuration enables Spring @Async method execution using a task executor?
@Configuration
@EnableAsync
class AsyncConfig { }
- A) @EnableWebMvc only
- B) @EntityScan only
- C) @RefreshScope only
- D) @EnableAsync on a @Configuration class
Answer & explanation
Correct answer: D
@EnableAsync activates processing of @Async methods through Spring AOP and TaskExecutor infrastructure. Without it, @Async methods run synchronously on the caller thread.
Why the other options are wrong:
- A) @EnableWebMvc configures web MVC, not asynchronous method execution.
- B) @EntityScan limits JPA entity scanning to specified packages.
- C) @RefreshScope is a Spring Cloud scope for refreshed configuration beans.
Memory sentence: "@EnableAsync switches on asynchronous @Async method handling."
Study: Book chapter
End of Mock Full 01 — Spring Professional (60 Questions)