Skip to main content

Mock Full 04 — 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:

  1. Pick an option for each question, then use Check answer to reveal the explanation and score.
  2. Use Back and Next to move through the set; you can change your selection until you check.
  3. 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 payment service has two NotificationSender implementations on the classpath: EmailNotificationSender and SmsNotificationSender. Both are annotated with @Component.

The BillingService must inject EmailNotificationSender specifically. Which approach is the Spring-idiomatic way to resolve the ambiguity?

@Service
public class BillingService {
// inject EmailNotificationSender only
}
  • A) Annotate EmailNotificationSender with @Primary and remove SmsNotificationSender from the classpath
  • B) Use @Qualifier("emailNotificationSender") on the injection point or field parameter
  • C) Rename BillingService so component scanning skips the conflict
  • D) Declare both senders as static fields inside BillingService
Answer & explanation

Correct answer: B

When multiple beans implement the same type, Spring raises a NoUniqueBeanDefinitionException unless you disambiguate. @Qualifier matches a specific bean by name or custom qualifier value. @Primary is an alternative but changes the default for all injection points, which is broader than needed when only one consumer requires a specific implementation.

Why the other options are wrong:

  • A) @Primary works globally but is heavy-handed when only one injection point needs a specific bean.
  • C) Class renaming has no effect on bean type matching or ambiguity resolution.
  • D) Static fields bypass the IoC container and break dependency injection entirely.

Memory sentence: "Multiple same-type beans → disambiguate with @Qualifier or @Primary."

Study: Book chapter

Question 2

A security review flags field injection in a new AccountService because required collaborators can be omitted without compile-time detection.

Which injection style does Spring recommend for mandatory, immutable dependencies?

@Service
public class AccountService {
private final AuditPort auditPort;
// preferred wiring here
}
  • A) Setter injection with @Autowired(required = false)
  • B) Field injection with @Resource
  • C) Lookup-method injection for every dependency
  • D) Constructor injection with final fields
Answer & explanation

Correct answer: D

Constructor injection makes dependencies explicit, supports immutability via final fields, and allows frameworks to detect missing required collaborators at construction time. Since Spring 4.3, a single constructor does not even need @Autowired. Field injection hides dependencies and complicates unit testing.

Why the other options are wrong:

  • A) Optional setter injection is for non-mandatory collaborators, not required immutable ones.
  • B) Field injection is discouraged because dependencies are not visible in the constructor signature.
  • C) Lookup methods solve scoped-proxy or prototype-in-singleton cases, not ordinary mandatory wiring.

Memory sentence: "Mandatory deps → constructor injection with final fields."

Study: Book chapter

Question 3

Two CacheManager beans exist: redisCacheManager and caffeineCacheManager. A single @Autowired CacheManager field in ReportFacade should default to redisCacheManager without changing call sites. What is the best declaration?

  • A) Mark redisCacheManager with @Primary
  • B) Add @Lazy to the ReportFacade field
  • C) Use @Scope("prototype") on redisCacheManager
  • D) Annotate ReportFacade with @DependsOn("redisCacheManager")
Answer & explanation

Correct answer: A

@Primary marks one bean as the preferred candidate when autowiring by type alone. Consumers that need caffeineCacheManager can still override the default with @Qualifier. @DependsOn controls startup order, not selection among type-compatible beans.

Why the other options are wrong:

  • B) @Lazy delays creation but does not choose among multiple CacheManager beans.
  • C) Prototype scope changes instance cardinality, not autowire preference.
  • D) @DependsOn ensures creation order; it does not resolve type ambiguity.

Memory sentence: "@Primary = default bean when multiple candidates share a type."

Study: Book chapter

Question 4

A library exposes a FactoryBean that builds encrypted PropertySource objects. Developers wonder whether calling getBean("securePropertySource") returns the FactoryBean itself or the product.

What does context.getBean("securePropertySource") return when SecurePropertySourceFactory implements FactoryBean<PropertySource<?>>?

public class SecurePropertySourceFactory implements FactoryBean<PropertySource<?>> {
@Override
public PropertySource<?> getObject() { return new EncryptedPropertySource(); }
@Override
public Class<?> getObjectType() { return PropertySource.class; }
}
  • A) Always the FactoryBean instance itself
  • B) A new FactoryBean on every getBean call regardless of scope
  • C) The object produced by getObject(), namely the PropertySource
  • D) Nothing unless the bean name is prefixed with &
Answer & explanation

Correct answer: C

For a FactoryBean registration, the container normally exposes the product of getObject() as the bean. Prefixed names with & retrieve the FactoryBean itself. This distinction matters when diagnosing what type is actually registered in the context.

Why the other options are wrong:

  • A) The FactoryBean instance is retrieved only with the &name syntax, not the plain bean name.
  • B) FactoryBean products follow the declared bean scope; getBean does not always create new FactoryBean instances.
  • D) Plain getBean(name) returns the product; &name returns the FactoryBean.

Memory sentence: "FactoryBean: plain name → product; &name → factory itself."

Study: Book chapter

Question 5

A bean needs the maximum thread pool size from configuration. The property is app.pool.max-size=16. Which @Value expression reads it correctly?

@Service
public class WorkerPoolConfigurer {
// choose correct injection
}
  • A) @Value("app.pool.max-size")
  • B) @Value("${app.pool.max-size}")
  • C) @Value("#{app.pool.max-size}")
  • D) @Value("$app.pool.max-size")
Answer & explanation

Correct answer: B

Property placeholders use the ${property.key} syntax so Spring's PropertySourcesPlaceholderConfigurer resolves external configuration. Plain strings without placeholder braces are injected literally. SpEL uses a different hash-brace form and is not the standard placeholder syntax for environment keys.

Why the other options are wrong:

  • A) Without ${}, the literal text "app.pool.max-size" is injected, not the configured value.
  • C) SpEL could read properties via @environment, but #{app.pool.max-size} is not the placeholder form for keys with hyphens.
  • D) $ without braces is not valid Spring property placeholder syntax.

Memory sentence: "External properties in @Value use ${property.key} syntax."

Study: Book chapter

Question 6

OrderService and InventoryService are singletons. OrderService's constructor requires InventoryService, and InventoryService's constructor requires OrderService.

What happens during ApplicationContext refresh?

  • A) Spring creates lightweight proxies first, then replaces them with real instances
  • B) One bean is automatically marked @Lazy to break the cycle
  • C) Spring injects null into one constructor and fixes it later with setters
  • D) Context refresh fails because constructor injection cannot resolve the circular dependency
Answer & explanation

Correct answer: D

Constructor injection cycles cannot be satisfied because neither bean can be fully constructed before the other. Spring may resolve some field/setter cycles with early references, but mutual constructor dependencies cause BeanCurrentlyInCreationException during startup.

Why the other options are wrong:

  • A) Proxy-based cycle breaking applies to some setter/field cases, not mutual constructor dependencies.
  • B) Spring does not silently pick one side as @Lazy unless you declare @Lazy explicitly.
  • C) Constructor injection does not fall back to null collaborators for required dependencies.

Memory sentence: "Constructor cycles fail at startup; break them with @Lazy or redesign."

