Skip to main content

Mock Full 02 — 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 legacy module is migrated to Spring. The team wants dependencies supplied by the container instead of manual new calls inside business classes.

What is the primary mechanism Spring uses to deliver a PaymentGateway implementation into OrderService?

@Service
public class OrderService {
private final PaymentGateway paymentGateway;
public OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}
  • A) Dependency Injection — the container resolves and supplies collaborators at creation or injection time
  • B) Aspect-Oriented Programming — cross-cutting advice wires collaborators automatically
  • C) Component Scanning — scanning alone creates and injects dependencies without bean definitions
  • D) Property binding — @Value replaces constructor wiring for all service dependencies
Answer & explanation

Correct answer: A

Spring's IoC container manages object creation and wiring. Dependency Injection is how collaborators are provided (constructor, setter, or field). AOP handles cross-cutting concerns; scanning discovers beans but injection is the delivery mechanism.

Why the other options are wrong:

  • B) AOP adds behavior around methods; it does not replace DI for supplying core collaborators.
  • C) Component scanning finds @Component classes, but injection is still how dependencies are delivered.
  • D) @Value injects scalar configuration, not arbitrary service collaborators as the primary wiring model.

Memory sentence: "IoC creates and owns beans; DI is how those beans receive their dependencies."

Study: Book chapter

Question 2

Two beans depend on each other: ReportGenerator needs AuditTrail, and AuditTrail needs ReportGenerator. Both use constructor injection only.

What happens when the ApplicationContext starts?

@Service
public class ReportGenerator {
public ReportGenerator(AuditTrail auditTrail) { ... }
}

@Service
public class AuditTrail {
public AuditTrail(ReportGenerator reportGenerator) { ... }
}
  • A) Spring creates both beans lazily on first use and resolves the cycle at runtime
  • B) Spring injects null into one constructor and completes wiring after both exist
  • C) Context startup fails because neither bean can be constructed without the other already existing
  • D) Spring automatically switches one side to setter injection to break the cycle
Answer & explanation

Correct answer: C

Constructor-only circular dependencies cannot be satisfied: each bean needs the other fully constructed first. Spring fails fast at context refresh. Setter/field injection or @Lazy on one constructor parameter can break the cycle.

Why the other options are wrong:

  • A) Lazy initialization delays creation but does not solve constructor mutual dependency at first access.
  • B) Spring does not inject null to break constructor cycles.
  • D) Spring does not silently convert constructor injection to setter injection.

Memory sentence: "Constructor circular dependencies fail at startup; break them with @Lazy, redesign, or setter/field injection."

Study: Book chapter

Question 3

A team has three NotificationSender implementations registered as beans. AlertService must use the one named smsSender.

Which approach reliably selects the smsSender bean at injection time?

@Component("smsSender")
public class SmsNotificationSender implements NotificationSender { }

@Service
public class AlertService {
// which injection is correct?
}
  • A) Annotate the preferred implementation with @Primary and inject NotificationSender without a qualifier
  • B) Inject with @Qualifier("smsSender") on the constructor parameter (or field/setter)
  • C) Rename the interface to SmsNotificationSender so Spring picks it by type
  • D) Use @Autowired on a List<NotificationSender> and take index 0
Answer & explanation

Correct answer: B

@Qualifier("smsSender") disambiguates when multiple beans share a type. @Primary marks a default but does not target a specific named bean when others also exist.

Why the other options are wrong:

  • A) @Primary helps when one default is enough; it does not guarantee smsSender if multiple beans compete.
  • C) The injection type remains NotificationSender; renaming the impl class does not disambiguate by itself.
  • D) List injection order is not a reliable selection strategy for production wiring.

Memory sentence: "Multiple same-type beans need @Qualifier or @Primary — qualifier targets a specific bean by name."

Study: Book chapter

Question 4

A developer compares BeanFactory and ApplicationContext for a CLI tool that should start quickly and load few beans initially.

Which statement about BeanFactory versus ApplicationContext is correct?

  • A) ApplicationContext always loads every bean lazily; BeanFactory loads eagerly
  • B) Both are identical in enterprise applications; the names are historical aliases
  • C) BeanFactory supports internationalization and event publication; ApplicationContext does not
  • D) BeanFactory is the basic IoC container with lazy-by-default behavior; ApplicationContext adds enterprise features and typically pre-instantiates singletons
Answer & explanation

Correct answer: D

BeanFactory is the foundational container (lazy singleton creation by default). ApplicationContext extends it with message sources, events, AOP auto-application, and usually eager singleton initialization at refresh.

Why the other options are wrong:

  • A) The lazy/eager behavior is reversed for typical singleton startup patterns.
  • B) They differ in capabilities and default initialization behavior.
  • C) Enterprise features like i18n and events belong to ApplicationContext, not plain BeanFactory.

Memory sentence: "BeanFactory = lean lazy core; ApplicationContext = BeanFactory plus enterprise features and eager singleton warmup."

Study: Book chapter

Question 5

A @Configuration class defines two @Bean methods where the second bean needs the first.

How does Spring ensure @Bean method inter-calls inside a @Configuration class return container-managed singletons?

@Configuration
public class BillingConfig {
@Bean
public TaxCalculator taxCalculator() { return new TaxCalculator(); }

@Bean
public InvoiceService invoiceService() {
return new InvoiceService(taxCalculator());
}
}
  • A) Spring rewrites bytecode so @Bean methods are static and bypass the configuration instance
  • B) Spring CGLIB-enhances the @Configuration class so @Bean method calls route through the proxy to the container
  • C) Each call to taxCalculator() always creates a new instance because new is used inside the method
  • D) Inter-bean calls work only when @Configuration is replaced with @Component
Answer & explanation

Correct answer: B

In full @Configuration mode, the class is proxied. Calling taxCalculator() from invoiceService() goes through the proxy and returns the singleton bean from the context, not a fresh new each time.

Why the other options are wrong:

  • A) @Bean methods are not made static; proxying intercepts instance method calls.
  • C) Without proxying that would be true; @Configuration proxying prevents duplicate instances.
  • D) @Component with @Bean methods uses lite mode without full inter-bean proxy semantics.

Memory sentence: "Full @Configuration proxies @Bean method calls so inter-bean references stay singleton-managed."

Study: Book chapter

Question 6

A library ships a plain Java class without Spring annotations. The application must expose it as a bean with custom initialization logic.

What is the idiomatic way to register LegacyParser as a Spring bean?

  • A) Add @Component to LegacyParser even though you cannot modify the library source
  • B) Declare a @Bean method in a @Configuration class that returns new LegacyParser()
  • C) Place LegacyParser in spring.factories so component scanning picks it up
  • D) Use @Autowired on a field inside LegacyParser to self-register
Answer & explanation

Correct answer: B

When source is not annotatable, @Bean methods in Java configuration register third-party types. You control instantiation and can add @PostConstruct wrappers or init logic in the factory method.

Why the other options are wrong:

  • A) You cannot annotate third-party library classes you do not own (in the typical scenario).
  • C) spring.factories is for auto-configuration registration, not general third-party bean discovery.
  • D) @Autowired does not register beans; it consumes existing ones.

Memory sentence: "Third-party classes become beans via @Bean factory methods in @Configuration."

Study: Book chapter

Question 7

