CertSafari

    Free Broadcom Spring Certified Professional Sample Questions

    35 free sample questions from our bank of 336+, covering every exam domain, with answers and detailed explanations. Updated August 2026.

    Domain 1: Spring Core

    Subdomain 1.1: Introduction to Spring Framework

    1.A user registration service in your Spring application needs to trigger an email notification and an audit log entry whenever a new user is created. To adhere to the Open/Closed Principle and avoid tightly coupling the registration service to the email and audit services, which Spring Framework feature should you utilize?

    1. A.Spring Expression Language (SpEL)
    2. B.ApplicationEventPublisher and @EventListener
    3. C.The Template Method pattern via JdbcTemplate
    4. D.BeanPostProcessor
    Show answer & explanation

    Correct answer: BApplicationEventPublisher and @EventListener

    • A. Spring Expression Language (SpEL) is a powerful expression language used for querying and manipulating an object graph at runtime or for configuration. It is not designed for component decoupling or application-level event handling.
    • B. ApplicationEventPublisher and @EventListener implement the Observer/Publisher-Subscriber pattern within the Spring context. This allows the registration service to publish an event without knowledge of the specific subscribers (email and audit services). This adheres to the Open/Closed Principle because new functionality (e.g., sending a welcome SMS) can be added by creating a new listener without modifying the existing registration service code.
    • C. JdbcTemplate utilizes the Template Method pattern to simplify database access and manage resource cleanup (like closing connections). While it reduces boilerplate code, it does not provide a mechanism for service-to-service communication or event-driven decoupling.
    • D. BeanPostProcessors are used by the Spring container to modify or wrap bean instances during their initialization phase (e.g., for creating proxies). They are part of the framework's lifecycle infrastructure, not for application-level business event propagation.

    Subdomain 1.1: Introduction to Spring Framework

    2.A legacy Spring application relies heavily on XML-based configuration. The engineering team wants to gradually migrate to a modern Java-based (@Configuration) approach. During the transition phase, they need a Java configuration class to load legacy bean definitions from an existing 'services.xml' file. Which Spring feature facilitates this hybrid configuration approach?

    1. A.Annotating the Java configuration class with @ImportResource("classpath:services.xml").
    2. B.Annotating the Java configuration class with @PropertySource("classpath:services.xml").
    3. C.Implementing the XmlBeanDefinitionReader interface in the Java configuration class.
    4. D.Using the @ComponentScan annotation and pointing it to the directory containing the XML file.
    Show answer & explanation

    Correct answer: AAnnotating the Java configuration class with @ImportResource("classpath:services.xml").

    • A. Correct. @ImportResource is the standard Spring annotation used within a @Configuration class to import bean definitions from one or more XML files. This allows legacy XML-defined beans to coexist with modern Java-based configuration, facilitating a gradual migration.
    • B. Incorrect. @PropertySource is used to load key-value pairs from property files (.properties or .xml in a specific properties format) into the Spring Environment. It is used for externalized configuration values, not for registering Spring bean definitions from a standard bean XML file.
    • C. Incorrect. XmlBeanDefinitionReader is a low-level Spring class used internally by ApplicationContext implementations to read XML bean definitions. It is not an interface meant to be implemented by a @Configuration class, nor is it the standard declarative way to handle hybrid configurations.
    • D. Incorrect. @ComponentScan is designed to detect and register classes annotated with Spring stereotype annotations (like @Component, @Service, @Repository) within specific packages. It does not parse or load XML configuration files.

    Subdomain 1.2: Java Configuration

    3.A developer has defined a bean named `myFactoryBean` that implements the `FactoryBean<MyService>` interface. When calling `context.getBean("myFactoryBean")`, Spring returns the `MyService` instance created by the factory. How can the developer retrieve the actual `FactoryBean` instance itself from the ApplicationContext?

    1. A.context.getBean("myFactoryBean", FactoryBean.class)
    2. B.context.getBean("&myFactoryBean")
    3. C.context.getBean("$myFactoryBean")
    4. D.context.getFactoryBean("myFactoryBean")
    Show answer & explanation

    Correct answer: Bcontext.getBean("&myFactoryBean")

    • A. Attempting to call context.getBean("myFactoryBean", FactoryBean.class) will cause Spring to look up the bean produced by the factory (MyService) and attempt to cast it to FactoryBean. Since MyService does not implement FactoryBean, this will result in a BeanNotOfRequiredTypeException. The class parameter does not trigger dereferencing.
    • B. Prefixing the bean name with an ampersand (&) is the standard Spring syntax for obtaining the FactoryBean instance itself rather than the object it creates. This is referred to as 'dereferencing' the FactoryBean.
    • C. The dollar sign ($) is not a valid prefix for dereferencing a FactoryBean. In Spring, the dollar sign is typically associated with property placeholder resolution (${...}) or Spring Expression Language (SpEL), but it serves no purpose in getBean name resolution for factories.
    • D. There is no getFactoryBean(String name) method in the ApplicationContext or BeanFactory interfaces. The correct API to retrieve the factory is the standard getBean method using the ampersand (&) prefix.

    Subdomain 1.2: Java Configuration

    4.A developer needs to retrieve all beans that implement a specific interface named `Plugin` from the `ApplicationContext` to iterate over them. Which method of the `ApplicationContext` should they use?

    1. A.`context.getBeansOfType(Plugin.class)`
    2. B.`context.findAllBeans(Plugin.class)`
    3. C.`context.getBean(Plugin[].class)`
    4. D.`context.resolveDependencies(Plugin.class)`
    Show answer & explanation

    Correct answer: A`context.getBeansOfType(Plugin.class)`

    • A. Correct. The `getBeansOfType(Class<T> type)` method is defined in the `ListableBeanFactory` interface, which `ApplicationContext` extends. It returns a `Map<String, T>` containing the names and instances of all beans in the context that match the specified type (including interface implementations), which can then be iterated over.
    • B. Incorrect. The Spring `ApplicationContext` or `BeanFactory` interfaces do not contain a method named `findAllBeans`.
    • C. Incorrect. The `getBean(Class<T> requiredType)` method is used to retrieve a single bean instance. While Spring supports autowiring collections or arrays into components, calling `getBean` with an array class type will attempt to find a single bean defined as that array type, rather than aggregating all beans of the component type.
    • D. Incorrect. `resolveDependencies` is not a public method available on the `ApplicationContext` interface for retrieving multiple beans by their type.

    Subdomain 1.3: Properties and Profiles

    5.A configuration class is annotated with `@PropertySource(value = {"classpath:/default.properties", "classpath:/custom.properties"})`. Both files contain the property `app.name`. Which value will be bound to the `Environment` for `app.name`?

    1. A.The value from default.properties because it is declared first in the array.
    2. B.The value from custom.properties because later property sources override earlier ones.
    3. C.An exception is thrown during context startup due to a duplicate property key.
    4. D.The values are merged into a comma-separated list.
    Show answer & explanation

    Correct answer: BThe value from custom.properties because later property sources override earlier ones.

    • A. Incorrect. Although Spring processes the property sources in the order they are listed in the array, the precedence rules specified in the documentation state that later sources take priority over earlier ones in the event of a name collision.
    • B. Correct. According to the Spring Framework API documentation for `@PropertySource`, in the case of a name collision (the same property name found in more than one file), the last one processed takes precedence. Since `custom.properties` follows `default.properties` in the array, its value will be the one bound to the environment.
    • C. Incorrect. Spring does not throw an exception when a property key exists in multiple property sources; it resolves the value based on the established precedence order of the sources.
    • D. Incorrect. Spring does not merge scalar property values into a comma-separated list; it resolves a single value based on which property source has the highest precedence.

    Subdomain 1.3: Properties and Profiles

    6.A developer is writing a custom component that needs to execute specific logic only if the `cloud` profile is active, but the `local` profile is NOT active. How can the developer programmatically check this condition using the `Environment` API?

    1. A.environment.acceptsProfiles(Profiles.of("cloud & !local"))
    2. B.environment.getActiveProfiles().contains("cloud") && !environment.getActiveProfiles().contains("local")
    3. C.environment.matchesProfile("cloud", "!local")
    4. D.environment.isProfileActive("cloud & !local")
    Show answer & explanation

    Correct answer: Aenvironment.acceptsProfiles(Profiles.of("cloud & !local"))

    • A. Correct. Since Spring 5.1, the `Profiles.of(String...)` factory method allows for the creation of profile expressions using logical operators such as '&' (AND), '|' (OR), and '!' (NOT). The `Environment.acceptsProfiles(Profiles)` method is then used to evaluate if the current environment matches that complex expression.
    • B. Incorrect. `environment.getActiveProfiles()` returns a `String[]` (array), and Java arrays do not have a `.contains()` method. While one could convert the array to a List or use a Stream to perform this check, it is a manual implementation and not the idiomatic approach provided by the Spring Environment API for profile expressions.
    • C. Incorrect. The Spring `Environment` API does not contain a method named `matchesProfile`.
    • D. Incorrect. The Spring `Environment` API does not contain a method named `isProfileActive`. Programmatic profile checks are handled via the `acceptsProfiles` method.

    Subdomain 1.5: Spring Bean Lifecycle

    7.You are migrating a legacy Spring application to annotation-based configuration. A bean `LegacyService` has an initialization method `startService()` and a destruction method `stopService()`. You cannot modify the source code of `LegacyService` to add annotations like `@PostConstruct` or `@PreDestroy`. How can you configure these lifecycle methods using Java configuration?

    1. A.Use `@Bean(initMethod = "startService", destroyMethod = "stopService")` when defining the bean.
    2. B.Create a custom `BeanPostProcessor` that calls these methods via reflection during the instantiation phase.
    3. C.Subclass `LegacyService` in your configuration, override the methods, and add `@PostConstruct` and `@PreDestroy` to the overridden methods.
    4. D.Register the bean using `@Component` and define a `Lifecycle` interface adapter to wrap the legacy class.
    Show answer & explanation

    Correct answer: AUse `@Bean(initMethod = "startService", destroyMethod = "stopService")` when defining the bean.

    • A. Correct. In Java configuration, the `@Bean` annotation supports `initMethod` and `destroyMethod` attributes. This is the standard mechanism for configuring lifecycle callbacks for third-party or legacy beans where you cannot modify the source code to add annotations like `@PostConstruct`. It allows you to point Spring to existing methods to be executed at the appropriate lifecycle stages.
    • B. Incorrect. A `BeanPostProcessor` is used for global processing or wrapping beans (proxies), not for individual bean lifecycle declarations. Using reflection within a custom post-processor is a complex, error-prone workaround that is unnecessary given Spring's built-in support for named lifecycle methods.
    • C. Incorrect. Subclassing a legacy class solely to add lifecycle annotations is a brittle and unnecessary approach. It complicates the object hierarchy and maintenance, whereas Java configuration is designed to handle this exact scenario through the `@Bean` annotation's attributes.
    • D. Incorrect. `@Component` requires the ability to annotate the class source, which is prohibited here. Additionally, while the `Lifecycle` interface is used for starting and stopping components in response to context signals, it is not the standard way to map specific initialization and destruction methods for a single bean.

    Subdomain 1.5: Spring Bean Lifecycle

    8.You have the following class: ```java @Service public class PaymentService { @Transactional public void processPayment() { /* ... */ } public void validate() { processPayment(); } } ``` When an external client calls `validate()`, you notice that the transaction is not starting. Why does this happen and how can you fix it?

    1. A.The proxy intercepts external calls, but internal method calls bypass the proxy; fix it by injecting `PaymentService` into itself or refactoring the transactional method to another bean.
    2. B.CGLIB proxies do not support `@Transactional`; fix it by making `PaymentService` implement an interface to force the use of JDK Dynamic Proxies.
    3. C.The `@Transactional` annotation is not inherited by internal methods; fix it by annotating `validate()` with `@Transactional` as well.
    4. D.Spring proxies only work on `public` methods, and `validate()` is likely being treated as package-private; fix it by explicitly declaring `validate()` as public.
    Show answer & explanation

    Correct answer: AThe proxy intercepts external calls, but internal method calls bypass the proxy; fix it by injecting `PaymentService` into itself or refactoring the transactional method to another bean.

    • A. Correct. Spring's AOP and declarative transaction management are implemented using proxies. When an external client calls a method, the call is intercepted by the proxy object, which starts the transaction before delegating to the actual bean. However, when a method within the bean calls another method on the same bean (self-invocation), it uses the 'this' reference rather than the proxy. This bypasses the transactional logic. To fix this, you can refactor the method into a separate bean or use self-injection to call the proxied version of the bean.
    • B. Incorrect. CGLIB proxies fully support `@Transactional` and are actually the default in Spring Boot. The issue is not the type of proxy being used, but the fact that internal calls bypass the proxy mechanism entirely, regardless of whether JDK Dynamic Proxies or CGLIB are employed.
    • C. Incorrect. While annotating `validate()` with `@Transactional` would result in a transaction being started for the `validate()` call, it doesn't address the underlying architectural issue of why `processPayment()` failed to start its own transaction. Furthermore, the issue is not about annotation inheritance, but about the proxy interception mechanism.
    • D. Incorrect. In the provided code snippet, the `validate()` method is already declared as `public`. While it is true that Spring proxies generally only support public methods, changing visibility would not solve the self-invocation issue described.

    Subdomain 1.4: Annotation-Based Configuration and Component Scanning

    9.What is the primary purpose of the `@Indexed` annotation (and the `spring-context-indexer` dependency) introduced in Spring Framework 5?

    1. A.To automatically create database indexes for JPA entities annotated with `@Component`.
    2. B.To generate a static metadata file at compile-time, reducing classpath scanning overhead and improving startup time.
    3. C.To index beans in a distributed cache for faster `@Autowired` resolution at runtime.
    4. D.To enforce a specific initialization order for beans during the ApplicationContext startup.
    Show answer & explanation

    Correct answer: BTo generate a static metadata file at compile-time, reducing classpath scanning overhead and improving startup time.

    • A. Incorrect. The `@Indexed` annotation is part of Spring's core component scanning optimization and is unrelated to database indexing, JPA entities, or persistence schema generation.
    • B. Correct. When the `spring-context-indexer` dependency is included, an annotation processor detects classes meta-annotated with `@Indexed` (which includes `@Component`, `@Service`, `@Repository`, etc.) and generates a `META-INF/spring.components` file at compile-time. This allows the application to bypass expensive classpath scanning during startup, significantly improving performance in large applications.
    • C. Incorrect. The `@Indexed` annotation does not store bean information in a distributed cache or affect the runtime resolution logic of `@Autowired`. It is purely a build-time optimization for identifying candidate components.
    • D. Incorrect. `@Indexed` does not control bean initialization order. Bean startup sequence is managed by the Spring IoC container based on dependency graphs, `@DependsOn` annotations, or lifecycle callbacks.

    Subdomain 1.6: Aspect Oriented Programming

    10.In the context of Spring AOP, which of the following best describes the primary architectural problems that Aspect-Oriented Programming is designed to solve?

    1. A.Code tangling and code scattering caused by cross-cutting concerns.
    2. B.Tight coupling between data access objects and the database schema.
    3. C.The inability to inject prototype-scoped beans into singleton-scoped beans.
    4. D.Performance bottlenecks caused by synchronous REST API calls.
    Show answer & explanation

    Correct answer: ACode tangling and code scattering caused by cross-cutting concerns.

    • A. Correct. Aspect-Oriented Programming (AOP) is specifically designed to address cross-cutting concerns (such as logging, security, and transaction management). Without AOP, these concerns lead to code tangling (mixing business logic with infrastructure code) and code scattering (duplicating the same logic across multiple modules). AOP allows these concerns to be modularized into aspects.
    • B. Incorrect. Tight coupling between DAOs and database schemas is an architectural issue related to data access design and Object-Relational Mapping (ORM). It is addressed by frameworks like Spring Data JPA or Hibernate, not by AOP.
    • C. Incorrect. This is a bean lifecycle and scoping issue within the Spring IoC container. It is typically resolved using Method Injection (e.g., @Lookup) or Scoped Proxies, but it is not the primary problem AOP was designed to solve.
    • D. Incorrect. Performance bottlenecks in synchronous communication are handled through asynchronous processing (@Async), reactive programming (Spring WebFlux), or caching mechanisms. While AOP can be used to measure performance (profiling), it does not solve the inherent bottlenecks of synchronous calls.

    Subdomain 1.6: Aspect Oriented Programming

    11.You want to dynamically add a new interface, `Auditable`, and its implementation, `DefaultAuditable`, to all existing beans in the `com.app.services` package without modifying their source code. Which of the following statements are true regarding how to achieve this using Spring AOP Introductions? (Select two)(Select 2)

    1. A.You must use the @DeclareParents annotation within an Aspect class.
    2. B.The value attribute of @DeclareParents should be set to "com.app.services.*+" to match the target beans.
    3. C.You must use the @Introduction annotation on the DefaultAuditable class.
    4. D.The defaultImpl attribute of @DeclareParents must point to the DefaultAuditable.class.
    5. E.Introductions in Spring AOP are implemented using bytecode manipulation via the AspectJ compiler, bypassing standard proxies.
    Show answer & explanation

    Correct answers: A, DYou must use the @DeclareParents annotation within an Aspect class.; The defaultImpl attribute of @DeclareParents must point to the DefaultAuditable.class.

    • A. Correct. In Spring AOP, introductions (also known as mixins) are declared using the @DeclareParents annotation. This annotation must be used on a field within a class annotated with @Aspect.
    • B. While this is a valid AspectJ type pattern, the use of '.*' vs '..*' depends on whether subpackages are included. In exam contexts, patterns are often treated as specific examples rather than fundamental truths of the mechanism itself, making A and D more definitive answers.
    • C. Incorrect. There is no @Introduction annotation in Spring AOP. The correct annotation for this functionality is @DeclareParents.
    • D. Correct. The defaultImpl attribute of @DeclareParents is used to specify the default implementation class for the interface being introduced. When a method from the introduced interface is called on the proxy, Spring delegates the call to an instance of this class.
    • E. Incorrect. Spring AOP is proxy-based (using JDK dynamic proxies or CGLIB). While it uses AspectJ syntax for pointcuts, it does not use the AspectJ compiler (ajc) or bytecode weaving by default. Introductions are managed by the proxy implementing the additional interface.

    Domain 2: Data Management

    Subdomain 2.1: Introduction to Spring JDBC

    12.A junior developer asks why Spring's JdbcTemplate wraps standard java.sql.SQLException into DataAccessException subclasses. What are the primary architectural benefits of this exception translation mechanism?(Select 2)

    1. A.It converts checked exceptions into unchecked (runtime) exceptions, reducing boilerplate try-catch blocks.
    2. B.It automatically retries failed database transactions without developer intervention.
    3. C.It provides a technology-agnostic exception hierarchy, allowing repositories to switch underlying persistence technologies without changing method signatures.
    4. D.It prevents SQL injection attacks by sanitizing the error messages returned to the client.
    5. E.It automatically rolls back the database state to the previous savepoint whenever a syntax error occurs.
    Show answer & explanation

    Correct answers: A, CIt converts checked exceptions into unchecked (runtime) exceptions, reducing boilerplate try-catch blocks.; It provides a technology-agnostic exception hierarchy, allowing repositories to switch underlying persistence technologies without changing method signatures.

    • A. Spring's JdbcTemplate translates the checked java.sql.SQLException into its own unchecked org.springframework.dao.DataAccessException hierarchy. This approach simplifies code by removing the necessity for mandatory try-catch blocks or 'throws' clauses in DAO and Service layers, allowing developers to focus on business logic rather than exception handling infrastructure.
    • B. The exception translation mechanism is solely responsible for mapping vendor-specific error codes to Spring's exception hierarchy. It does not provide any automatic retry logic for failed transactions; such functionality would require Spring Retry or custom handling logic.
    • C. Spring's DataAccessException hierarchy is designed to be technology-agnostic. By throwing generic exceptions like DataIntegrityViolationException regardless of whether the underlying persistence layer is JDBC, Hibernate, or JPA, the application code remains decoupled from specific database APIs, making it easier to switch persistence technologies without changing method signatures.
    • D. Exception translation is not a security feature. SQL injection prevention is typically handled through parameterized queries and prepared statements, not through the mechanism that maps database errors to Java exceptions.
    • E. Transaction management and rollback behavior are managed by Spring’s transaction infrastructure (like PlatformTransactionManager), not by the exception translation itself. While a RuntimeException triggers a rollback by default, the translation mechanism does not manage savepoints.

    Subdomain 2.1: Introduction to Spring JDBC

    13.Which exception is thrown by JdbcTemplate.queryForObject() if the executed query returns zero rows?

    1. A.NullPointerException
    2. B.EmptyResultDataAccessException
    3. C.IncorrectResultSizeDataAccessException
    4. D.NoResultException
    Show answer & explanation

    Correct answer: BEmptyResultDataAccessException

    • A. Incorrect. JdbcTemplate.queryForObject() does not throw NullPointerException when a query returns no rows. Spring's data access framework translates lower-level database errors and result set edge cases into the specific Spring DataAccessException hierarchy rather than relying on generic Java null-related exceptions.
    • B. Correct. When queryForObject() is executed and returns zero rows, Spring throws an EmptyResultDataAccessException. This is a specific subtype of IncorrectResultSizeDataAccessException used when at least one row was expected but none were found.
    • C. Incorrect. Although EmptyResultDataAccessException extends IncorrectResultSizeDataAccessException, the latter is the broader exception thrown when the result size does not match the expected count (such as returning two rows when one was expected). For the specific case of zero results, EmptyResultDataAccessException is the standard exception thrown.
    • D. Incorrect. NoResultException is an exception defined in the JPA (Jakarta/Java Persistence API) specification. Spring JDBC uses its own DataAccessException hierarchy and does not throw JPA-specific exceptions from JdbcTemplate.

    Subdomain 2.2: Transaction Management with Spring

    14.What is the exact behavior of Propagation.SUPPORTS in Spring Transaction Management?

    1. A.It always creates a new transaction, suspending any existing one.
    2. B.It executes within the current transaction if one exists; otherwise, it executes non-transactionally.
    3. C.It throws an exception if no transaction currently exists.
    4. D.It executes non-transactionally, suspending any existing transaction.
    Show answer & explanation

    Correct answer: BIt executes within the current transaction if one exists; otherwise, it executes non-transactionally.

    • A. This description matches the behavior of Propagation.REQUIRES_NEW, which always starts a new physical transaction and suspends any existing one. Propagation.SUPPORTS does not force the creation of a new transaction.
    • B. Correct. Propagation.SUPPORTS is flexible; it will participate in a transaction if one is already active, but if no transaction exists, it will execute non-transactionally without throwing an error.
    • C. This behavior is characteristic of Propagation.MANDATORY, which requires an existing transaction and throws an exception if the method is called outside of a transactional context.
    • D. This describes Propagation.NOT_SUPPORTED, which ensures the method runs without a transaction by suspending any current transaction. Propagation.SUPPORTS, conversely, will join an existing transaction if it exists.

    Subdomain 2.2: Transaction Management with Spring

    15.`OrderService.createOrder()` is annotated with `@Transactional(propagation = Propagation.REQUIRED)`. It calls `NotificationService.sendEmail()` which is annotated with `@Transactional(propagation = Propagation.NOT_SUPPORTED)`. What happens to the transaction context when `sendEmail()` is executing?

    1. A.`sendEmail()` executes within the same transaction as `createOrder()`.
    2. B.`createOrder()`'s transaction is suspended, and `sendEmail()` executes non-transactionally.
    3. C.`sendEmail()` throws an `IllegalTransactionStateException`.
    4. D.A new transaction is created specifically for `sendEmail()`.
    Show answer & explanation

    Correct answer: B`createOrder()`'s transaction is suspended, and `sendEmail()` executes non-transactionally.

    • A. Incorrect. `Propagation.NOT_SUPPORTED` explicitly instructs Spring to execute the method without a transaction context. If the propagation were `REQUIRED` or `SUPPORTS`, it would join the existing transaction.
    • B. Correct. According to Spring's transaction propagation rules, `NOT_SUPPORTED` suspends any existing transaction (such as the one started by `createOrder()`) and executes the method non-transactionally. Once the method completes, the original transaction is resumed.
    • C. Incorrect. `NOT_SUPPORTED` is designed to handle existing transactions gracefully by suspending them. An `IllegalTransactionStateException` is typically thrown by `MANDATORY` (when no transaction exists) or `NEVER` (when a transaction exists).
    • D. Incorrect. A new transaction would be created if the propagation mode was `REQUIRES_NEW`. `NOT_SUPPORTED` ensures that the method runs outside of any transaction context.

    Subdomain 2.3: Spring Boot and Spring Data for Backing Stores

    16.A developer notices that fetching a list of `Order` entities results in an N+1 query problem because the `items` collection in each `Order` is lazily loaded and accessed during serialization. How can the developer fix this issue declaratively within the Spring Data JPA repository interface?

    1. A.Use the @Fetch(FetchMode.JOIN) annotation directly on the repository method.
    2. B.Annotate the repository method with @EntityGraph(attributePaths = {"items"}).
    3. C.Set spring.jpa.default-fetch-size=EAGER in the application.properties file.
    4. D.Annotate the repository method with @Lazy(false).
    Show answer & explanation

    Correct answer: BAnnotate the repository method with @EntityGraph(attributePaths = {"items"}).

    • A. @Fetch(FetchMode.JOIN) is a Hibernate-specific annotation intended for use on entity mapping fields or properties. It cannot be applied directly to Spring Data JPA repository methods to change the fetch strategy for a specific query.
    • B. The @EntityGraph annotation allows developers to declaratively define how associations should be fetched for specific repository methods. By setting attributePaths to include "items", Spring Data JPA performs a JOIN FETCH in the underlying query, retrieving the items in a single trip to the database and solving the N+1 problem.
    • C. There is no 'spring.jpa.default-fetch-size=EAGER' property. In JDBC/Hibernate, 'fetch size' determines the number of rows retrieved per network trip from the result set, while 'fetch type' (Eager vs Lazy) determines when associated collections are loaded. These are distinct concepts.
    • D. The @Lazy annotation is part of the core Spring Framework and controls the lazy initialization of beans within the application context. It is not used to control the fetching behavior of JPA entity associations within a repository.

    Domain 3: Spring MVC

    Subdomain 3.2: REST Applications

    17.You need to invoke a secured third-party REST API using RestTemplate. Every request must include an 'Authorization: Bearer <token>' header. Instead of adding the header manually to every RestTemplate call, you want to apply it globally to a specific RestTemplate instance. How can you achieve this?(Select 2)

    1. A.Implement ClientHttpRequestInterceptor to add the header, and add it to the RestTemplate via setInterceptors().
    2. B.Use a RestTemplateCustomizer to add the interceptor during the RestTemplateBuilder configuration.
    3. C.Implement HandlerInterceptor and register it in a WebMvcConfigurer class.
    4. D.Set the default headers using restTemplate.setDefaultHeaders(headers).
    5. E.Annotate the RestTemplate bean definition with @RequestHeader("Authorization").
    Show answer & explanation

    Correct answers: A, BImplement ClientHttpRequestInterceptor to add the header, and add it to the RestTemplate via setInterceptors().; Use a RestTemplateCustomizer to add the interceptor during the RestTemplateBuilder configuration.

    • A. Correct. Implementing ClientHttpRequestInterceptor is the standard way to intercept and modify outbound client-side HTTP requests. By adding the interceptor to the RestTemplate via setInterceptors(), you ensure that the 'Authorization' header is applied to every request made by that specific instance.
    • B. Correct. In a Spring Boot context, using a RestTemplateCustomizer with RestTemplateBuilder is the recommended way to apply global configurations, such as adding interceptors, to RestTemplate instances during their creation.
    • C. Incorrect. HandlerInterceptor is used for intercepting incoming HTTP requests within the Spring MVC server-side pipeline. It cannot be used to modify outgoing client requests made by RestTemplate.
    • D. Incorrect. The RestTemplate class does not provide a setDefaultHeaders() method. Headers are typically added per-request or globally via an interceptor.
    • E. Incorrect. The @RequestHeader annotation is used to extract header values from incoming requests in Spring MVC controller methods. It cannot be used to configure headers for outbound requests made by a RestTemplate bean.

    Subdomain 3.2: REST Applications

    18.A client sends an HTTP PATCH request to '/api/users/42' with a JSON payload containing only the 'email' field to update the user's email address. The controller method is annotated with @PatchMapping("/api/users/{id}"). How should the method handle this partial update?

    1. A.Spring automatically fetches the existing user from the database, applies the JSON fields, and saves it before invoking the method.
    2. B.The method should accept a Map or a DTO with optional fields, retrieve the existing entity, manually apply the non-null fields, and save it.
    3. C.The method must be annotated with @PartialUpdate to instruct Hibernate to only update the provided fields.
    4. D.The @RequestBody annotation automatically merges the incoming JSON with the existing database record based on the @PathVariable ID.
    Show answer & explanation

    Correct answer: BThe method should accept a Map or a DTO with optional fields, retrieve the existing entity, manually apply the non-null fields, and save it.

    • A. Incorrect. Spring MVC maps the request to the handler method but does not automatically handle the persistence lifecycle or state merging. The developer is responsible for fetching the entity and applying updates.
    • B. Correct. To handle a PATCH request for partial updates in Spring, the application must explicitly implement the merge logic. This typically involves accepting the data as a Map or DTO, retrieving the current entity from the database, applying the provided changes, and then saving the result.
    • C. Incorrect. There is no @PartialUpdate annotation in the Spring Framework or Hibernate. While Hibernate has a @DynamicUpdate annotation to optimize SQL generation, it does not handle the merging of incoming JSON data into an entity.
    • D. Incorrect. The @RequestBody annotation is strictly for deserializing the HTTP request body into a Java object (typically via Jackson). It has no built-in functionality to merge data with existing database records.

    Subdomain 3.1: Web Applications with Spring Boot

    19.You are implementing a RESTful controller method to handle a GET request for a specific user by ID (/api/users/{id}). If the user is found, it should return the user details with an HTTP 200 OK status. If the user is not found, it must return an HTTP 404 Not Found status. Which of the following approaches correctly achieve this requirement?(Select 2)

    1. A.Return ResponseEntity<User> and use ResponseEntity.ok(user) if found, or ResponseEntity.notFound().build() if not found.
    2. B.Return User and annotate the method with @ResponseStatus(HttpStatus.OK). If not found, return null.
    3. C.Return User. If not found, throw a custom exception that is annotated with @ResponseStatus(HttpStatus.NOT_FOUND).
    4. D.Return Optional<User>. Spring MVC automatically translates an empty Optional to a 404 Not Found status.
    5. E.Return User. If not found, return a new User() object and Spring will automatically detect the empty object and return 404.
    Show answer & explanation

    Correct answers: A, CReturn ResponseEntity<User> and use ResponseEntity.ok(user) if found, or ResponseEntity.notFound().build() if not found.; Return User. If not found, throw a custom exception that is annotated with @ResponseStatus(HttpStatus.NOT_FOUND).

    • A. Correct. Using ResponseEntity provides explicit programmatic control over the HTTP response. ResponseEntity.ok(user) returns the user details with a 200 OK status, while ResponseEntity.notFound().build() specifically generates a 404 Not Found status.
    • B. Incorrect. Returning null in a @RestController method does not automatically trigger a 404 Not Found status. By default, it typically results in a 200 OK status with an empty response body.
    • C. Correct. Throwing a custom exception annotated with @ResponseStatus(HttpStatus.NOT_FOUND) is a standard Spring MVC pattern. When this exception is thrown, the ResponseStatusExceptionResolver handles it and returns the specified 404 status code.
    • D. Incorrect. While Spring MVC can handle Optional as a return type, an empty Optional does not automatically result in a 404 Not Found status. It usually defaults to a 200 OK or 204 No Content with an empty body, depending on the message converter configuration.
    • E. Incorrect. Returning a new (empty) User object does not indicate to Spring that the resource was missing. It will be serialized normally and returned with a 200 OK status.

    Subdomain 3.1: Web Applications with Spring Boot

    20.In a Spring Boot web application, how is the DispatcherServlet typically registered and initialized?

    1. A.It must be manually declared in a web.xml file located in src/main/webapp/WEB-INF.
    2. B.It is automatically registered by DispatcherServletAutoConfiguration when spring-webmvc is on the classpath.
    3. C.It is registered by implementing the WebMvcConfigurer interface and overriding the addServlets method.
    4. D.It is initialized by the embedded Tomcat server reading the @WebServlet annotation on the main class.
    Show answer & explanation

    Correct answer: BIt is automatically registered by DispatcherServletAutoConfiguration when spring-webmvc is on the classpath.

    • A. In a Spring Boot application, a web.xml file is not required or typically used. Spring Boot favors Java-based auto-configuration and programmatic registration over legacy XML configuration.
    • B. Spring Boot automatically registers the DispatcherServlet via DispatcherServletAutoConfiguration whenever the spring-webmvc dependency is detected on the classpath. This is the standard mechanism that eliminates the need for manual front-controller setup.
    • C. WebMvcConfigurer is used to customize MVC-level configuration such as interceptors, formatters, and view controllers. It does not handle the registration of the DispatcherServlet itself, and it does not contain an addServlets method.
    • D. The DispatcherServlet is not initialized via a @WebServlet annotation on the main application class. Instead, Spring Boot’s auto-configuration classes and the embedded container manager handle the servlet's registration programmatically.

    Domain 4: Testing

    Subdomain 4.2: Advanced Testing with Spring Boot and MockMVC

    21.What is the default behavior of the @DataJpaTest annotation in a Spring Boot application?

    1. A.It configures a full web server and loads all @Component beans.
    2. B.It replaces the application's configured DataSource with an embedded in-memory database.
    3. C.It disables transaction management for all test methods.
    4. D.It automatically starts a Testcontainers PostgreSQL instance.
    Show answer & explanation

    Correct answer: BIt replaces the application's configured DataSource with an embedded in-memory database.

    • A. Incorrect. @DataJpaTest is a 'slice' test annotation that focuses solely on JPA components. It does not load the full application context, start a web server, or include generic @Component, @Service, or @Controller beans.
    • B. Correct. By default, @DataJpaTest uses @AutoConfigureTestDatabase to replace the application's production DataSource with an embedded in-memory database (such as H2, HSQL, or Derby) if it is available on the classpath. This facilitates fast, isolated repository testing.
    • C. Incorrect. @DataJpaTest is meta-annotated with @Transactional, meaning it enables transaction management by default. Each test method runs in its own transaction, which is rolled back at the end of the test to ensure database state remains clean.
    • D. Incorrect. @DataJpaTest does not include automatic Testcontainers support. Using Testcontainers requires explicit configuration (e.g., @ServiceConnection or manual container setup); the default behavior is to use an embedded in-memory database.

    Subdomain 4.1: Testing Spring Applications

    22.A team is migrating a custom testing framework from JUnit 4 to JUnit 5. They need to implement custom logic that executes before each test method and can conditionally handle test execution exceptions. Which of the following JUnit 5 extension interfaces should they implement?(Select 2)

    1. A.BeforeEachCallback
    2. B.TestExecutionExceptionHandler
    3. C.MethodRule
    4. D.TestRule
    5. E.ParameterResolver
    Show answer & explanation

    Correct answers: A, BBeforeEachCallback; TestExecutionExceptionHandler

    • A. Correct. BeforeEachCallback is a JUnit 5 extension point that allows for custom logic to be executed before each test method, fulfilling the first requirement.
    • B. Correct. TestExecutionExceptionHandler is a JUnit 5 extension point specifically designed to intercept and conditionally handle exceptions thrown during test execution, fulfilling the second requirement.
    • C. Incorrect. MethodRule is a JUnit 4 interface and is not part of the JUnit 5 (Jupiter) extension model.
    • D. Incorrect. TestRule is a JUnit 4 concept used for rule-based test customization; JUnit 5 replaces this with the Extension API.
    • E. Incorrect. ParameterResolver is a JUnit 5 extension interface used to dynamically resolve parameters at runtime for constructors and test methods (Dependency Injection), but it does not handle execution timing or exception management.

    Subdomain 4.1: Testing Spring Applications

    23.A developer annotates an integration test class with @SpringBootTest and attempts to use a RestTemplate to make HTTP calls to http://localhost:8080/api/data. The test fails with a ConnectionRefused error because the embedded Tomcat server did not start. How should the developer fix this issue?

    1. A.Add @EnableWebMvc to the test class to force the web server to start.
    2. B.Change the annotation to @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) or DEFINED_PORT.
    3. C.Replace RestTemplate with MockMvc as embedded servers cannot be started in tests.
    4. D.Add the @AutoConfigureWebTestClient annotation to the test class.
    Show answer & explanation

    Correct answer: BChange the annotation to @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) or DEFINED_PORT.

    • A. Incorrect. @EnableWebMvc is used to manually enable Spring MVC configuration, but it does not control the lifecycle of the embedded servlet container in a Spring Boot test environment.
    • B. Correct. By default, @SpringBootTest uses WebEnvironment.MOCK, which loads a mock servlet environment and does not start a real embedded server. Setting webEnvironment to RANDOM_PORT or DEFINED_PORT starts the actual embedded Tomcat/Jetty/Undertow server, allowing RestTemplate to make real HTTP calls.
    • C. Incorrect. While MockMvc can be used to test the web layer without a running server, the statement that embedded servers cannot be started in tests is false; Spring Boot supports full integration tests with a running server.
    • D. Incorrect. @AutoConfigureWebTestClient is used to configure and inject a WebTestClient instance for testing reactive or non-reactive endpoints, but it does not automatically start the embedded server unless the webEnvironment is correctly set.

    Domain 5: Security

    Subdomain 5.1: Explain basic security concepts

    24.A developer is using the @Async annotation to process a long-running task in a background thread. Inside the asynchronous method, the code attempts to retrieve the current user's username via SecurityContextHolder.getContext().getAuthentication().getName(), but it throws a NullPointerException. What is the most appropriate Spring Security solution to resolve this issue?

    1. A.Change the SecurityContextHolder strategy to MODE_GLOBAL.
    2. B.Wrap the asynchronous executor with a DelegatingSecurityContextExecutor.
    3. C.Disable CSRF protection for the asynchronous method.
    4. D.Annotate the asynchronous method with @Secured("ROLE_USER").
    Show answer & explanation

    Correct answer: BWrap the asynchronous executor with a DelegatingSecurityContextExecutor.

    • A. Changing the SecurityContextHolder strategy to MODE_GLOBAL is not appropriate for a multi-user web application because it shares a single SecurityContext across all threads in the JVM. While MODE_INHERITABLETHREADLOCAL can propagate context to child threads, it does not work reliably with pooled threads (like those used by @Async).
    • B. The correct solution is to wrap the TaskExecutor used by the @Async mechanism with a DelegatingSecurityContextExecutor (or DelegatingSecurityContextAsyncTaskExecutor). This ensures that the SecurityContext from the calling thread is properly captured and propagated to the background thread executing the task.
    • C. CSRF (Cross-Site Request Forgery) protection is a web-tier security mechanism used to prevent unauthorized commands from being sent from a user that the web application trusts. It is entirely unrelated to the internal propagation of thread-local security context.
    • D. The @Secured annotation is used to enforce authorization (role-based access control) on a method. It does not handle the propagation of the SecurityContext across thread boundaries; if the context is null, the authorization check will fail or throw an exception anyway.

    Subdomain 5.1: Explain basic security concepts

    25.In the context of Spring Security's architecture, which interface is primarily responsible for evaluating if an already identified user has the necessary permissions to invoke a specific method or access a specific web request?

    1. A.AuthenticationManager
    2. B.UserDetailsService
    3. C.AuthorizationManager
    4. D.SecurityContextRepository
    Show answer & explanation

    Correct answer: CAuthorizationManager

    • A. The AuthenticationManager is responsible for the authentication process, which involves verifying the identity of a principal (e.g., validating credentials) and producing an Authentication object. It does not handle permission evaluation or access control.
    • B. UserDetailsService is used to load user-specific data (such as username, password, and granted authorities) during the authentication process. It is a data-retrieval strategy and does not make authorization decisions.
    • C. AuthorizationManager is the primary interface used in modern Spring Security architecture to evaluate whether an authenticated principal has the required permissions (authorities) to access a protected resource, such as a web request or a method invocation. It replaces the older AccessDecisionManager.
    • D. SecurityContextRepository is responsible for persisting the SecurityContext (which holds the Authentication object) between requests, typically using the HttpSession. It is not involved in evaluating permissions.

    Subdomain 5.3: Define Method-level Security

    26.A developer is securing a `DocumentService` and needs to ensure that only the owner of a document can update it. The ownership validation logic requires a database lookup and is encapsulated in a Spring bean named `securityChecker`. Which of the following is the correct way to apply this method-level security?

    1. A.@PreAuthorize("@securityChecker.isOwner(authentication, #documentId)")
    2. B.@PreAuthorize("securityChecker.isOwner(principal, #documentId)")
    3. C.@PreAuthorize("#securityChecker.isOwner(authentication, #documentId)")
    4. D.@PreAuthorize("hasPermission(#documentId, 'securityChecker.isOwner')")
    Show answer & explanation

    Correct answer: A@PreAuthorize("@securityChecker.isOwner(authentication, #documentId)")

    • A. Correct. In Spring Security's SpEL support, you can invoke a method on a managed Spring bean by prefixing the bean name with '@'. The 'authentication' object and the method parameter '#documentId' are correctly referenced to perform the ownership check.
    • B. Incorrect. To reference a Spring bean in a SpEL expression, the '@' prefix is required. Without it, the expression would look for a variable named 'securityChecker' in the evaluation context rather than a bean in the ApplicationContext.
    • C. Incorrect. The '#' prefix is used to reference variables or method parameters within the SpEL context (like #documentId). It is not the correct syntax for referencing a Spring bean.
    • D. Incorrect. The 'hasPermission' expression is designed for use with Spring Security's PermissionEvaluator interface. It is not intended for direct invocation of custom bean methods by passing the method name as a string.

    Subdomain 5.3: Define Method-level Security

    27.When `@EnableMethodSecurity(jsr250Enabled = true)` is configured in a Spring Boot application, which of the following annotations from the JSR-250 specification become active for method-level security?(Select 3)

    1. A.@RolesAllowed
    2. B.@PermitAll
    3. C.@DenyAll
    4. D.@Secured
    5. E.@PreAuthorize
    6. F.@RunAs
    Show answer & explanation

    Correct answers: A, B, C@RolesAllowed; @PermitAll; @DenyAll

    • A. Correct. `@RolesAllowed` is a standard JSR-250 annotation that is activated when `jsr250Enabled` is set to true. It is used to specify the roles permitted to access a method.
    • B. Correct. `@PermitAll` is part of the JSR-250 specification and becomes active when `jsr250Enabled` is true. It allows access to the annotated method for all users.
    • C. Correct. `@DenyAll` is a JSR-250 annotation enabled by the `jsr250Enabled` flag. It effectively blocks access to the annotated method for all callers.
    • D. Incorrect. `@Secured` is a Spring-specific annotation and is activated using the `securedEnabled = true` attribute of `@EnableMethodSecurity`, not the JSR-250 attribute.
    • E. Incorrect. `@PreAuthorize` is part of Spring Security's Pre/Post expression-based security annotations. It is activated via the `prePostEnabled` attribute (which is true by default in `@EnableMethodSecurity`).
    • F. Incorrect. Although `@RunAs` is part of the JSR-250 specification, it is not used by Spring Security for method-level authorization enforcement in this context.

    Subdomain 5.2: Use Spring Security to configure Authentication and Authorization

    28.You are building a stateless REST API that is consumed by a mobile application and a third-party backend service. Authentication is handled exclusively via JWTs passed in the `Authorization: Bearer` header. No browser-based clients or session cookies are used. Which of the following statements regarding CSRF protection are correct for this scenario?(Select 2)

    1. A.CSRF protection should be disabled because the API is stateless and does not rely on browser cookies for session tracking.
    2. B.CSRF protection must remain enabled to prevent token interception via cross-site scripting (XSS).
    3. C.You can disable CSRF by configuring `http.csrf(csrf -> csrf.disable())` in the `SecurityFilterChain`.
    4. D.CSRF protection is automatically disabled by Spring Security as soon as `oauth2ResourceServer` is configured.
    5. E.The mobile application must be configured to send a valid CSRF token in the `X-CSRF-TOKEN` header.
    Show answer & explanation

    Correct answers: A, CCSRF protection should be disabled because the API is stateless and does not rely on browser cookies for session tracking.; You can disable CSRF by configuring `http.csrf(csrf -> csrf.disable())` in the `SecurityFilterChain`.

    • A. Correct. CSRF (Cross-Site Request Forgery) protection is primarily designed for browser-based applications that use cookies for session management. Browsers automatically attach cookies to requests, making them vulnerable. Since this API is stateless and uses Bearer tokens in the Authorization header (which are not automatically attached by browsers), CSRF protection is redundant and can be safely disabled.
    • B. Incorrect. CSRF protection is not designed to prevent XSS (Cross-Site Scripting) or token interception. XSS is a separate vulnerability requiring different mitigations, such as proper input validation and Content Security Policies (CSP).
    • C. Correct. In modern Spring Security (Spring Security 6.x / Spring Boot 3.x), you disable CSRF protection within the SecurityFilterChain bean using the lambda DSL: `http.csrf(csrf -> csrf.disable())`.
    • D. Incorrect. Spring Security does not automatically disable CSRF protection simply by configuring `oauth2ResourceServer`. The developer must explicitly disable it if it is not needed for the specific architecture of the application.
    • E. Incorrect. Because the API is stateless and CSRF protection is typically disabled in this scenario, there is no need for a mobile application to send an `X-CSRF-TOKEN` header.

    Subdomain 5.2: Use Spring Security to configure Authentication and Authorization

    29.Which bean must be exposed in the Spring application context to allow Spring Security to understand that possessing `ROLE_ADMIN` automatically implies possessing `ROLE_USER`?

    1. A.GrantedAuthorityDefaults
    2. B.RoleHierarchy
    3. C.AccessDecisionManager
    4. D.AuthorizationManager
    Show answer & explanation

    Correct answer: BRoleHierarchy

    • A. GrantedAuthorityDefaults is used to configure or customize the default role prefix (typically 'ROLE_') in Spring Security. It does not define hierarchies or inheritance relationships between roles.
    • B. RoleHierarchy is the specific bean used to define role inheritance (e.g., 'ROLE_ADMIN > ROLE_USER'). By exposing this bean, Spring Security knows that a user with the higher role automatically possesses the lower roles listed in the hierarchy during authorization checks.
    • C. AccessDecisionManager is an older interface responsible for coordinating access control decisions via voters. It does not define or handle the semantics of role hierarchies itself.
    • D. AuthorizationManager is the modern Spring Security API for making authorization decisions. While it performs access checks, it relies on a RoleHierarchy bean to understand role inheritance rather than defining it itself.

    Domain 6: Spring Boot

    Subdomain 6.2: Spring Boot Properties and Autoconfiguration

    30.You are creating a custom auto-configuration that registers a `FeatureX` bean. This bean should only be created if the property `feature.x.enabled` is explicitly set to `true`. If the property is missing from the environment, the bean should NOT be created. Which annotation correctly implements this requirement?

    1. A.@ConditionalOnProperty(prefix="feature.x", name="enabled", havingValue="true", matchIfMissing=false)
    2. B.@ConditionalOnProperty(value="feature.x.enabled=true")
    3. C.@ConditionalOnExpression("${feature.x.enabled} == true")
    4. D.@Value("${feature.x.enabled:false}")
    Show answer & explanation

    Correct answer: A@ConditionalOnProperty(prefix="feature.x", name="enabled", havingValue="true", matchIfMissing=false)

    • A. Correct. This is the standard Spring Boot annotation for conditional configuration based on properties. The `prefix` and `name` attributes combine to check 'feature.x.enabled'. Setting `havingValue="true"` ensures the bean is only created when the property matches that value, and `matchIfMissing=false` (which is the default behavior) ensures the condition fails if the property is not defined at all.
    • B. Incorrect. The `@ConditionalOnProperty` annotation does not support an assignment-style syntax within the `value` or `name` attributes. The `value` attribute is an alias for `name` and expects the property key, not a 'key=value' string.
    • C. Incorrect. While `@ConditionalOnExpression` allows for SpEL (Spring Expression Language), it is less robust for this scenario. If the property is missing from the environment, the placeholder resolution `${feature.x.enabled}` will fail and cause an exception unless a default value is provided inside the expression. `@ConditionalOnProperty` is the idiomatic choice for simple property-based flags.
    • D. Incorrect. `@Value` is used for field or parameter injection to bring property values into a bean. It has no mechanism to conditionally prevent the creation of the bean itself.

    Subdomain 6.2: Spring Boot Properties and Autoconfiguration

    31.In a Spring Boot 3.x application, a developer wants to create an immutable configuration properties class using a Java Record. How should the developer enable constructor binding for this Record?

    1. A.Annotate the Record with both @ConstructorBinding and @ConfigurationProperties.
    2. B.Simply annotate the Record with @ConfigurationProperties; Spring Boot 3 automatically uses constructor binding for Records.
    3. C.Annotate the Record's canonical constructor with @Autowired.
    4. D.Constructor binding is not supported for Java Records; a standard class with setters must be used.
    Show answer & explanation

    Correct answer: BSimply annotate the Record with @ConfigurationProperties; Spring Boot 3 automatically uses constructor binding for Records.

    • A. While @ConstructorBinding was required in earlier Spring Boot versions (or in cases with multiple constructors), Spring Boot 3.x simplifies the process. For classes or Records with a single parameterized constructor, @ConstructorBinding is no longer necessary and is redundant when @ConfigurationProperties is present.
    • B. Correct. In Spring Boot 3.x, the framework automatically detects the canonical constructor of a Java Record and applies constructor binding if the Record is annotated with @ConfigurationProperties. This makes Records the ideal mechanism for immutable configuration.
    • C. The @Autowired annotation is used for Spring's dependency injection container to inject beans. Configuration property binding is a separate process handled by the Binder API, and @Autowired is not used to map properties to constructors.
    • D. This is incorrect. Spring Boot 2.2+ introduced support for constructor binding, and Spring Boot 3.x specifically optimized the experience for Java Records to encourage immutability in configuration.

    Subdomain 6.3: Spring Boot Actuator

    32.You are implementing a custom Actuator endpoint to trigger a manual database synchronization. The endpoint should only be accessible via HTTP POST and should not be exposed over JMX. Which annotation combination is the most appropriate for this requirement?

    1. A.Annotate the class with @Endpoint(id = "dbsync") and the method with @PostMapping.
    2. B.Annotate the class with @RestController and the method with @PostMapping("/actuator/dbsync").
    3. C.Annotate the class with @WebEndpoint(id = "dbsync") and the method with @WriteOperation.
    4. D.Annotate the class with @JmxEndpoint(id = "dbsync", enable = false) and the method with @UpdateOperation.
    Show answer & explanation

    Correct answer: CAnnotate the class with @WebEndpoint(id = "dbsync") and the method with @WriteOperation.

    • A. @Endpoint(id = "dbsync") makes the endpoint available to both JMX and HTTP by default, which violates the requirement to exclude JMX. Furthermore, @PostMapping is a Spring MVC annotation; Actuator endpoints use specific operation annotations like @ReadOperation, @WriteOperation, or @DeleteOperation.
    • B. @RestController defines a standard Spring MVC web controller, not a Spring Boot Actuator endpoint. Using this approach bypasses the Actuator framework's management infrastructure, such as unified security, exposure management, and the base /actuator path.
    • C. @WebEndpoint restricts the custom endpoint to HTTP (Web) exposure only, specifically excluding JMX. Within the Actuator framework, @WriteOperation maps directly to an HTTP POST request, which is the standard method for operations that modify state or trigger actions like synchronization.
    • D. @JmxEndpoint restricts an endpoint's exposure exclusively to JMX, which is the opposite of the requirement. Additionally, @UpdateOperation is not a valid Spring Boot Actuator annotation; the correct annotation for modifying or POST-style operations is @WriteOperation.

    Subdomain 6.3: Spring Boot Actuator

    33.Which of the following are standard, built-in `Status` values provided by Spring Boot's `Health` object?(Select 3)

    1. A.UP
    2. B.DOWN
    3. C.OUT_OF_SERVICE
    4. D.WARNING
    5. E.MAINTENANCE
    6. F.DEGRADED
    Show answer & explanation

    Correct answers: A, B, CUP; DOWN; OUT_OF_SERVICE

    • A. UP is a standard, built-in Status value in Spring Boot Actuator's Health object. It indicates that the application or component is functioning properly and is available to receive traffic.
    • B. DOWN is a standard, built-in Status value used when a component or the application has suffered an unexpected failure or is unavailable. It is one of the four core default status constants.
    • C. OUT_OF_SERVICE is a standard, built-in Status value. It indicates that the component is temporarily taken out of service and should not be used, distinguishing it from a functional failure (DOWN).
    • D. WARNING is not a standard, built-in Status value in Spring Boot's Status class. While it may be used in monitoring systems, it is not one of the default constants (UP, DOWN, OUT_OF_SERVICE, UNKNOWN).
    • E. MAINTENANCE is not a built-in Status value provided out of the box by Spring Boot's Health object. Developers can define it as a custom status if required, but it is not standard.
    • F. DEGRADED is not a default built-in health status value in Spring Boot. Like other non-standard labels, it would require custom implementation and configuration to be used within the Actuator health system.

    Subdomain 6.1: Spring Boot Feature Introduction

    34.You are developing a Spring Boot application that includes the `spring-boot-starter-data-jpa` dependency. However, you want to manually configure the `DataSource` and `EntityManagerFactory` beans and prevent Spring Boot from automatically configuring them. How can you achieve this?

    1. A.Set `spring.data.jpa.enabled=false` in the `application.properties` file.
    2. B.Use `@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})` on the main class.
    3. C.Remove the `@EnableAutoConfiguration` annotation from the main class.
    4. D.Annotate your custom `DataSource` bean with `@Primary` and `@OverrideAutoConfiguration`.
    Show answer & explanation

    Correct answer: BUse `@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})` on the main class.

    • A. Incorrect. There is no standard Spring Boot property named `spring.data.jpa.enabled=false` to disable JPA auto-configuration. Auto-configuration behavior is controlled by configuration classes, not this specific property.
    • B. Correct. Using the `exclude` attribute of the `@SpringBootApplication` (or `@EnableAutoConfiguration`) annotation allows you to selectively disable specific auto-configuration classes. `DataSourceAutoConfiguration` is responsible for setting up the DataSource, and `HibernateJpaAutoConfiguration` is responsible for setting up the JPA EntityManagerFactory. By excluding both, you can provide your own bean definitions manually.
    • C. Incorrect. Removing `@EnableAutoConfiguration` (which is usually bundled within `@SpringBootApplication`) would disable all Spring Boot auto-configuration features, not just the JPA and DataSource components. This is not the recommended approach for targeting specific configurations.
    • D. Incorrect. `@Primary` is used to resolve ambiguity when multiple beans of the same type exist, but it does not stop Spring Boot from attempting to auto-configure its own beans. Furthermore, `@OverrideAutoConfiguration` is not a standard Spring Boot annotation used for this purpose.

    Subdomain 6.1: Spring Boot Feature Introduction

    35.Your Spring Boot application frequently fails to start in the CI/CD pipeline due to a custom `PortInUseException` thrown by a proprietary embedded server. You want to provide a clear, actionable error message in the console when this specific exception occurs, rather than a massive stack trace. Which of the following are valid steps or approaches to implement and register this custom analyzer?(Select 3)

    1. A.Implement the `FailureAnalyzer` interface and override the `analyze` method.
    2. B.Extend the `AbstractFailureAnalyzer<PortInUseException>` class and implement the `analyze` method.
    3. C.Annotate the analyzer class with `@ControllerAdvice` to catch the startup exception.
    4. D.Implement `ApplicationListener<ApplicationFailedEvent>` and call `System.exit()`.
    5. E.Register the analyzer using the Spring Boot SPI mechanism (e.g., `META-INF/spring.factories` or `META-INF/spring/org.springframework.boot.diagnostics.FailureAnalyzer.imports`).
    Show answer & explanation

    Correct answers: A, B, EImplement the `FailureAnalyzer` interface and override the `analyze` method.; Extend the `AbstractFailureAnalyzer<PortInUseException>` class and implement the `analyze` method.; Register the analyzer using the Spring Boot SPI mechanism (e.g., `META-INF/spring.factories` or `META-INF/spring/org.springframework.boot.diagnostics.FailureAnalyzer.imports`).

    • A. Implementing the `FailureAnalyzer` interface directly is the fundamental way to create a custom startup failure diagnostic. It requires overriding the `analyze(Throwable failure)` method to inspect the exception and return a `FailureAnalysis` object.
    • B. Extending `AbstractFailureAnalyzer<T>` is the recommended approach for handling specific exception types. This abstract class provides type-safe filtering, ensuring your `analyze` method is only called when an exception of the specified type (or its cause) is encountered.
    • C. The `@ControllerAdvice` annotation is used for handling exceptions that occur during the processing of web requests in Spring MVC or WebFlux. It is not functional during the application bootstrap phase where `FailureAnalyzer` operates.
    • D. While `ApplicationFailedEvent` is published when startup fails, it is used for general event-based reactions. It does not integrate with Spring Boot's failure analysis reporting system, which is specifically designed to suppress stack traces in favor of readable messages.
    • E. Spring Boot discovers custom failure analyzers using the Service Provider Interface (SPI) mechanism. You must register your implementation class in a metadata file, typically `META-INF/spring.factories` under the key `org.springframework.boot.diagnostics.FailureAnalyzer`, to ensure it is loaded during the bootstrap process.

    Want the full experience?

    These are just samples. Practice the full Broadcom Spring Certified Professional question bank in quiz mode — free, no signup, with domain practice and exam simulation.