Study: Book chapter

Question 7

A CLI utility bootstraps a standalone AnnotationConfigApplicationContext and must retrieve a bean programmatically after refresh. Which call is correct?

AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
// need ExportJob bean
  • A) ctx.getBean(ExportJob.class)
  • B) ExportJob.createFromSpring()
  • C) ctx.findComponent(ExportJob.class)
  • D) new ExportJob(ctx)
Answer & explanation

Correct answer: A

ApplicationContext.getBean(Class) is the standard programmatic lookup once the container is refreshed. Spring-managed objects should not be constructed with new when you need container-managed instances with injected collaborators.

Why the other options are wrong:

  • B) Spring does not generate createFromSpring factory methods on user classes.
  • C) findComponent is not part of the ApplicationContext API.
  • D) Manual construction bypasses dependency injection and lifecycle management.

Memory sentence: "Programmatic lookup after refresh: context.getBean(Type.class)."

Study: Book chapter

Question 8

CatalogService depends on a slow RemotePricingClient. The team wants CatalogService to start quickly and defer pricing client creation until first use.

Which declaration achieves lazy initialization of the dependency?

@Service
public class CatalogService {
private final PricingClient pricingClient;
}
  • A) Annotate CatalogService with @Scope("prototype")
  • B) Mark RemotePricingClient with @Repository only
  • C) Annotate the PricingClient injection point or bean with @Lazy
  • D) Remove @Component from RemotePricingClient
Answer & explanation

Correct answer: C

@Lazy on a dependency or bean definition tells Spring to inject a proxy and create the target bean only when first accessed. This reduces startup cost for expensive collaborators without removing the bean from the container.

Why the other options are wrong:

  • A) Prototype scope on CatalogService changes its own cardinality, not dependency laziness.
  • B) Stereotype choice does not imply lazy initialization.
  • D) Removing the stereotype prevents wiring altogether rather than deferring creation.

Memory sentence: "@Lazy defers bean creation until first access through a proxy."

Study: Book chapter

Question 9

A class com.example.billing.InvoiceExporter is annotated with @Component and no explicit bean name. What is the default bean name?

  • A) com.example.billing.InvoiceExporter
  • B) invoiceExporter
  • C) InvoiceExporter
  • D) billingInvoiceExporter
Answer & explanation

Correct answer: B

For annotated classes, the default bean name is the decapitalized simple class name unless an explicit value is provided in @Component("name"). Fully qualified class names are not used as default bean names.

Why the other options are wrong:

  • A) Fully qualified names are not the default for stereotype-annotated classes.
  • C) The first letter is lowercased per JavaBeans convention, yielding invoiceExporter.
  • D) Package segments are not prepended to the default bean name.

Memory sentence: "Default @Component name = decapitalized simple class name."

Study: Book chapter

Question 10

ShipmentTracker depends on the TrackingPort interface. Exactly one implementation, FedExTrackingAdapter, is registered in the context.

What happens when ShipmentTracker declares @Autowired TrackingPort trackingPort?

@Component
public class FedExTrackingAdapter implements TrackingPort { }

@Service
public class ShipmentTracker {
@Autowired
private TrackingPort trackingPort;
}
  • A) Injection fails because interfaces cannot be autowired
  • B) Spring requires @Qualifier whenever the field type is an interface
  • C) A JDK proxy is always created instead of the concrete class
  • D) FedExTrackingAdapter is injected because it is the only matching bean
Answer & explanation

Correct answer: D

Autowired by type succeeds when exactly one bean matches the declared dependency type. Interfaces are first-class injection targets. Ambiguity appears only when multiple implementations exist without @Primary or @Qualifier.

Why the other options are wrong:

  • A) Interface-typed injection is standard Spring practice.
  • B) @Qualifier is required only when multiple candidates exist.
  • C) Spring injects the concrete managed bean unless explicit proxying is configured for other reasons.

Memory sentence: "Single matching bean → autowire by type works, even for interfaces."

Study: Book chapter

Question 11

Two @Bean methods in the same @Configuration class call each other. Why should the class be processed as a CGLIB-enhanced configuration proxy?

@Configuration
public class PricingConfig {
@Bean
public DiscountPolicy discountPolicy() {
return new DiscountPolicy(baseRate());
}
@Bean
public RateTable baseRate() {
return new RateTable();
}
}
  • A) To allow @Profile evaluation at runtime only
  • B) So @Bean methods can be private
  • C) So inter-bean method calls route through the container and return singletons
  • D) To disable component scanning for the configuration package
Answer & explanation

Correct answer: C

Full @Configuration classes are proxied so @Bean method invocations go through the container rather than plain Java calls. Without that enhancement, calling baseRate() directly from discountPolicy() would create a new RateTable instead of reusing the singleton bean.

Why the other options are wrong:

  • A) Profile processing is unrelated to CGLIB enhancement of @Configuration.
  • B) @Bean methods should be public; proxying does not exist to support private factory methods.
  • D) Configuration proxying does not turn off component scanning.

Memory sentence: "@Configuration proxy ensures @Bean method calls reuse container-managed beans."

Study: Book chapter

Question 12

A team maintains separate datasource beans for production and local development.

Which approach activates only the embedded H2 datasource bean during local runs?

@Bean
public DataSource dataSource() { /* cloud */ }

@Bean
public DataSource dataSource() { /* h2 */ }
  • A) Annotate the H2 @Bean method with @Profile("local") and run with spring.profiles.active=local
  • B) Place both beans in the same @Configuration without profiles and rely on @Primary
  • C) Use @Scope("prototype") on the H2 bean
  • D) Annotate the main application class with @ComponentScan(basePackageClasses = DataSource.class)
Answer & explanation

Correct answer: A

@Profile conditionally registers bean definitions based on active profiles. Combining @Profile("local") with spring.profiles.active=local ensures only the intended datasource configuration participates in the context for that environment.

Why the other options are wrong:

  • B) Two @Bean methods with the same method name in one class is invalid Java and still lacks environment switching.
  • C) Prototype scope does not hide beans per environment.
  • D) Component scan narrowing does not provide environment-specific bean registration.

Memory sentence: "Environment-specific beans → @Profile plus active profile property."

Study: Book chapter

Question 13

In a Spring MVC web application, a DashboardFilter bean should be created once per HTTP request. Which scope is appropriate?

@Component
@Scope("???")
public class DashboardFilter { }
  • A) singleton
  • B) request
  • C) prototype
  • D) application
Answer & explanation

Correct answer: B

Request scope creates one bean instance per HTTP request in a web-aware ApplicationContext. Singleton would share state across users, while prototype would create a new instance on every injection point resolution, not per request boundary.

Why the other options are wrong:

  • A) Singleton shares one instance for the entire application lifetime.
  • C) Prototype creates a new instance per getBean or injection resolution, not aligned to HTTP request lifecycle.
  • D) "application" is the ServletContext scope name in Spring web contexts, not per-request isolation.

Memory sentence: "Per HTTP request state → request scope in a web context."

Study: Book chapter

Question 14

application.yml contains nested mail settings, but MailSettings fields remain null at runtime.