An integration test calls context.refresh() twice on the same AnnotationConfigApplicationContext without closing it.

What is the expected outcome?

  • A) All singleton beans are re-created and the context remains usable with a fresh set of instances
  • B) Only prototype beans refresh; singletons are untouched
  • C) Only @Lazy beans are recreated on the second refresh
  • D) The second refresh() is ignored silently
Answer & explanation

Correct answer: A

Calling refresh() shuts down the previous context state and rebuilds it, recreating singleton bean definitions. Prototype instances are not stored as singletons; new prototypes are created per request.

Why the other options are wrong:

  • B) Singletons are re-instantiated on refresh, not preserved.
  • C) Refresh rebuilds the context broadly, not only @Lazy beans.
  • D) refresh() is not a no-op; it actively reinitializes the context.

Memory sentence: "refresh() rebuilds the context — singleton beans get new instances."

Study: Book chapter

Question 8

A service has a mandatory repository and an optional metrics collector that may be absent in some profiles.

Which injection style best expresses optional dependency semantics?

@Service
public class CheckoutService {
private final OrderRepository orderRepository;
// optional MetricsCollector may be absent
}
  • A) Required constructor injection for both dependencies — startup fails if metrics is missing
  • B) Field injection with @Autowired on both fields
  • C) Constructor for OrderRepository plus Optional<MetricsCollector> or @Autowired(required = false)
  • D) Static factory method on CheckoutService called from main
Answer & explanation

Correct answer: C

Mandatory deps belong in the required constructor. Optional deps use Optional<T>, @Nullable, or @Autowired(required = false) on setter/field. Constructor injection of optional deps can use Optional parameters in Spring Framework 4.3+.

Why the other options are wrong:

  • A) Required constructor injection makes the optional bean mandatory and fails startup if absent.
  • B) Field injection works but is less explicit about required vs optional and is harder to test.
  • D) Manual factory bypasses the IoC container's wiring model.

Memory sentence: "Required deps in constructor; optional deps via Optional, required=false, or @Nullable."

Study: Book chapter

Question 9

Packages are split across modules: @SpringBootApplication sits in com.acme.app but components live in com.acme.billing and com.acme.shipping.

Beans in com.acme.billing are not discovered at startup. What is the most likely fix?

  • A) Add @EnableAutoConfiguration on each subpackage class
  • B) Add @ComponentScan(basePackages = "com.acme") or move/share a scan root that includes both subpackages
  • C) Rename packages so every class is directly under com.acme.app
  • D) Replace @Service with @Bean in every subpackage
Answer & explanation

Correct answer: B

Default scanning starts at the @SpringBootApplication package and descendants only. Sibling packages (com.acme.billing) are outside that tree unless you widen @ComponentScan or restructure packages.

Why the other options are wrong:

  • A) @EnableAutoConfiguration enables Boot auto-config; it does not replace component scan base packages.
  • C) Restructuring can work but widening scan is the direct fix; renaming everything is unnecessary.
  • D) @Bean per class is verbose and does not solve scan visibility by itself.

Memory sentence: "Component scan only sees the annotated package and subpackages — siblings need explicit basePackages."

Study: Book chapter

Question 10

A developer asks whether Spring eliminates the need for factories, singletons, and dependency graphs in application design.

What problem does Spring's IoC container primarily solve?

  • A) It compiles Java sources faster than javac
  • B) It replaces JDBC with object mapping automatically
  • C) It removes the need for interfaces in service design
  • D) It centralizes object creation and wiring so classes focus on business logic instead of locating collaborators
Answer & explanation

Correct answer: D

Spring addresses tight coupling and scattered new/lookup code by managing the object graph. Classes declare dependencies; the container assembles them. It does not remove design needs like interfaces or persistence technology choices.

Why the other options are wrong:

  • A) Spring is a runtime framework, not a compiler.
  • B) Data access is addressed by Spring Data/JPA modules, not IoC itself.
  • C) Interfaces remain a design tool; Spring works well with or without them.

Memory sentence: "Spring solves wiring and lifecycle — not compilation, ORM, or eliminating good design."

Study: Book chapter

Question 11

A property app.retry.max=3 should bind to a configuration class field with a safe default when the property is missing.

Which declaration correctly binds the property with default value 3?

@Component
public class RetrySettings {
// which field declaration is correct?
}
  • A) @Value("${app.retry.max:3}") private int maxRetries;
  • B) @Value("app.retry.max=3") private int maxRetries;
  • C) @ConfigurationProperties("app.retry") with only @DefaultValue on the field
  • D) @PropertySource("3") private int maxRetries;
Answer & explanation

Correct answer: A

Spring @Value placeholder syntax supports defaults after a colon: $\{property.name:defaultValue\}. @ConfigurationProperties binds prefixes from the environment but uses different default mechanisms (field init or @DefaultValue in Boot 2.4+).

Why the other options are wrong:

  • B) That is not valid placeholder syntax; it would be treated as a literal or fail.
  • C) @ConfigurationProperties needs a prefix and property name mapping; @DefaultValue alone without proper binding is incomplete in the snippet shown.
  • D) @PropertySource names a properties file location, not an inline default value.

Memory sentence: "$\{key:default\} in @Value supplies a fallback when the property is absent."

Study: Book chapter

Question 12

Database settings should bind from app.datasource.* keys into a type-safe object used in @Configuration.

Which approach is the most maintainable for multiple related properties?

app.datasource.url=jdbc:postgresql://db:5432/orders
app.datasource.username=app
app.datasource.pool-size=10
  • A) Three separate @Value injections in DataSourceConfig
  • B) A @Bean method that reads System.getenv() manually
  • C) A @ConfigurationProperties(prefix = "app.datasource") class enabled with @EnableConfigurationProperties
  • D) Hard-code values in @Bean methods and override only in production
Answer & explanation

Correct answer: C

@ConfigurationProperties groups related settings with validation and relaxed binding. It scales better than many @Value fields and keeps configuration structured.

Why the other options are wrong:

  • A) Multiple @Value fields work but become brittle as property count grows.
  • B) Manual env reads bypass Spring's binding, validation, and test property support.
  • D) Hard-coding defeats externalized configuration goals.

Memory sentence: "Grouped external config → @ConfigurationProperties plus enablement; scattered scalars → @Value."

Study: Book chapter

Question 13

Beans annotated @Profile("postgres") should load only when the postgres profile is active in a Spring Boot app.

Which activation method is valid?

@Profile("postgres")
@Repository
public class PostgresOrderRepository implements OrderRepository { }
  • A) Annotate the main class with @Profile("postgres") only
  • B) Set spring.profiles.active=postgres in configuration or pass --spring.profiles.active=postgres
  • C) Rename the bean class to PostgresOrderRepository
  • D) Add @Primary to the profile-specific bean
Answer & explanation

Correct answer: B

Profiles activate via spring.profiles.active (property, env var, command line, or @ActiveProfiles in tests). @Profile on beans gates registration when that profile is active.

Why the other options are wrong:

  • A) Putting @Profile on the main class is unusual and does not by itself activate the profile.
  • C) Class naming does not activate Spring profiles.
  • D) @Primary selects among competing beans of the same type; it does not activate profiles.

Memory sentence: "Profiles are turned on via spring.profiles.active, not by naming conventions alone."

Study: Book chapter