Which pair of annotations binds prefix app.mail to a type-safe configuration properties class?

app:
mail:
host: smtp.example.com
port: 587
  • A) @Value on each field only
  • B) @Entity and @Table
  • C) @RequestMapping on the properties class
  • D) @ConfigurationProperties(prefix = "app.mail") with @EnableConfigurationProperties or @Component
Answer & explanation

Correct answer: D

@ConfigurationProperties binds hierarchical external configuration to a POJO using the declared prefix. The class must be registered via @EnableConfigurationProperties, @ConfigurationPropertiesScan, or as a @Component. @Value handles individual keys but not structured hierarchical binding as cleanly.

Why the other options are wrong:

  • A) Repeated @Value works for individual keys but is not the type-safe hierarchical binding pattern asked for.
  • B) JPA entity annotations map to database tables, not configuration properties.
  • C) Web mapping annotations do not bind environment configuration to fields.

Memory sentence: "Structured config → @ConfigurationProperties(prefix = "app.mail")."

Study: Book chapter

Question 15

A property exists in both application.properties and a command-line argument --app.feature.enabled=true. Which value wins with default Spring Boot property precedence?

  • A) The command-line argument value
  • B) The application.properties value
  • C) The first value discovered during classpath scanning
  • D) Neither; startup fails on duplicate keys
Answer & explanation

Correct answer: A

Spring Boot orders property sources so command-line arguments override application.properties and application.yml defaults. This allows runtime overrides without rebuilding artifacts.

Why the other options are wrong:

  • B) Files in the jar are lower precedence than command-line arguments.
  • C) Precedence is defined by Spring Boot rules, not first discovery order.
  • D) Duplicate keys are resolved by precedence rather than failing startup.

Memory sentence: "Command-line args beat application.properties in Boot precedence."

Study: Book chapter

Question 16

A custom metrics exporter should register only when management.metrics.export.enabled=true.

Which Boot condition expresses that requirement on a @Configuration class?

  • A) @ConditionalOnMissingBean(MeterRegistry.class)
  • B) @Profile("metrics") only
  • C) @ConditionalOnProperty(name = "management.metrics.export.enabled", havingValue = "true")
  • D) @Lazy on the configuration class
Answer & explanation

Correct answer: C

@ConditionalOnProperty ties bean registration to the presence and value of a configuration property. It is the idiomatic Boot mechanism for feature toggles in auto-configuration style modules.

Why the other options are wrong:

  • A) Missing-bean conditions gate on bean presence, not property values.
  • B) Profiles can separate environments but do not directly test an arbitrary property value.
  • D) @Lazy affects initialization timing, not conditional registration based on properties.

Memory sentence: "Property-gated beans → @ConditionalOnProperty with name and havingValue."

Study: Book chapter

Question 17

A singleton ReportBuilder injects a prototype TemplateEngine. How many TemplateEngine instances exist over three calls to reportBuilder.build() in the same application?

@Component
@Scope("prototype")
class TemplateEngine { }

@Service
class ReportBuilder {
@Autowired TemplateEngine engine;
void build() { engine.render(); }
}
  • A) One shared TemplateEngine for the entire application
  • B) One TemplateEngine per build() call
  • C) Zero; prototype beans cannot be injected into singletons
  • D) Three singleton TemplateEngine beans stored in a pool
Answer & explanation

Correct answer: B

Injecting a prototype into a singleton stores one prototype instance in the singleton for the lifetime of that singleton. To obtain a new prototype per operation, use ObjectProvider<TemplateEngine>, @Lookup, or scope proxies intentionally designed for per-use resolution.

Why the other options are wrong:

  • A) The injected prototype instance is fixed at singleton creation time unless you use a provider or lookup method.
  • C) Injection is allowed; the nuance is instance cardinality, not prohibition.
  • D) Prototype scope does not create a managed pool of three instances automatically.

Memory sentence: "Prototype inside singleton = one shared prototype unless you use ObjectProvider."

Study: Book chapter

Question 18

A bean uses @PostConstruct to open a socket and @PreDestroy to close it.

When does the @PreDestroy method run?

  • A) Immediately after the constructor returns
  • B) Before any @PostConstruct method in the same JVM
  • C) Only when the bean is prototype-scoped
  • D) As the ApplicationContext is shutting down or the bean is being removed from the container
Answer & explanation

Correct answer: D

@PreDestroy methods participate in the bean destruction phase when the container closes or the scoped bean ends. They are the symmetric cleanup hook to @PostConstruct initialization for managed resources.

Why the other options are wrong:

  • A) Post-construct initialization runs after construction; pre-destroy runs at shutdown.
  • B) PreDestroy is not invoked before initialization hooks.
  • C) Singleton and other scopes also receive destruction callbacks on context close.

Memory sentence: "@PreDestroy runs on context shutdown or scoped bean disposal."

Study: Book chapter

Question 19

Which statement about @SpringBootApplication is accurate?

@SpringBootApplication
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
  • A) @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan
  • B) @SpringBootApplication disables auto-configuration by default
  • C) @SpringBootApplication is required on every @RestController
  • D) @SpringBootApplication replaces the need for application.properties
Answer & explanation

Correct answer: A

@SpringBootApplication is a composed annotation that enables Java configuration, auto-configuration, and component scanning from its package downward. It is the conventional entry-point marker for Boot applications.

Why the other options are wrong:

  • B) It enables, not disables, auto-configuration via @EnableAutoConfiguration.
  • C) Controllers are discovered because of component scanning, not by placing @SpringBootApplication on each controller.
  • D) External configuration remains external; the annotation does not embed property files.

Memory sentence: "@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan."

Study: Book chapter

Question 20

A team builds a CLI batch module using spring-boot-starter but must prevent DataSourceAutoConfiguration because no database is used.

How can the application exclude that auto-configuration while keeping other Boot defaults?

@SpringBootApplication
public class BatchApplication { }
  • A) Delete spring-boot-autoconfigure.jar from the classpath
  • B) Remove @EnableAutoConfiguration from every configuration class manually
  • C) Use @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
  • D) Set spring.autoconfigure.exclude=false in properties
Answer & explanation

Correct answer: C

Spring Boot supports excluding specific auto-configuration classes via the exclude attribute on @SpringBootApplication or @EnableAutoConfiguration, or through the spring.autoconfigure.exclude property. This removes only targeted auto-config while retaining the rest.

Why the other options are wrong:

  • A) Removing the autoconfigure module disables all auto-configuration, not a surgical exclusion.
  • B) @SpringBootApplication already carries @EnableAutoConfiguration; manual removal fights the Boot model.
  • D) spring.autoconfigure.exclude expects class names to exclude, not the literal false value shown.

Memory sentence: "Exclude one auto-config → @SpringBootApplication(exclude = X.class)."

Study: Book chapter

Question 21

With spring-boot-starter-actuator on the classpath and no custom security blocking endpoints, which URL typically exposes the default health endpoint in Spring Boot 3?

  • A) /status
  • B) /actuator/health
  • C) /health/check
  • D) /management/health
Answer & explanation

Correct answer: B

Actuator web endpoints are exposed under the /actuator base path by default, with /actuator/health being the standard health endpoint. Additional endpoints require explicit exposure configuration in modern Boot defaults.

Why the other options are wrong:

  • A) /status is not the default Actuator health path.
  • C) /health/check is not the conventional Boot 3 actuator endpoint.
  • D) /management/health is not the default unless the base path is customized.

Memory sentence: "Default Actuator health URL → /actuator/health."

Study: Book chapter

Question 22

A starter should auto-configure only if Jackson ObjectMapper is present on the classpath.

Which condition should guard the auto-configuration class?

  • A) @ConditionalOnWebApplication
  • B) @ConditionalOnMissingClass("com.fasterxml.jackson.databind.ObjectMapper")
  • C) @ConditionalOnExpression("true")
  • D) @ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
Answer & explanation

Correct answer: D

@ConditionalOnClass checks for the presence of specified classes on the classpath, which is how Boot starters avoid registering Jackson-related beans when Jackson is absent. Missing-class conditions invert that logic.

Why the other options are wrong:

  • A) Web application checks do not test for Jackson presence.
  • B) OnMissingClass registers beans when the class is absent, opposite of the requirement.
  • C) A literal true expression ignores classpath requirements entirely.

Memory sentence: "Classpath present → @ConditionalOnClass; absent → @ConditionalOnMissingClass."

Study: Book chapter

Question 23

A developer adds spring-boot-devtools to a web project. What is a typical local-development behavior?

  • A) Automatic restart of the application when classpath files change
  • B) Disabling of all auto-configuration at runtime
  • C) Mandatory HTTPS on port 443
  • D) Production-ready performance tuning of the JVM
Answer & explanation

Correct answer: A

DevTools provides development-time enhancements such as automatic restart on classpath changes and LiveReload support. It is not intended for production classpath and should be marked optional in build tools.

Why the other options are wrong:

  • B) DevTools does not globally disable auto-configuration.
  • C) DevTools does not force HTTPS.
  • D) DevTools optimizes developer feedback loops, not production JVM tuning.

Memory sentence: "DevTools = faster local restart on classpath changes."

Study: Book chapter

Question 24

On startup, a service must read persisted migration flags and then execute after the context is ready.

Which callback interface runs after the ApplicationContext is fully started and receives access to raw String command-line arguments?

  • A) BeanPostProcessor
  • B) InitializingBean
  • C) CommandLineRunner
  • D) ServletContextListener only
Answer & explanation

Correct answer: C

CommandLineRunner beans execute after application startup with access to the main method args as a String array. ApplicationRunner is similar but uses ApplicationArguments. Both are common for startup tasks in Boot applications.

Why the other options are wrong:

  • A) BeanPostProcessor hooks bean initialization, not post-startup application logic.
  • B) InitializingBean runs during individual bean setup, not after the full context is ready.
  • D) ServletContextListener is a servlet API hook, not the Boot-native startup runner abstraction.

Memory sentence: "Post-startup tasks with main args → CommandLineRunner."

Study: Book chapter

Question 25

Only the health and info Actuator endpoints should be exposed over HTTP in production. Which property configuration achieves that?

  • A) management.endpoints.enabled=*
  • B) management.endpoints.web.exposure.include=health,info
  • C) server.actuator.expose=all
  • D) spring.mvc.actuator.paths=health,info
Answer & explanation

Correct answer: B

management.endpoints.web.exposure.include lists which actuator endpoints are published on the web port. Modern Boot defaults are conservative, so teams must explicitly include any endpoint beyond the limited defaults they need.

Why the other options are wrong:

  • A) enabled=* does not selectively expose web endpoints and is overly broad.
  • C) server.actuator.expose is not the standard Boot property.
  • D) spring.mvc.actuator.paths is not the documented exposure mechanism.

Memory sentence: "Expose selected Actuator web endpoints with management.endpoints.web.exposure.include."

Study: Book chapter

Question 26

Operations wants custom health details for a downstream payment gateway without writing a full Actuator endpoint class from scratch.

Which extension point contributes a nested detail object to the overall /actuator/health response?

  • A) HttpMessageConverter
  • B) BeanFactoryPostProcessor
  • C) FilterRegistrationBean
  • D) HealthIndicator or ReactiveHealthIndicator implementation
Answer & explanation

Correct answer: D

Spring Boot Actuator aggregates HealthIndicator beans into the composite health endpoint. Custom indicators report UP, DOWN, or other statuses with optional details, which is the supported way to expose dependency health beyond defaults.

Why the other options are wrong:

  • A) HttpMessageConverter serializes HTTP bodies; it does not define health status contributors.
  • B) BeanFactoryPostProcessor modifies bean definitions at startup, not runtime health reporting.
  • C) FilterRegistrationBean registers servlet filters, not Actuator health contributors.

Memory sentence: "Custom Actuator health sections → implement HealthIndicator."

Study: Book chapter

Question 27

A production incident requires DEBUG logging for org.springframework.web only. What is the Boot property key?

  • A) logging.level.org.springframework.web=DEBUG
  • B) logger.org.springframework.web=DEBUG
  • C) debug.spring.web=true
  • D) spring.logging.org.springframework.web.level=DEBUG
Answer & explanation

Correct answer: A

Spring Boot maps logging.level.<logger-name> to the underlying logging system. This is the supported way to tune package-level verbosity without changing code.

Why the other options are wrong:

  • B) logger.* is not the Boot-standard property namespace.
  • C) debug.spring.web does not target a specific logger hierarchy.
  • D) spring.logging.*.level is not the conventional Boot logging property format.

Memory sentence: "Package log level → logging.level.<package>=DEBUG."

Study: Book chapter

Question 28

A large monolith's startup time is dominated by eager singleton creation for rarely used modules.

Which Boot 2.2+ feature creates non-lazy-init beans only when first used application-wide?

  • A) spring.main.web-application-type=none
  • B) spring.jpa.open-in-view=false
  • C) spring.main.lazy-initialization=true
  • D) management.endpoint.shutdown.enabled=true
Answer & explanation

Correct answer: C

spring.main.lazy-initialization=true tells the container to create singleton beans lazily unless marked @Lazy(false) or otherwise eager. This can shorten startup at the cost of shifting creation to first use and delaying some failures.

Why the other options are wrong:

  • A) Web application type changes servlet stack presence, not global bean laziness.
  • B) Open-in-view adjusts JPA session behavior in web requests, not bean initialization policy.
  • D) Shutdown endpoint enables graceful shutdown exposure, not lazy bean creation.

Memory sentence: "Global lazy singletons → spring.main.lazy-initialization=true."

Study: Book chapter

Question 29

A class should return JSON directly from method results without view resolution. Which stereotype is appropriate?

@???
public class ProductApi {
@GetMapping("/products/{id}")
public ProductDto one(@PathVariable Long id) { }
}
  • A) @Controller only
  • B) @RestController
  • C) @Repository
  • D) @Configuration
Answer & explanation

Correct answer: B

@RestController combines @Controller and @ResponseBody, signaling that handler methods write directly to the HTTP response body through message converters instead of resolving view names.