Question 14

A singleton ShoppingCartFacade injects a prototype-scoped PromotionCalculator.

How many PromotionCalculator instances exist over the lifetime of one ShoppingCartFacade singleton?

@Service
@Scope("singleton")
public class ShoppingCartFacade {
private final PromotionCalculator calculator; // prototype bean
}
  • A) Exactly one — prototype scope collapses to singleton when injected into a singleton
  • B) Zero — prototype beans cannot be injected into singletons
  • C) One per HTTP request automatically
  • D) One per injection resolution into the singleton — by default a single instance is injected at startup and reused
Answer & explanation

Correct answer: D

Injecting a prototype bean into a singleton typically captures one prototype instance at singleton creation time. For per-use prototype behavior, use ObjectProvider<T>, @Lookup, or scoped proxy patterns.

Why the other options are wrong:

  • A) Prototype does not collapse; the issue is injection timing captures one instance.
  • B) Injection is allowed; semantics are what surprise teams.
  • C) Per-request behavior requires web scope or explicit lookup, not prototype-into-singleton alone.

Memory sentence: "Prototype into singleton = one instance captured at injection unless you use ObjectProvider or @Lookup."

Study: Book chapter

Question 15

A non-web integration test tries to create a @Scope("request") bean without a web context.

What is the likely result?

  • A) Context fails because request scope requires an active web/request context
  • B) The bean silently becomes singleton scope
  • C) Spring creates a new request scope per test method automatically
  • D) The bean is created as prototype instead
Answer & explanation

Correct answer: A

Request (and session) scopes need RequestContextListener / Spring MVC or WebFlux request context. Outside web context, scoped bean creation fails unless you use @Scope with a test MockHttpServletRequest or custom scope.

Why the other options are wrong:

  • B) Scope does not silently downgrade; missing context causes failure.
  • C) Tests do not auto-provide request context without @WebAppConfiguration or MockMvc setup.
  • D) Scope is not auto-converted to prototype on failure.

Memory sentence: "Request/session scopes need a live web request context — plain tests fail without faking it."

Study: Book chapter

Question 16

A singleton UserPreferencesService must see the current request's LocaleContext bean.

Which technique injects the current request-scoped bean into a singleton correctly?

@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class LocaleContext { }
  • A) Direct constructor injection of LocaleContext into the singleton without proxy
  • B) Mark UserPreferencesService as @Scope("request") instead
  • C) Use scoped proxy (proxyMode = TARGET_CLASS or INTERFACES) so the singleton holds a proxy delegating per request
  • D) Store LocaleContext in a static ThreadLocal manually and skip Spring scopes
Answer & explanation

Correct answer: C

Scoped proxies let shorter-lived beans be injected into longer-lived ones. The proxy resolves the correct instance per request (or session) at method invocation time.

Why the other options are wrong:

  • A) Direct injection captures one request instance at singleton init — wrong lifecycle.
  • B) Making the singleton request-scoped may be undesirable and changes service lifetime.
  • D) Manual ThreadLocal bypasses Spring's scoped proxy machinery and is error-prone.

Memory sentence: "Singleton needs request bean → scoped proxy (TARGET_CLASS or INTERFACES)."

Study: Book chapter

Question 17

A bean must log when it is fully constructed and again when the context shuts down.

Which callback pair is standard for init and destroy in a Spring-managed bean?

@Component
public class CacheWarmer {
@PostConstruct
void warm() { }

@PreDestroy
void shutdown() { }
}
  • A) @PostConstruct and @PreDestroy (JSR-250) or InitializingBean / DisposableBean
  • B) @Before and @After from JUnit
  • C) @Transactional start and rollback callbacks
  • D) main() and System.exit()
Answer & explanation

Correct answer: A

Spring supports @PostConstruct/@PreDestroy, initMethod/destroyMethod on @Bean, and InitializingBean/DisposableBean. These run at container-managed lifecycle points.

Why the other options are wrong:

  • B) JUnit annotations are for tests, not bean lifecycle in the container.
  • C) Transaction callbacks relate to transaction boundaries, not general bean init/destroy.
  • D) Not container lifecycle hooks.

Memory sentence: "Bean lifecycle hooks: @PostConstruct / @PreDestroy or @Bean(initMethod, destroyMethod)."

Study: Book chapter

Question 18

A @Component class (not @Configuration) contains two @Bean methods that call each other.

What is true about inter-@Bean method calls in this @Component class?

  • A) They behave identically to @Configuration full mode with CGLIB singleton enforcement
  • B) Spring lite @Bean mode does not proxy inter-method calls — each call may produce a new instance
  • C) Inter-@Bean calls are forbidden and cause compilation failure
  • D) Only @Repository classes can host @Bean methods
Answer & explanation

Correct answer: B

@Bean in @Component uses lite configuration (no CGLIB subclass proxy for @Bean inter-calls). Calling one @Bean method from another bypasses the container and may create duplicate instances.

Why the other options are wrong:

  • A) Full proxy semantics require @Configuration, not plain @Component.
  • C) It is legal but semantically different from full configuration mode.
  • D) Any @Component can declare @Bean methods in lite mode.

Memory sentence: "@Bean inside @Component = lite mode; inter-method calls are not container-proxied."

Study: Book chapter

Question 19

A new Spring Boot application needs component scanning, auto-configuration, and Spring Boot configuration property support.

Which combination does @SpringBootApplication meta-annotate?

@SpringBootApplication
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
  • A) @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan (with optional scan customization)
  • B) Only @ComponentScan and @EnableWebMvc
  • C) @Configuration, @EnableScheduling, and @EnableJpaRepositories
  • D) @SpringBootConfiguration and @Profile("default") only
Answer & explanation

Correct answer: A

@SpringBootApplication combines @SpringBootConfiguration (specialized @Configuration), @EnableAutoConfiguration, and @ComponentScan on the application class package.

Why the other options are wrong:

  • B) @EnableWebMvc is not part of @SpringBootApplication; Boot auto-configures MVC.
  • C) Scheduling and JPA repos require their own enable annotations when needed.
  • D) It includes auto-configuration and component scanning, not just @SpringBootConfiguration.

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

Study: Book chapter

Question 20

A custom auto-configuration should register a MetricsExporter only when the class io.micrometer.core.MeterRegistry is on the classpath.

Which condition annotation is appropriate?

@AutoConfiguration
@ConditionalOnClass(MeterRegistry.class)
public class MetricsExportAutoConfiguration {
@Bean
MetricsExporter metricsExporter(MeterRegistry registry) { ... }
}
  • A) @ConditionalOnMissingClass("io.micrometer.core.MeterRegistry")
  • B) @Profile("metrics")
  • C) @ConditionalOnClass(MeterRegistry.class)
  • D) @ConditionalOnBean(MeterRegistry.class) only, with no classpath check
Answer & explanation

Correct answer: C

@ConditionalOnClass guards auto-config based on classpath presence (using string name or class reference with care for missing classes). @ConditionalOnBean checks existing beans, not classpath alone.

Why the other options are wrong:

  • A) That condition activates when the class is absent — opposite intent.
  • B) Profiles are orthogonal to classpath conditions.
  • D) @ConditionalOnBean does not replace a classpath guard; both may combine but the question asks for classpath detection.