Why the other options are wrong:

  • A) Plain @Controller methods typically return view names unless each method adds @ResponseBody.
  • C) @Repository is a persistence stereotype, not an MVC web stereotype.
  • D) @Configuration defines beans; it does not map HTTP requests.

Memory sentence: "@RestController = @Controller + @ResponseBody for direct HTTP bodies."

Study: Book chapter

Question 30

A GET endpoint must read /orders/42 where 42 is the order identifier.

Which mapping correctly binds the path variable?

@GetMapping("/orders/{id}")
public OrderDto get(@??? Long id) { }
  • A) @RequestParam("id")
  • B) @RequestHeader("id")
  • C) @CookieValue("id")
  • D) @PathVariable("id")
Answer & explanation

Correct answer: D

@PathVariable extracts URI template variables from the path. @RequestParam reads query parameters, not path segments. The names must align with the {id} template variable.

Why the other options are wrong:

  • A) @RequestParam binds query string parameters such as ?id=42, not /orders/42 path segments.
  • B) @RequestHeader reads HTTP headers, not URI templates.
  • C) @CookieValue reads cookies, not path variables.

Memory sentence: "URI template {id} → @PathVariable("id")."

Study: Book chapter

Question 31

A POST /customers endpoint should validate a JSON request body before business logic runs. What must the controller parameter include?

@PostMapping("/customers")
public ResponseEntity<Void> create(@??? CustomerRequest request)
  • A) @Valid @RequestBody CustomerRequest request
  • B) @RequestParam CustomerRequest request
  • C) @ResponseBody CustomerRequest request
  • D) @PathVariable CustomerRequest request
Answer & explanation

Correct answer: A

@RequestBody maps the JSON payload to the object, and @Valid triggers Bean Validation on the object's constraints. Without @Valid, constraint annotations on CustomerRequest are ignored during MVC validation.

Why the other options are wrong:

  • B) @RequestParam binds form or query parameters, not a JSON request body.
  • C) @ResponseBody serializes return values; it does not validate inbound payloads.
  • D) @PathVariable binds URI segments, not request bodies.

Memory sentence: "Validate JSON body → @Valid @RequestBody on the parameter."

Study: Book chapter

Question 32

A controller method should return 201 Created with a Location header and a response body.

Which return type expresses both the status and headers idiomatically?

  • A) void with response.sendRedirect
  • B) String view name
  • C) ResponseEntity<CustomerDto>
  • D) HttpServletRequest
Answer & explanation

Correct answer: C

ResponseEntity carries status code, headers, and body in one type. It is the standard way to fine-tune REST responses beyond simple @ResponseStatus annotations.

Why the other options are wrong:

  • A) sendRedirect is servlet-centric and not the idiomatic Spring MVC REST approach.
  • B) View names participate in view resolution, not precise REST status/header control.
  • D) HttpServletRequest represents the inbound request, not the outbound response payload.

Memory sentence: "Custom status, headers, and body → ResponseEntity<T>."

Study: Book chapter

Question 33

Multiple controllers throw InvalidOrderException. A single class should map that exception to HTTP 400 with a problem body. Where should the handler live?

  • A) Duplicated in every controller as private methods
  • B) A @ControllerAdvice class with @ExceptionHandler methods
  • C) Only inside the DispatcherServlet source code
  • D) In application.properties as an error code mapping
Answer & explanation

Correct answer: B

@ControllerAdvice combines with @ExceptionHandler to centralize exception-to-response translation across controllers. This avoids duplicated error handling logic and keeps controllers focused on happy-path flows.

Why the other options are wrong:

  • A) Duplication violates DRY and is harder to maintain consistently.
  • C) DispatcherServlet is framework infrastructure, not application exception policy.
  • D) Properties files cannot declare Java exception handler methods.

Memory sentence: "Global MVC exception mapping → @ControllerAdvice + @ExceptionHandler."

Study: Book chapter

Question 34

A client sends Content-Type: application/xml but the endpoint only supports JSON.

Which annotation on the handler method restricts input to JSON?

  • A) produces = "application/json"
  • B) headers = "Accept: text/plain"
  • C) method = RequestMethod.PATCH only
  • D) consumes = MediaType.APPLICATION_JSON_VALUE
Answer & explanation

Correct answer: D

consumes narrows matching to requests with compatible Content-Type values. produces filters response content negotiation based on Accept. XML input to a JSON-only consumer should yield 415 Unsupported Media Type.

Why the other options are wrong:

  • A) produces governs response content type, not accepted request bodies.
  • B) Accept header constraints use produces or explicit header conditions, not this mismatched plain text value.
  • C) HTTP method restriction does not address media type mismatch.

Memory sentence: "Request Content-Type matching → consumes on @RequestMapping/@PostMapping."

Study: Book chapter

Question 35

Spring MVC converts a JSON request body into a Java object before a @RestController method runs. Which component performs that conversion?

  • A) An HttpMessageConverter such as MappingJackson2HttpMessageConverter
  • B) The ViewResolver
  • C) BeanFactoryPostProcessor
  • D) TransactionInterceptor
Answer & explanation

Correct answer: A

HttpMessageConverter implementations read and write HTTP bodies. Jackson-based converters map JSON to objects for @RequestBody and objects to JSON for @ResponseBody methods.

Why the other options are wrong:

  • B) ViewResolver resolves view names to templates, not JSON request bodies.
  • C) BeanFactoryPostProcessor modifies bean definitions at context startup, unrelated to HTTP conversion.
  • D) TransactionInterceptor manages transactional proxies, not message conversion.

Memory sentence: "@RequestBody JSON ↔ Java via HttpMessageConverter implementations."

Study: Book chapter

Question 36

A client posts JSON to an endpoint that declares consumes = "application/json", but the request has no Content-Type header.

What is the most likely HTTP result?

  • A) 200 OK with empty body
  • B) 302 Found redirect
  • C) 415 Unsupported Media Type or 400-series content negotiation failure
  • D) 500 Internal Server Error caused by NPE in Jackson only
Answer & explanation

Correct answer: C

When a handler declares consumes, Spring matches Content-Type carefully. Missing or incompatible media types prevent handler selection or body conversion, typically surfacing as 415 Unsupported Media Type or another 4xx related to content negotiation.

Why the other options are wrong:

  • A) Successful 200 is unlikely when the declared consumer media type is not satisfied.
  • B) Redirects are unrelated to content type negotiation for REST POST bodies.
  • D) While errors can occur deeper in conversion, the framework usually rejects the request earlier with a client error.

Memory sentence: "Wrong or missing Content-Type vs consumes → 415-style client error."

Study: Book chapter

Question 37

A @Transactional service method catches a RuntimeException, logs it, and does not rethrow. What happens to the transaction by default?

@Transactional
public void placeOrder() {
try {
orderRepository.save(order);
throw new IllegalStateException("inventory hold failed");
} catch (RuntimeException ex) {
log.warn("failure", ex);
}
}
  • A) The transaction always commits because the exception was caught
  • B) The transaction is marked rollback-only when the runtime exception is thrown, even if caught inside the method
  • C) Rollback occurs only for checked exceptions
  • D) Transactions are suspended automatically in catch blocks
Answer & explanation

Correct answer: B

Spring's transaction interceptor marks the transaction rollback-only when a rollback-triggering exception crosses the transactional boundary. Catching RuntimeException inside the method does not undo rollback marking that already occurred for default rollback rules.

Why the other options are wrong:

  • A) Catching without rollback configuration does not guarantee commit; default runtime exceptions still roll back.
  • C) Checked exceptions do not roll back by default unless configured.
  • D) Catch blocks do not automatically suspend transactions.

Memory sentence: "Caught or not, default @Transactional still rolls back on RuntimeException."

Study: Book chapter

Question 38

A read-heavy report service loads large result sets that are mapped to DTOs and never modified.

Which @Transactional attribute can optimize the interaction with the persistence provider?

  • A) propagation = REQUIRES_NEW for every query
  • B) rollbackFor = Exception.class on all reports
  • C) timeout = -1 only
  • D) readOnly = true
Answer & explanation

Correct answer: D

readOnly = true hints that no state changes occur, allowing optimizations such as flush avoidance and, with some providers, read-only JDBC connections. It is appropriate for query-only transactional boundaries.

Why the other options are wrong:

  • A) REQUIRES_NEW creates independent transactions per call, not read optimization.
  • B) rollbackFor broadens rollback behavior but does not optimize read-only access.
  • C) Timeout settings do not mark the transaction as read-only.

Memory sentence: "Query-only transactional work → readOnly = true."

Study: Book chapter

Question 39

A repository method executes a bulk UPDATE JPQL statement. Which annotations are required for correct Spring Data JPA behavior?

@Modifying
@Query("update Inventory i set i.qty = i.qty - 1 where i.sku = ?1")
int decrement(String sku);
  • A) @Modifying plus @Transactional on the service or repository layer
  • B) @Cacheable only
  • C) @Entity on the repository interface
  • D) @OneToMany on the method
Answer & explanation

Correct answer: A

Custom modifying queries must be annotated with @Modifying and run inside a transaction so the persistence context and database stay consistent. Spring Data also typically expects @Transactional for write operations at the service boundary.

Why the other options are wrong:

  • B) @Cacheable controls caching, not DML execution semantics.
  • C) Repository interfaces are not JPA entities.
  • D) Relationship mapping annotations do not apply to repository query methods.

Memory sentence: "Bulk JPQL updates → @Modifying and a surrounding transaction."

Study: Book chapter

Question 40

A batch job loads thousands of entities, modifies a few fields per row, and suffers memory growth.

Which EntityManager operations help limit persistence context growth during the loop?

  • A) merge() before every read
  • B) detach() on the transaction manager
  • C) flush() periodically and clear() to detach managed entities
  • D) getReference() only without any flush
Answer & explanation

Correct answer: C

Long-running loops accumulate managed entities in the persistence context. Periodic flush() writes pending changes, and clear() detaches managed instances so memory does not grow unbounded.

Why the other options are wrong:

  • A) Blind merge on every read increases managed entity count rather than controlling it.
  • B) detach() belongs to EntityManager on entities; the transaction manager is not the persistence context.
  • D) getReference() avoids immediate loading but does not by itself solve context growth for loaded entities.

Memory sentence: "Big batch loops → periodic flush() and clear() on EntityManager."

Study: Book chapter

Question 41

What is the default fetch type for a @OneToMany association in JPA?

  • A) EAGER
  • B) LAZY
  • C) IMMEDIATE
  • D) SUBSELECT only
Answer & explanation

Correct answer: B

JPA defaults @OneToMany and @ManyToMany collections to LAZY fetching. @ManyToOne and @OneToOne default to EAGER, which is a common exam trap when diagnosing N+1 or unexpected joins.

Why the other options are wrong:

  • A) EAGER is the default for single-valued @ManyToOne, not collections.
  • C) IMMEDIATE is not a standard JPA fetch type name.
  • D) SUBSELECT is an optional fetch mode, not the default fetch type.

Memory sentence: "Collections default LAZY; many-to-one defaults EAGER."

Study: Book chapter

Question 42

Service A with no transaction calls Service B annotated with @Transactional(propagation = REQUIRED).

What transaction behavior occurs when B's method runs?

  • A) B always runs without a transaction
  • B) B creates a brand-new transaction that commits before A continues
  • C) B joins A's existing transaction only if A is also transactional
  • D) B starts a new transactional boundary because REQUIRED creates one when none exists
Answer & explanation

Correct answer: D

REQUIRED participates in the current transaction if present; otherwise it creates a new one. Because A is non-transactional, B begins and commits its own transaction for the duration of the proxied call.

Why the other options are wrong:

  • A) REQUIRED does not run non-transactionally when no existing transaction is present; it creates one.
  • B) The transaction lasts for B's method execution but is not independent of the REQUIRED rule semantics described here.
  • C) A has no transaction to join, so B cannot join A's transaction.

Memory sentence: "REQUIRED = join existing tx or create a new one if absent."

Study: Book chapter

Question 43

An entity includes @Version private Long version. Two transactions update the same row concurrently. What should the loser expect?

@Entity
class Product {
@Version
private Long version;
}
  • A) OptimisticLockException or similar optimistic locking failure
  • B) Automatic retry by Spring Data without error
  • C) Silent overwrite of the version column only
  • D) Immediate database deadlock on every update
Answer & explanation

Correct answer: A

@Version enables optimistic locking. The UPDATE includes the version predicate; if zero rows match because another transaction incremented the version, the persistence provider throws OptimisticLockException.

Why the other options are wrong:

  • B) Spring Data does not silently retry concurrent optimistic failures by default.
  • C) The losing transaction fails rather than silently overwriting managed state.
  • D) Optimistic locking avoids long-held pessimistic locks; deadlock is not the guaranteed outcome.

Memory sentence: "@Version mismatch → OptimisticLockException on conflicting update."

Study: Book chapter

Question 44

A new Customer entity with a null id is passed to customerRepository.save(customer).

What does save() do for a new entity in typical Spring Data JPA usage?

  • A) Always issues an UPDATE statement only
  • B) Throws IllegalArgumentException because id is null
  • C) Uses persist semantics to INSERT and assign the generated id
  • D) Detaches the entity without database interaction
Answer & explanation

Correct answer: C

Spring Data JPA save() delegates to EntityManager persist or merge based on entity state. A new entity with null id is persisted, causing an INSERT and population of generated identifiers.

Why the other options are wrong:

  • A) UPDATE occurs for existing detached or managed entities with identifiers, not brand-new null-id entities.
  • B) Null id is expected for new entities and does not inherently trigger IllegalArgumentException.
  • D) save() interacts with the persistence context; it does not merely detach.

Memory sentence: "save() on new null-id entity → persist and INSERT."

Study: Book chapter

Question 45

In Spring Security 6 with a Servlet-based Spring Boot app, which bean defines the HTTP security filter chain?

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public ??? securityFilterChain(HttpSecurity http) throws Exception { }
}
  • A) FilterRegistrationBean only without SecurityFilterChain
  • B) A @Bean method returning SecurityFilterChain
  • C) HttpSecurity stored as a singleton without building a chain
  • D) WebMvcConfigurer adapter exclusively