Memory sentence: "Classpath present → @ConditionalOnClass; bean already defined → @ConditionalOnBean."

Study: Book chapter

Question 21

Spring Boot 3 registers auto-configuration classes differently than older META-INF/spring.factories entries.

Where should Boot 3 auto-configuration classes be listed?

  • A) Only in application.properties under spring.auto.configure
  • B) In META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
  • C) In META-INF/services/java.sql.Driver
  • D) Only via @ComponentScan on the auto-config package
Answer & explanation

Correct answer: B

Spring Boot 2.7+ introduced AutoConfiguration.imports; Boot 3 uses it instead of spring.factories for auto-config class registration.

Why the other options are wrong:

  • A) No such standard property lists auto-config classes.
  • C) JDBC driver service files are unrelated to Spring Boot auto-configuration registration.
  • D) Auto-config is imported by Boot via imports file and conditions, not only component scan.

Memory sentence: "Boot 3 auto-config registration → META-INF/spring/...AutoConfiguration.imports."

Study: Book chapter

Question 22

Operations needs the default Actuator health endpoint URL on a Boot web app with no custom management context path.

What is the default URL for the health endpoint when exposed via the web?

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

Correct answer: D

By default, Actuator web endpoints live under /actuator with endpoint id appended: /actuator/health. Exposure also depends on management.endpoints.web.exposure.include.

Why the other options are wrong:

  • A) /health is common in apps but not the Boot Actuator default base path.
  • B) /api/health is application-specific, not Actuator default.
  • C) /status is not the default Actuator health path.

Memory sentence: "Default Actuator base path is /actuator → health is /actuator/health."

Study: Book chapter

Question 23

A security-conscious team wants only health and info exposed over HTTP in production.

Which property configuration achieves selective web exposure?

  • A) management.endpoints.web.exposure.include=health,info
  • B) management.server.port=0
  • C) spring.actuator.enabled=false
  • D) server.port=-1
Answer & explanation

Correct answer: A

management.endpoints.web.exposure.include controls which actuator endpoints are exposed on the web. Use exclude for deny lists or include=* with caution.

Why the other options are wrong:

  • B) Port 0 assigns a random port but does not select which endpoints are exposed.
  • C) Disabling actuator entirely is broader than selective exposure.
  • D) Invalid/main server port setting; unrelated to endpoint exposure selection.

Memory sentence: "Expose specific Actuator endpoints → management.endpoints.web.exposure.include."

Study: Book chapter

Question 24

A library auto-config defines a default ObjectMapper bean, but the application already provides its own @Bean ObjectMapper.

With @ConditionalOnMissingBean(ObjectMapper.class) on the auto-config @Bean, what happens?

@Configuration
public class JacksonAutoConfiguration {
@Bean
@ConditionalOnMissingBean(ObjectMapper.class)
ObjectMapper objectMapper() { return new ObjectMapper(); }
}
  • A) Both beans are registered and @Primary decides
  • B) Auto-config always overrides user beans
  • C) The auto-configured ObjectMapper is skipped because a bean of that type already exists
  • D) Context fails due to duplicate bean definitions
Answer & explanation

Correct answer: C

@ConditionalOnMissingBean prevents auto-config from registering a default when the user (or another config) already defined that bean type.

Why the other options are wrong:

  • A) The condition avoids duplicate registration rather than creating two competing beans.
  • B) User beans take precedence; auto-config backs off.
  • D) Backing off prevents the duplicate definition failure.

Memory sentence: "@ConditionalOnMissingBean = auto-config yields when you already defined the bean."

Study: Book chapter

Question 25

A project adds spring-boot-starter-data-jpa without specifying individual Hibernate or JDBC artifact versions.

How does Spring Boot determine compatible dependency versions?

  • A) Maven Central latest version of each artifact at build time
  • B) Dependency versions are managed by the Spring Boot BOM imported via the starter parent or dependencyManagement
  • C) Versions must be declared explicitly in every pom.xml dependency
  • D) Only Gradle projects get version management; Maven does not
Answer & explanation

Correct answer: B

Spring Boot starters import the Boot BOM which pins tested versions for transitive dependencies. You omit version numbers for managed coordinates.

Why the other options are wrong:

  • A) Boot does not resolve to arbitrary latest; it uses curated BOM versions.
  • C) Explicit versions are optional for BOM-managed dependencies.
  • D) Both Maven and Gradle support Boot dependency management.

Memory sentence: "Boot starters + BOM = curated compatible versions without manual version pins."

Study: Book chapter

Question 26

Two startup hooks exist: ApplicationRunner and CommandLineRunner. Both are @Bean methods with @Order annotations.

When do these runners execute relative to the application being ready to serve traffic?

  • A) Before the ApplicationContext is refreshed
  • B) Only after a manual call from main after SpringApplication.run returns
  • C) During bean registration, before any beans are instantiated
  • D) After context refresh/start completes, as part of application startup before SpringApplication.run returns
Answer & explanation

Correct answer: D

Runners execute after the context is up and beans are initialized, as a final startup phase. @Order controls relative ordering among runners.

Why the other options are wrong:

  • A) Context must be refreshed first; runners run after startup infrastructure is ready.
  • B) They run automatically during startup, not only on manual invocation after run returns.
  • C) They run after bean creation, not during registration.

Memory sentence: "Runners fire after context startup completes, ordered by @Order, before run() returns."

Study: Book chapter

Question 27

A large monolith has slow startup because hundreds of unused beans initialize eagerly.

Which setting enables lazy initialization of beans by default in Spring Boot?

# application.properties
spring.main.lazy-initialization=true
  • A) spring.main.lazy-initialization=true
  • B) spring.jpa.open-in-view=false
  • C) management.endpoints.enabled-by-default=false
  • D) server.tomcat.lazy=true
Answer & explanation

Correct answer: A

spring.main.lazy-initialization=true tells Boot to create beans lazily unless marked @Lazy(false) or eagerly required. It can delay failures and reduce startup work.

Why the other options are wrong:

  • B) OSIV affects persistence session length in web apps, not global bean lazy init.
  • C) Controls actuator endpoint defaults, not bean initialization timing.
  • D) Not a standard Spring Boot property for bean laziness.

Memory sentence: "Global lazy beans in Boot → spring.main.lazy-initialization=true."

Study: Book chapter

Question 28

A feature flag property features.export.enabled=true must gate an auto-configuration class.

Which condition is the best fit?

  • A) @ConditionalOnClass only
  • B) @Profile("export") only without a property
  • C) @ConditionalOnProperty(name = "features.export.enabled", havingValue = "true")
  • D) @Transactional
Answer & explanation

Correct answer: C

@ConditionalOnProperty matches environment property values (with havingValue, matchIfMissing). Ideal for feature flags alongside other conditions.

Why the other options are wrong:

  • A) Classpath checks do not read boolean feature properties.
  • B) Profiles can mirror flags but the question targets a specific property value.
  • D) @Transactional is unrelated to conditional auto-configuration.

Memory sentence: "Feature flags in auto-config → @ConditionalOnProperty with havingValue."

Study: Book chapter

Question 29

An HTTP GET /orders/42 should reach a controller method and return JSON.

What is the primary role of DispatcherServlet in this flow?