Answer & explanation

Correct answer: B

Modern Spring Security configures the servlet filter chain by exposing a SecurityFilterChain bean, usually created from an HttpSecurity builder in a @Configuration class. This replaces the older WebSecurityConfigurerAdapter style.

Why the other options are wrong:

  • A) FilterRegistrationBean can register filters but does not replace SecurityFilterChain-based security configuration.
  • C) HttpSecurity is a builder; you must call build() to produce the SecurityFilterChain bean.
  • D) WebMvcConfigurer customizes MVC, not the security filter chain ordering and authorization rules.

Memory sentence: "Servlet security in Boot 3 → @Bean SecurityFilterChain from HttpSecurity."

Study: Book chapter

Question 46

User passwords must be stored hashed in the database and verified on login.

Which PasswordEncoder is the recommended default choice in Spring Security?

  • A) NoOpPasswordEncoder for readability
  • B) PlaintextPasswordEncoder
  • C) Md5PasswordEncoder
  • D) BCryptPasswordEncoder
Answer & explanation

Correct answer: D

BCryptPasswordEncoder is the recommended adaptive hashing encoder for storing passwords securely. Legacy plaintext or weak hash encoders are provided for migration scenarios but must not be used for new systems.

Why the other options are wrong:

  • A) NoOpPasswordEncoder stores passwords in plain text and is unsafe.
  • B) Plaintext storage is not acceptable for production authentication.
  • C) MD5 is unsuitable for password hashing in modern threat models.

Memory sentence: "Store passwords with BCryptPasswordEncoder, not plaintext or MD5."

Study: Book chapter

Question 47

Method security should allow deleteOrder only when the caller has ROLE_ADMIN. Which annotation expresses that on the service method?

@Service
public class OrderAdminService {
public void deleteOrder(Long id) { }
}
  • A) @PreAuthorize("hasRole('ADMIN')")
  • B) @PermitAll
  • C) @RolesAllowed from Servlet API only on controllers
  • D) @Transactional(readOnly = true)
Answer & explanation

Correct answer: A

@PreAuthorize with hasRole checks authorities at method invocation time when method security is enabled via @EnableMethodSecurity. hasRole automatically prefixes ROLE_ for role names.

Why the other options are wrong:

  • B) @PermitAll allows unrestricted access, opposite of the requirement.
  • C) @RolesAllowed can work in some setups, but the Spring-native expression-based choice here is @PreAuthorize on the service method.
  • D) Transaction readOnly governs persistence behavior, not authorization.

Memory sentence: "Method-level roles → @PreAuthorize("hasRole('ADMIN')")."

Study: Book chapter

Question 48

A stateless REST API uses JWT bearer tokens and has no browser form login.

What is a common CSRF configuration for that API?

  • A) Keep CSRF enabled and require a synchronizer token on every GET
  • B) Disable session creation only but keep CSRF token repository mandatory for POST
  • C) Disable CSRF protection because browsers are not submitting cookie-based session auth
  • D) Enable formLogin and logout concurrently with JWT
Answer & explanation

Correct answer: C

CSRF protects cookie-based session authentication in browsers. Stateless JWT APIs that do not rely on browser-automatic credential submission commonly disable CSRF while still enforcing authentication on protected endpoints.

Why the other options are wrong:

  • A) GET requests should not carry CSRF tokens; enabling CSRF for token APIs is usually unnecessary overhead.
  • B) CSRF token repositories target session-cookie form posts, not bearer-token clients.
  • D) formLogin is a session-oriented pattern and conflicts with a pure stateless JWT design.

Memory sentence: "Stateless JWT APIs often disable CSRF; cookie sessions need CSRF."

Study: Book chapter

Question 49

In HttpSecurity authorizeHttpRequests configuration, what does requestMatchers("/public/**").permitAll() accomplish?

  • A) Requires ROLE_ADMIN for those paths
  • B) Allows unauthenticated access to matching paths
  • C) Disables the entire security filter chain
  • D) Encrypts responses for those paths
Answer & explanation

Correct answer: B

permitAll grants access without authentication for the matched requests. Other matchers can still require authentication, and the filter chain continues to run.

Why the other options are wrong:

  • A) permitAll is the opposite of admin-only authorization.
  • C) Security filters still execute; only authorization requirements are relaxed for those paths.
  • D) Authorization rules do not perform response encryption.

Memory sentence: "permitAll = accessible without authentication for matched URLs."

Study: Book chapter

Question 50

On login, Spring Security must load user details and granted authorities from a database.

Which extension point should be implemented?

  • A) HttpMessageConverter
  • B) BeanPostProcessor
  • C) FilterChainProxy directly in controllers
  • D) UserDetailsService
Answer & explanation

Correct answer: D

UserDetailsService loads user-specific data during authentication. DaoAuthenticationProvider combines the presented credentials with the UserDetails and PasswordEncoder to decide authentication success.

Why the other options are wrong:

  • A) HttpMessageConverter handles HTTP bodies, not security principal loading.
  • B) BeanPostProcessor customizes bean initialization, not authentication data retrieval.
  • C) Controllers should not implement FilterChainProxy; security stays in the filter chain configuration.

Memory sentence: "Load users for authentication → implement UserDetailsService."

Study: Book chapter

Question 51

You want to test a @RestController in isolation with MockMvc without loading the full application context. Which test slice is appropriate?

  • A) @WebMvcTest(controllers = InvoiceController.class)
  • B) @SpringBootTest with RANDOM_PORT
  • C) @DataJpaTest
  • D) @SpringBootConfiguration only
Answer & explanation

Correct answer: A

@WebMvcTest auto-configures Spring MVC infrastructure and MockMvc while limiting component scanning to web-layer beans relevant to the specified controllers. Service and repository beans are not loaded unless provided via @Import or @MockBean.

Why the other options are wrong:

  • B) Full Boot tests start the entire context and embedded server, not controller isolation.
  • C) @DataJpaTest targets persistence components, not MVC controllers.
  • D) @SpringBootConfiguration alone does not provide the MVC test slice or MockMvc setup.

Memory sentence: "Controller-only MockMvc tests → @WebMvcTest with targeted controllers."

Study: Book chapter

Question 52

A @WebMvcTest loads InvoiceController, but InvoiceController depends on InvoiceService which must be simulated.

Which annotation adds a Mockito mock of InvoiceService into the sliced test context?

  • A) @Mock on a field without Spring integration
  • B) @Autowired on a manually new-ed service
  • C) @MockBean InvoiceService invoiceService;
  • D) @SpyBean on the controller only
Answer & explanation

Correct answer: C

@MockBean tells Spring Boot test support to add a Mockito mock as a bean in the application context, which is essential in slice tests where the real collaborator is not on the classpath scan.

Why the other options are wrong:

  • A) Plain @Mock creates a Mockito object that is not registered in the Spring test context for injection into the controller.
  • B) Manual construction bypasses the slice context wiring.
  • D) @SpyBean wraps a real bean; the service bean is absent in the slice and should be mocked, not spied.

Memory sentence: "Missing collaborator in slice tests → @MockBean in the test context."

Study: Book chapter