Client GET /orders/42
-> DispatcherServlet
-> HandlerMapping / Controller
-> HttpMessageConverter (JSON)
  • A) It compiles controller bytecode at runtime
  • B) It fronts the web layer, dispatching requests to handlers and rendering/converting responses
  • C) It replaces the need for controllers by mapping URLs to repositories directly
  • D) It manages JPA transactions for @RestController methods automatically
Answer & explanation

Correct answer: B

DispatcherServlet is Spring MVC's front controller. It resolves handler mappings, invokes controllers, and coordinates view resolution or message conversion.

Why the other options are wrong:

  • A) It is a servlet dispatcher, not a compiler.
  • C) Controllers (or handler methods) remain the mapped endpoints.
  • D) Transactions come from @Transactional AOP, not DispatcherServlet directly.

Memory sentence: "DispatcherServlet = front controller routing requests to handlers and response processing."

Study: Book chapter

Question 30

A REST endpoint must read page and size query parameters and the \{accountId\} path segment.

Which annotation pairing is correct?

@GetMapping("/accounts/{accountId}/transactions")
public List<Tx> list(
@PathVariable String accountId,
@RequestParam int page,
@RequestParam int size) { ... }
  • A) @RequestParam for accountId and @PathVariable for page
  • B) Both should use @RequestBody
  • C) Both should use @ModelAttribute only
  • D) @PathVariable for path segments and @RequestParam for query parameters — as shown
Answer & explanation

Correct answer: D

Path template variables use @PathVariable. Query string parameters use @RequestParam. The code shown follows Spring MVC conventions.

Why the other options are wrong:

  • A) Reverses the correct mapping for path vs query.
  • B) @RequestBody reads the HTTP body, not path or query parts on GET.
  • C) @ModelAttribute binds form/query to objects; not the idiomatic pair for explicit path + query params.

Memory sentence: "Path template → @PathVariable; query string → @RequestParam."

Study: Book chapter

Question 31

A controller throws OrderNotFoundException for missing resources. API clients should receive HTTP 404 with a JSON error body.

What is the cleanest MVC approach for mapping the exception to 404 consistently across controllers?

  • A) A @ControllerAdvice class with @ExceptionHandler(OrderNotFoundException.class) returning ResponseEntity or problem details
  • B) Add throws OrderNotFoundException to every controller signature only
  • C) Catch the exception in DispatcherServlet source code
  • D) Use @ResponseStatus on the controller class only
Answer & explanation

Correct answer: A

Global @ControllerAdvice + @ExceptionHandler centralizes exception-to-HTTP mapping. @ResponseStatus on exception classes is also valid; advice scales better for response bodies.

Why the other options are wrong:

  • B) Declaring throws does not set status codes or bodies for clients.
  • C) You should not modify framework servlet code.
  • D) Class-level @ResponseStatus on a controller does not handle thrown exceptions from handler methods.

Memory sentence: "Central HTTP error mapping → @ControllerAdvice + @ExceptionHandler."

Study: Book chapter

Question 32

Clients may request either JSON or XML for the same endpoint based on the Accept header.

Which mechanism selects the response format?

@GetMapping(value = "/reports", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public Report getReport() { ... }
  • A) Only @RequestParam("format") is supported natively
  • B) Random selection among registered HttpMessageConverter instances
  • C) Content negotiation via Accept header, produces, and registered message converters
  • D) The database column type decides JSON vs XML
Answer & explanation

Correct answer: C

Spring MVC content negotiation uses Accept, produces/consumes attributes, and converters (Jackson, JAXB, etc.) to choose representation.

Why the other options are wrong:

  • A) Format query params can be configured but native negotiation centers on Accept and converters.
  • B) Selection is deterministic based on negotiation rules.
  • D) Persistence types do not drive HTTP representation format.

Memory sentence: "Response format → content negotiation (Accept, produces, message converters)."

Study: Book chapter

Question 33

A POST endpoint accepts a JSON body that must be validated before the service layer runs.

Which controller signature triggers Bean Validation on the request body?

@PostMapping("/customers")
public ResponseEntity<Customer> create(@Valid @RequestBody CustomerRequest request) {
return ResponseEntity.ok(service.create(request));
}
  • A) Remove @Valid — validation runs automatically on all bodies
  • B) @Valid @RequestBody on the parameter plus validation annotations on CustomerRequest fields
  • C) Only @ModelAttribute triggers JSON validation
  • D) Annotate the service method with @Validated only, not the controller parameter
Answer & explanation

Correct answer: B

@Valid (or @Validated) on @RequestBody triggers JSR-380 validation on the object graph. Invalid requests typically raise MethodArgumentNotValidException handled by MVC advice.

Why the other options are wrong:

  • A) Validation does not run on request bodies without @Valid/@Validated.
  • C) @ModelAttribute is for form data binding, not typical JSON @RequestBody validation.
  • D) Service-level @Validated validates method parameters there, not the MVC layer request body unless also annotated at entry.

Memory sentence: "Validate JSON bodies at the controller with @Valid @RequestBody on DTOs carrying constraints."

Study: Book chapter

Question 34

Multiple @ControllerAdvice beans exist in the application.

How does Spring MVC apply them to controller exceptions and model attributes?

  • A) Only the advice in the same package as the controller applies
  • B) Advice beans are never used with @RestController
  • C) Random advice is chosen per request
  • D) Applicable advice beans are ordered (e.g., @Order) and consulted according to scope annotations like @ControllerAdvice(assignableTypes = OrderController.class)
Answer & explanation

Correct answer: D

@ControllerAdvice can be global or scoped by annotations/packages/assignable types. @Order/@Priority influences precedence when multiple advices apply.

Why the other options are wrong:

  • A) Advice is not limited to same package unless scoped that way.
  • B) @RestController is a @Controller specialization; advice applies.
  • C) Selection follows scope and ordering rules, not random choice.

Memory sentence: "@ControllerAdvice scope + @Order determine which global MVC advice handles a case."

Study: Book chapter

Question 35

A endpoint should accept only PUT requests to /inventory/\{sku\} and reject POST to the same path.

Which mapping is correct?

  • A) @PutMapping("/inventory/{sku}") on the handler method
  • B) @GetMapping("/inventory/{sku}") with manual verb check
  • C) @RequestMapping without method attribute on all verbs
  • D) @PatchMapping only for every update scenario
Answer & explanation

Correct answer: A

@PutMapping is a composed @RequestMapping(method = PUT) mapping restricting HTTP method and path.

Why the other options are wrong:

  • B) GET mapping rejects PUT at mapping level unless configured for multiple methods.
  • C) Unqualified @RequestMapping may accept all methods unless restricted.
  • D) PATCH is for partial updates; question asks specifically for PUT-only.

Memory sentence: "Restrict HTTP verb with composed mappings like @PutMapping, @PostMapping, etc."

Study: Book chapter

Question 36

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

Which controller attribute rejects non-JSON request bodies for that handler?

  • A) consumes = "application/json" on the mapping annotation
  • B) produces = "application/json" only
  • C) response = JSON
  • D) @Transactional(readOnly = true)
Answer & explanation

Correct answer: A

consumes specifies accepted request content types. produces specifies response types. Mismatch yields 415 Unsupported Media Type.

Why the other options are wrong:

  • B) produces governs response, not request body content type.
  • C) Not a Spring MVC mapping attribute.
  • D) Transactions do not filter content types.