Question 53

An integration test must start the full Spring Boot application on a random available port to exercise RestClient against real servlet listeners. Which configuration applies?

  • A) @WebMvcTest
  • B) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  • C) @JsonTest
  • D) @ExtendWith(MockitoExtension.class) only
Answer & explanation

Correct answer: B

@SpringBootTest with RANDOM_PORT launches the complete application context and binds the web server to a random port, enabling true end-to-end HTTP integration tests.

Why the other options are wrong:

  • A) @WebMvcTest does not start a real listening port for the full application.
  • C) @JsonTest slices JSON mapping support only.
  • D) MockitoExtension provides unit-test mocks without Spring context or HTTP port binding.

Memory sentence: "Full app on random port → @SpringBootTest(RANDOM_PORT)."

Study: Book chapter

Question 54

A developer wants to test JPA repositories against an in-memory database without loading controllers or security.

Which annotation is the best fit?

  • A) @WebMvcTest
  • B) @SpringBootTest
  • C) @MockMvcTest
  • D) @DataJpaTest
Answer & explanation

Correct answer: D

@DataJpaTest limits the context to JPA-related beans and repositories, uses an embedded database by default, and excludes most web and security auto-configuration unless explicitly imported.

Why the other options are wrong:

  • A) @WebMvcTest targets controllers, not repositories.
  • B) @SpringBootTest loads the entire application, heavier than needed for repository tests.
  • C) @MockMvcTest is not a standard Spring Boot test slice annotation.

Memory sentence: "Repository-focused JPA tests → @DataJpaTest slice."

Study: Book chapter

Question 55

A @SpringBootTest needs an extra @Bean not present in production configuration. Where should test-only beans be declared?

  • A) @TestConfiguration class imported or discovered by the test
  • B) Directly inside the production @SpringBootApplication class
  • C) Only in static main method
  • D) In application.properties as key-value pairs
Answer & explanation

Correct answer: A

@TestConfiguration provides supplemental beans for tests without polluting production configuration. It can be inner static classes or separate types referenced from the test class.

Why the other options are wrong:

  • B) Production application sources should not carry test-only beans.
  • C) main is unrelated to Spring test bean registration.
  • D) Properties cannot declare arbitrary @Bean factory methods.

Memory sentence: "Test-only beans → @TestConfiguration, keep production config clean."

Study: Book chapter

Question 56

A plain unit test without Spring context must inject mocks into OrderService.

Which Mockito annotation creates the service and injects @Mock collaborators?

  • A) @MockBean on OrderService
  • B) @Captor only
  • C) @InjectMocks OrderService orderService;
  • D) @SpringBootTest
Answer & explanation

Correct answer: C

@InjectMocks constructs the class under test and injects Mockito mocks and spies into its fields or constructor. @MockBean is for Spring tests, not plain Mockito unit tests.

Why the other options are wrong:

  • A) @MockBean requires a Spring test context.
  • B) @Captor captures argument values for verification; it does not create the system under test.
  • D) @SpringBootTest boots the context, which is unnecessary for a isolated Mockito unit test.

Memory sentence: "Pure Mockito wiring → @InjectMocks plus @Mock fields."

Study: Book chapter

Question 57

AuditService is proxied for @Transactional, but internal method calls skip advice.

Why does calling this.save(record) from this.archive(record) not start a new transaction?

@Service
public class AuditService {
@Transactional
public void archive(Record record) {
this.save(record);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(Record record) { }
}
  • A) Because @Transactional only works on private methods
  • B) Because self-invocation bypasses the Spring proxy and calls the target object directly
  • C) Because REQUIRES_NEW is invalid inside the same class
  • D) Because archive() is not public
Answer & explanation

Correct answer: B

Spring AOP proxies intercept external calls through the proxy reference. this.save() is an internal call on the raw target, so transaction advice on save() is never applied. Delegate to another bean or use AopContext.currentProxy() intentionally if needed.

Why the other options are wrong:

  • A) @Transactional on public methods is supported; privacy is not the issue here.
  • C) REQUIRES_NEW is valid; the problem is proxy bypass via self-invocation.
  • D) archive() visibility is fine; self-invocation would fail even if both methods were public.

Memory sentence: "this.method() inside a bean bypasses the proxy — no advice applied."

Study: Book chapter

Question 58

A service method should run asynchronously on a task executor after @EnableAsync is present. Which annotation marks the method?

@Service
public class EmailDispatchService {
@???
public void sendReceipt(String orderId) { }
}
  • A) @Scheduled
  • B) @EventListener
  • C) @Cacheable
  • D) @Async
Answer & explanation

Correct answer: D

@Async routes method execution through an TaskExecutor when @EnableAsync is configured. The caller receives a Future or void immediately while work continues on another thread.

Why the other options are wrong:

  • A) @Scheduled runs tasks on a timer, not ad-hoc async invocation from callers.
  • B) @EventListener reacts to application events; it is not the general async method marker.
  • C) @Cacheable intercepts method calls for cache storage, not asynchronous execution.

Memory sentence: "Async method execution → @Async with @EnableAsync enabled."

Study: Book chapter

Question 59

OrderPlacedEvent is published with applicationContext.publishEvent(orderPlacedEvent). No @Async is used on listeners.

How are @EventListener methods invoked by default in the same thread?

  • A) Synchronously in the caller thread before publishEvent returns
  • B) Always on a new daemon thread
  • C) Only after the JVM shuts down
  • D) Only when @TransactionalEventListener(AFTER_COMMIT) is present
Answer & explanation

Correct answer: A

Default @EventListener invocation is synchronous in the publishing thread unless the listener is made async. Transactional event listeners add phase control relative to transaction commit but are a separate mechanism.

Why the other options are wrong:

  • B) Async behavior requires explicit @Async configuration on listeners or the executor setup.
  • C) Events are delivered during normal application execution, not exclusively at shutdown.
  • D) AFTER_COMMIT is optional for transactional listeners, not the default for every event.

Memory sentence: "Default @EventListener runs synchronously in the publisher thread."

Study: Book chapter

Question 60

@Scheduled(fixedRate = 5000) is placed on a cleanup() method. What does fixedRate mean?

@Component
public class TempFileCleaner {
@Scheduled(fixedRate = 5000)
public void cleanup() { }
}
  • A) Wait 5000 ms after the previous run finishes before starting again
  • B) Run only once 5000 ms after startup
  • C) Start every 5000 ms measured from the start of each scheduled execution
  • D) Execute only when a cron expression matches
Answer & explanation

Correct answer: C

fixedRate schedules the next execution based on the start time of invocations, every 5000 ms in this example. fixedDelay measures from the completion of the previous run, which is a different scheduling semantics trap.

Why the other options are wrong:

  • A) Waiting after completion describes fixedDelay, not fixedRate.
  • B) fixedRate repeats on an interval; it is not a single delayed one-shot unless configured otherwise.
  • D) Cron scheduling uses cron expressions, not fixedRate milliseconds.

Memory sentence: "fixedRate = interval from start; fixedDelay = gap after previous finish."

Study: Book chapter


End of Mock Full 04 — Spring Professional (60 Questions)