Memory sentence: "Request body type gate → consumes; response type → produces."

Study: Book chapter

Question 37

A service method is annotated @Transactional and calls a repository save that throws a checked IOException.

What is the default rollback behavior for that checked exception?

@Transactional
public void archive(Order order) throws IOException {
repository.save(order);
storage.write(order.getId()); // may throw IOException
}
  • A) Transaction rolls back on any Exception including checked exceptions by default
  • B) Transaction commits unless the exception is unchecked (RuntimeException/Error) — checked exceptions do not roll back by default
  • C) Transactions always commit regardless of exceptions
  • D) Only @Rollback(false) on the repository controls commit
Answer & explanation

Correct answer: B

Default rollback applies to RuntimeException and Error. Checked exceptions commit by default unless configured with rollbackFor / noRollbackFor.

Why the other options are wrong:

  • A) Checked exceptions do not trigger rollback by default.
  • C) Unchecked exceptions do roll back by default.
  • D) Rollback rules come from @Transactional metadata, not repository-level @Rollback(false) alone in typical service transactions.

Memory sentence: "Default @Transactional rolls back on unchecked exceptions and Error, not checked exceptions."

Study: Book chapter

Question 38

A read-heavy report method only queries data and should avoid unnecessary dirty checks and flush operations.

Which @Transactional attribute helps optimize read-only work?

  • A) propagation = REQUIRES_NEW always
  • B) isolation = SERIALIZABLE always
  • C) timeout = 0
  • D) readOnly = true
Answer & explanation

Correct answer: D

readOnly = true hints to the persistence provider/JDBC layer that no modifications occur, enabling optimizations and, with some setups, routing to read replicas.

Why the other options are wrong:

  • A) REQUIRES_NEW starts a new transaction; not a read optimization hint.
  • B) SERIALIZABLE is the strictest isolation, not a read-only optimization.
  • C) timeout = 0 semantics depend on provider; not the standard read-only hint.

Memory sentence: "Read-only transactional queries → readOnly = true."

Study: Book chapter

Question 39

A controller returns an Order entity with lazy OrderLine children. The transaction ended in the service layer before JSON serialization.

What failure is most likely during response rendering?

  • A) LazyInitializationException when Jackson accesses uninitialized lazy collections outside the session
  • B) CSRF token mismatch
  • C) Duplicate bean definition for ObjectMapper
  • D) Actuator health down
Answer & explanation

Correct answer: A

Accessing lazy associations outside an open persistence context/session causes LazyInitializationException. Fix with fetch join, DTOs, @Transactional on read boundary, or open-in-view (with tradeoffs).

Why the other options are wrong:

  • B) CSRF is unrelated to JPA lazy loading.
  • C) Jackson/ObjectMapper bean issues are separate from lazy loading.
  • D) Actuator health is unrelated to entity graph serialization.

Memory sentence: "Lazy collections outside a transaction/session → LazyInitializationException."

Study: Book chapter

Question 40

A service calls repository.save(entity) then runs a bulk JPQL update in the same transaction before the method ends.

When are SQL changes from save likely flushed to the database relative to the bulk update?

  • A) Never — JPA only writes at transaction commit
  • B) Only after application restart
  • C) Before or by the time the bulk update executes if flush mode/synchronization requires pending changes visible — often at query execution or transaction commit depending on flush mode
  • D) Hibernate never flushes when using JPQL
Answer & explanation

Correct answer: C

Persistence context tracks changes; flush can occur before queries (auto flush) or at commit depending on FlushModeType. Pending save changes can be flushed so queries see consistent state.

Why the other options are wrong:

  • A) Flush can happen before commit, especially before queries with AUTO flush.
  • B) Persistence is runtime, not restart-dependent.
  • D) JPQL can trigger flush when auto-flush is enabled.

Memory sentence: "JPA flush synchronizes persistence context to DB before commit and often before queries."

Study: Book chapter

Question 41

A repository needs a query that returns DTO projections without loading full entities.

Which Spring Data JPA approach supports custom read models efficiently?

interface OrderSummaryRepository extends JpaRepository<Order, Long> {
@Query("select new com.acme.OrderSummary(o.id, o.total) from Order o where o.status = :status")
List<OrderSummary> findSummaries(@Param("status") String status);
}
  • A) Load all Order entities and map manually in a loop always
  • B) JPQL constructor expression in @Query returning a DTO/projection type
  • C) Only native SQL without @Query is allowed for DTOs
  • D) Call entityManager.clear() before every query
Answer & explanation

Correct answer: B

JPQL constructor expressions (for example select new com.acme.OrderSummary(o.id, o.total)) fetch only needed columns into DTOs. Interface-based projections and native queries are alternatives.

Why the other options are wrong:

  • A) Entity loading is heavier than constructor/projection queries.
  • C) JPQL @Query fully supports DTO constructor projections.
  • D) clear() detaches entities; unrelated to declaring DTO queries.

Memory sentence: "DTO reads in Spring Data → JPQL constructor expressions or interface/native projections."

Study: Book chapter

Question 42

Deleting a Parent entity should remove its Child rows from the database automatically.

Which JPA mapping attribute on the relationship establishes that behavior?

  • A) fetch = LAZY only
  • B) @Transactional on the child entity
  • C) @Version on the parent
  • D) cascade = CascadeType.REMOVE (or ALL including remove) on the parent-to-children association
Answer & explanation

Correct answer: D

CascadeType.REMOVE propagates remove operations to associated entities. Orphan removal (orphanRemoval = true) handles disassociated children depending on mapping.

Why the other options are wrong:

  • A) Fetch type controls loading, not delete propagation.
  • B) @Transactional on entity classes is not standard JPA delete cascading.
  • C) @Version enables optimistic locking, not cascaded delete.

Memory sentence: "Cascade delete children → cascade = REMOVE or orphanRemoval = true on the association."

Study: Book chapter

Question 43

Method A (transactional) calls Method B which must join the existing transaction or start one if none exists.

Which propagation setting on Method B matches that requirement?

  • A) Propagation.REQUIRED
  • B) Propagation.REQUIRES_NEW always
  • C) Propagation.NOT_SUPPORTED
  • D) Propagation.NEVER
Answer & explanation

Correct answer: A

REQUIRED joins the current transaction if present; otherwise creates a new one. It is the default propagation.

Why the other options are wrong:

  • B) REQUIRES_NEW suspends current and always creates a new transaction.
  • C) NOT_SUPPORTED suspends transactions.
  • D) NEVER fails if a transaction already exists.

Memory sentence: "Default join-or-create behavior → Propagation.REQUIRED."

Study: Book chapter

Question 44

Listing orders executes 1 query for orders and N additional queries for each order's customer.

What is the most targeted JPA fix for this N+1 select problem in the read path?

  • A) Disable logging
  • B) Increase heap size only
  • C) Use fetch join or @EntityGraph to load customers with orders in one query
  • D) Switch all entities to @Embeddable
Answer & explanation

Correct answer: C

N+1 arises from lazy loading per row. join fetch, @EntityGraph, or batch fetching (@BatchSize) reduce round trips.

Why the other options are wrong:

  • A) Logging changes do not alter query patterns.
  • B) Memory does not fix excessive query count.
  • D) Embeddable mapping redesign is unrelated to fetch strategy for associations.

Memory sentence: "N+1 fix → fetch join, @EntityGraph, or batch size — fetch associated data efficiently."

Study: Book chapter

Question 45

A Spring Boot app configures security with a custom SecurityFilterChain bean.

Where does SecurityFilterChain fit in the request processing pipeline?

HTTP request
-> SecurityFilterChain (JwtAuthFilter, AuthorizationFilter, ...)
-> DispatcherServlet
-> Controller
  • A) It replaces DispatcherServlet entirely
  • B) It runs only after controller methods return
  • C) It is a database connection pool configuration
  • D) It is a chain of servlet filters (including security filters) applied before the request reaches Spring MVC
Answer & explanation

Correct answer: D

Spring Security is filter-based. SecurityFilterChain defines ordered security filters (auth, authorization, etc.) in the servlet chain before dispatcher servlet handling.

Why the other options are wrong:

  • A) MVC still uses DispatcherServlet; security filters run earlier in the servlet chain.
  • B) Filters run on inbound requests before handlers and on the way out.
  • C) Unrelated to JDBC pooling.

Memory sentence: "Spring Security = servlet filter chain before DispatcherServlet."

Study: Book chapter

Question 46

User passwords must be stored hashed with a strong adaptive algorithm recommended by Spring Security.

Which encoder is the typical default choice in modern Spring Security apps?

  • A) Base64 encoding without salt
  • B) BCryptPasswordEncoder (or delegating factory producing bcrypt and upgrades)
  • C) MD5 without salt
  • D) Reversible AES encryption of plaintext passwords
Answer & explanation

Correct answer: B

Spring Security recommends strong password hashing like BCrypt (via PasswordEncoder beans). Passwords should be one-way hashed, not reversibly encrypted.

Why the other options are wrong:

  • A) Base64 is encoding, not secure password hashing.
  • C) MD5 is unsuitable for password storage.
  • D) Passwords should be hashed for verification, not reversibly encrypted for storage.

Memory sentence: "Store passwords with a strong PasswordEncoder — BCrypt via delegating encoder in Boot."

Study: Book chapter

Question 47

Method security should allow access only when the authenticated user has role ADMIN using SpEL.

Which annotation expresses that rule on a service method?

@Service
public class AdminService {
public void purgeCache() { }
}
  • A) @PreAuthorize("hasRole('ADMIN')")
  • B) @PermitAll on the method
  • C) @CrossOrigin("ADMIN")
  • D) @Profile("ADMIN")
Answer & explanation

Correct answer: A

@PreAuthorize applies SpEL authorization before method execution. hasRole automatically prefixes ROLE_ for role names.

Why the other options are wrong:

  • B) @PermitAll allows unrestricted access.
  • C) @CrossOrigin configures CORS, not authorization.
  • D) @Profile activates beans by environment profile, not user roles.

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

Study: Book chapter

Question 48

A stateless REST API uses JWT bearer tokens and no browser cookie session.

What is a common CSRF configuration for this API?

  • A) CSRF must remain fully enabled for all REST endpoints always
  • B) Disable database connection pooling
  • C) Disable CSRF for stateless token APIs because browsers do not auto-send bearer tokens cross-site
  • D) Enable form login with session cookies only
Answer & explanation

Correct answer: C

CSRF protects cookie-based session auth from cross-site requests. Stateless bearer-token APIs commonly disable CSRF while still requiring authentication on protected resources.

Why the other options are wrong:

  • A) Cookieless bearer APIs typically disable CSRF; cookie-based apps keep it enabled.
  • B) Connection pooling is unrelated to CSRF.
  • D) Form login with sessions is a different auth model than stateless JWT APIs.

Memory sentence: "Stateless bearer APIs often disable CSRF; cookie-session apps keep CSRF protection."

Study: Book chapter

Question 49

A browser SPA on https://app.example.com calls an API on https://api.example.com.

Which Spring component addresses cross-origin browser restrictions for allowed origins and methods?

  • A) CSRF token repository alone
  • B) CORS configuration (CorsConfigurationSource / http.cors)
  • C) BCrypt strength setting
  • D) @Transactional
Answer & explanation

Correct answer: B

CORS headers tell browsers which cross-origin requests are permitted. CSRF addresses cross-site request forgery for credentialed requests — related but different concerns.

Why the other options are wrong:

  • A) CSRF tokens do not replace CORS response headers for browser cross-origin access.
  • C) Password encoding is unrelated to browser origin policy.
  • D) Transactions are unrelated to HTTP CORS.

Memory sentence: "Browser cross-origin API access → CORS config; CSRF protects cookie-based mutating requests."

Study: Book chapter

Question 50

Spring Security 6 style configuration uses authorizeHttpRequests in a SecurityFilterChain bean.

What does requestMatchers("/public/**").permitAll() accomplish?

  • A) It disables all security filters globally
  • B) It encrypts responses for /public/**
  • C) It requires ADMIN role for public paths
  • D) It allows unauthenticated access to paths matching /public/** while other rules may still secure remaining endpoints
Answer & explanation

Correct answer: D

permitAll() grants access without authentication for matched requests. Other requestMatchers rules can require auth or roles for remaining paths.

Why the other options are wrong:

  • A) Security filters still run; authorization permits access for matched URLs.
  • B) No response encryption is implied.
  • C) permitAll is the opposite of requiring ADMIN.

Memory sentence: "permitAll() = anonymous access allowed for matched paths under authorization rules."

Study: Book chapter

Question 51

A team wants to test only a @RestController with MockMvc without loading the full database layer.

Which test slice annotation is appropriate?

@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mockMvc;
}
  • A) @WebMvcTest
  • B) @DataJpaTest
  • C) @SpringBootTest with full context always
  • D) @JdbcTest for every controller test
Answer & explanation

Correct answer: A

@WebMvcTest loads MVC infrastructure and the targeted web slice, mocking or omitting full data layer beans. Pair with @MockBean for controller dependencies.

Why the other options are wrong:

  • B) @DataJpaTest focuses on JPA/repositories, not MVC controllers.
  • C) Full context works but is slower and not the slice-focused choice.
  • D) @JdbcTest tests JDBC components, not REST controllers.

Memory sentence: "Controller-only MVC tests → @WebMvcTest + MockMvc."

Study: Book chapter

Question 52

An @WebMvcTest needs to replace the real OrderService bean with a stub in the test context.

Which annotation adds or replaces a bean in the Spring test context?

  • A) @Mock from Mockito alone on a field without Spring integration
  • B) @InjectMocks only
  • C) @MockBean on a field or @Bean method in the test configuration
  • D) @SpyBean is the only option and always calls real methods
Answer & explanation

Correct answer: C

@MockBean registers a Mockito mock/stub in the Spring ApplicationContext, replacing or adding beans for integration/slice tests.

Why the other options are wrong:

  • A) Plain @Mock does not register beans in the Spring context.
  • B) @InjectMocks constructs the test subject but does not publish mocks as Spring beans.
  • D) @SpyBean wraps real beans; @MockBean is the standard replacement stub.

Memory sentence: "Spring test context mock replacement → @MockBean, not plain Mockito @Mock."

Study: Book chapter

Question 53

Repository query methods should be tested against an in-memory database with JPA bootstrap but without the web layer.

Which annotation starts the right test slice?

  • A) @WebMvcTest
  • B) @DataJpaTest
  • C) @JsonTest only
  • D) @RestClientTest
Answer & explanation

Correct answer: B

@DataJpaTest configures JPA, typically with an embedded database, and loads repository beans without full application/web stack.

Why the other options are wrong:

  • A) @WebMvcTest excludes full JPA auto-config except what you mock.
  • C) @JsonTest targets JSON serialization only.
  • D) @RestClientTest targets REST clients, not JPA repositories.

Memory sentence: "Test repositories in isolation → @DataJpaTest with embedded DB."

Study: Book chapter

Question 54

An integration test must start the full application context and bind to a random HTTP port for REST calls.

Which @SpringBootTest configuration is correct?

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApiIntegrationTest {
@Autowired TestRestTemplate restTemplate;
}
  • A) webEnvironment = WebEnvironment.MOCK only
  • B) No webEnvironment attribute — port is always fixed 8080
  • C) Use @WebMvcTest with @AutoConfigureMockMvc only
  • D) webEnvironment = WebEnvironment.RANDOM_PORT
Answer & explanation

Correct answer: D

WebEnvironment.RANDOM_PORT starts the embedded server on a random port, enabling TestRestTemplate/WebTestClient against a real listener.

Why the other options are wrong:

  • A) MOCK uses mock servlet environment without a real listening port.
  • B) Random port requires explicit RANDOM_PORT configuration.
  • C) @WebMvcTest is a slice, not full integration with real port binding.

Memory sentence: "Full integration on real embedded port → @SpringBootTest(RANDOM_PORT)."

Study: Book chapter

Question 55

A @DataJpaTest modifies data in @Test methods against a shared embedded database.

What is the default transaction behavior for Spring Boot tests annotated with @Transactional at class level?

  • A) Each test runs in a transaction that rolls back after the test by default, leaving the database clean
  • B) Data always persists across tests without rollback
  • C) Tests never use transactions
  • D) Rollback occurs only on @SpringBootTest, never on slice tests
Answer & explanation

Correct answer: A

Spring Test @Transactional on tests rolls back by default after each test method, isolating database state. @Commit can override.

Why the other options are wrong:

  • B) Default test transaction rolls back unless @Commit or explicit persistence.
  • C) Test-managed transactions are common, especially for data tests.
  • D) @Transactional rollback applies to slice tests too when annotated.

Memory sentence: "Test class @Transactional → rollback after each test by default."

Study: Book chapter

Question 56

A developer chooses between MockMvc and TestRestTemplate for testing a secured REST endpoint.

Which statement best distinguishes them?

  • A) They are identical APIs with different package names
  • B) MockMvc always starts a network socket on port 443
  • C) MockMvc simulates MVC dispatch in-process without a real HTTP server; TestRestTemplate issues real HTTP calls against a running server
  • D) TestRestTemplate cannot send HTTP headers
Answer & explanation

Correct answer: C

MockMvc tests the servlet/MVC stack in memory (great for @WebMvcTest). TestRestTemplate/WebTestClient hit actual endpoints on embedded or real servers (RANDOM_PORT tests).

Why the other options are wrong:

  • A) APIs and runtime models differ significantly.
  • B) MockMvc does not open real network ports.
  • D) TestRestTemplate supports headers, entities, and full HTTP exchange.

Memory sentence: "In-process MVC → MockMvc; real HTTP to embedded server → TestRestTemplate/WebTestClient."

Study: Book chapter

Question 57

A @Service class calls its own @Transactional method from another method in the same class.

Why does the transactional advice often not apply to the internal call?

@Service
public class TransferService {
public void process() {
doTransfer(); // internal call
}

@Transactional
public void doTransfer() { ... }
}
  • A) Transactions never work in @Service classes
  • B) Spring AOP proxies intercept external calls; self-invocation bypasses the proxy and skips advice
  • C) Only @Repository methods can be transactional
  • D) Internal calls always run in REQUIRES_NEW automatically
Answer & explanation

Correct answer: B

Spring applies @Transactional via proxies. Calls through this inside the class bypass the proxy, so advice does not run. Fix by injecting self proxy, moving code, or AOP refactoring.

Why the other options are wrong:

  • A) Transactions work when calls go through the Spring proxy.
  • C) @Transactional is supported on services and other Spring beans.
  • D) Propagation is not auto-changed for self-invocation; advice is simply skipped.

Memory sentence: "Self-invocation skips the proxy — @Transactional on internal calls does not apply."

Study: Book chapter

Question 58

An application publishes a OrderPlacedEvent using ApplicationEventPublisher. No @Async listener is configured.

How are @EventListener methods invoked by default?

@Service
public class BillingService {
@Autowired ApplicationEventPublisher events;

public void placeOrder() {
events.publishEvent(new OrderPlacedEvent(...));
}
}

@Component
class OrderAuditListener {
@EventListener
void onOrderPlaced(OrderPlacedEvent event) { }
}
  • A) Always on a new thread pool thread
  • B) Only after server shutdown
  • C) Only if @EnableScheduling is present
  • D) Synchronously on the publishing thread unless configured otherwise (e.g., @Async)
Answer & explanation

Correct answer: D

Default Spring event listeners run synchronously in the caller thread. @Async on listener methods or async event multicaster enables async delivery.

Why the other options are wrong:

  • A) Async delivery requires explicit async configuration.
  • B) Events are runtime dispatch, not shutdown-triggered.
  • C) Scheduling enablement is unrelated to event listener threading.

Memory sentence: "Default Spring events are synchronous — async listeners need @Async support."

Study: Book chapter

Question 59

A method is annotated @Async but calls return immediately without running work on another thread.

What is the most common missing setup?

  • A) @EnableAsync is not enabled on a @Configuration class
  • B) @EnableWebMvc is missing
  • C) The method is private which is required for async
  • D) JUnit 4 is required
Answer & explanation

Correct answer: A

@Async requires @EnableAsync to configure Spring's async proxy/executor infrastructure. Public methods called through the Spring proxy are async-eligible.

Why the other options are wrong:

  • B) Web MVC enablement is unrelated to async method execution.
  • C) private methods are not proxied for @Async; public methods are required.
  • D) JUnit version does not control runtime async enablement.

Memory sentence: "@Async needs @EnableAsync and calls through the Spring proxy on public methods."

Study: Book chapter

Question 60

A scheduled job should start the next run a fixed time after the previous run finishes, not at fixed wall-clock intervals.

Which @Scheduled attribute expresses that behavior?

@Component
public class ReconciliationJob {
@Scheduled(fixedDelay = 5000)
public void reconcile() { }
}
  • A) cron = "*/1 * * * * *" only
  • B) initialDelay only
  • C) fixedDelay — delay measured from the end of the previous execution
  • D) fixedRate — interval measured from the start of each execution
Answer & explanation

Correct answer: C

fixedDelay waits after completion before scheduling the next run. fixedRate schedules at a steady rate from start times, which can overlap if runs are slow.

Why the other options are wrong:

  • A) Cron expresses calendar patterns, not completion-based delay semantics.
  • B) initialDelay only affects the first execution timing.
  • D) fixedRate measures from start to start, not end to start.

Memory sentence: "Wait after finish → fixedDelay; steady start-to-start interval → fixedRate."

Study: Book chapter


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