VMware Spring Certified Professional (2V0-72.22) — Questions and Answers
Question 1: In Spring Security, what is the default behavior when an authenticated user accesses a resource they are not authorized to view?
- The user is redirected to the login page
- The request is silently ignored
- A 403 Forbidden response is returned (Correct answer)
- A 401 Unauthorized response is returned
Correct answer: A 403 Forbidden response is returned
Spring Security returns HTTP 403 Forbidden for authenticated users who lack the required authority, while 401 Unauthorized is returned for unauthenticated requests.
Question 2: What is the primary role of the Inversion of Control (IoC) container in the Spring Framework?
- To manage database transactions and connections directly.
- To manage the lifecycle and configuration of application objects (beans), including their creation and dependency injection. (Correct answer)
- To handle incoming HTTP requests and route them to controllers.
- To compile Java source code into bytecode for the JVM.
Correct answer: To manage the lifecycle and configuration of application objects (beans), including their creation and dependency injection.
The core responsibility of the Spring IoC container is to manage the entire lifecycle of objects, known as beans. This includes instantiating the beans, configuring them, assembling their dependencies (Dependency Injection), and managing them through their complete lifecycle.
Question 3: Which Spring MVC component is responsible for converting Java objects to JSON in REST responses?
- HttpMessageConverter (Correct answer)
- ContentNegotiationManager
- ViewResolver
- HandlerAdapter
Correct answer: HttpMessageConverter
HttpMessageConverter implementations (specifically MappingJackson2HttpMessageConverter) serialize Java objects to JSON and deserialize JSON to Java objects.
Question 4: How do you bind a method's return value inside an @AfterReturning advice?
- Declare a parameter named 'result' automatically
- Annotate the parameter with @ReturnValue
- Set the 'returning' attribute on @AfterReturning to match a method parameter name (Correct answer)
- Use JoinPoint.getReturnValue()
Correct answer: Set the 'returning' attribute on @AfterReturning to match a method parameter name
The 'returning' attribute of @AfterReturning must match the advice method parameter name where the return value will be injected.
Question 5: How can you pass the thrown exception object into an @AfterThrowing advice method?
- Use a JoinPoint parameter
- Autowire ExceptionContext
- Declare a Throwable parameter with the same name as the 'throwing' attribute (Correct answer)
- Use @ExceptionHandler inside the aspect
Correct answer: Declare a Throwable parameter with the same name as the 'throwing' attribute
Setting the 'throwing' attribute on @AfterThrowing and declaring a matching parameter binds the thrown exception to that parameter.
Question 6: In Spring AOP, what proxy type is used by default when the target class does not implement any interface?
- JDK dynamic proxy
- Byte-buddy proxy
- Javassist proxy
- CGLIB subclass proxy (Correct answer)
Correct answer: CGLIB subclass proxy
When no interface is available, Spring AOP falls back to CGLIB to create a subclass-based proxy of the target class.
Question 7: What is the purpose of the @Primary annotation on a Spring bean?
- It prevents the bean from being overridden by child contexts
- It designates the preferred bean when multiple candidates exist for autowiring (Correct answer)
- It forces eager initialization of the bean
- It marks the bean as the highest-priority singleton
Correct answer: It designates the preferred bean when multiple candidates exist for autowiring
@Primary tells Spring to prefer this bean over other candidates when resolving an ambiguous autowiring dependency.
Question 8: When using programmatic transaction management, which Spring interface provides the core API?
- TransactionTemplate
- TransactionDefinition
- PlatformTransactionManager (Correct answer)
- TransactionStatus
Correct answer: PlatformTransactionManager
PlatformTransactionManager defines the core contract — getTransaction(), commit(), and rollback() — used by all Spring transaction managers.
Question 9: Which of the following is the default scope for a Spring bean if no scope is explicitly specified?
- session
- singleton (Correct answer)
- request
- prototype
Correct answer: singleton
In the Spring Framework, if no scope is specified for a bean, it defaults to the 'singleton' scope. This means the Spring IoC container creates exactly one instance of the bean, and that single instance is shared for all requests for that bean.
Question 10: What does Spring's @RequestBody annotation do when used on a controller method parameter?
- Maps the URL path to a Java object
- Injects the raw HttpServletRequest
- Reads the first query parameter from the URL
- Deserializes the HTTP request body into a Java object (Correct answer)
Correct answer: Deserializes the HTTP request body into a Java object
@RequestBody instructs Spring to read the HTTP request body and deserialize it into the annotated parameter type using the configured HttpMessageConverter.
Question 11: Which Spring Boot class provides programmatic access to which profiles are currently active?
- Environment (Correct answer)
- ProfileResolver
- ApplicationContext
- ConfigurableApplicationContext
Correct answer: Environment
The Environment interface exposes getActiveProfiles() and getDefaultProfiles() methods for programmatic profile inspection.
Question 12: In Spring, what does @DependsOn("beanA") guarantee when placed on beanB?
- beanA proxies all calls to beanB
- beanA is initialized before beanB (Correct answer)
- beanA is injected into beanB automatically
- beanA and beanB share the same scope
Correct answer: beanA is initialized before beanB
@DependsOn ensures the listed beans are fully initialized before the annotated bean is created.
Question 13: Which annotation marks a field as the primary key in a JPA entity?
- @GeneratedId
- @Id (Correct answer)
- @Key
- @PrimaryKey
Correct answer: @Id
@Id designates the field as the entity's primary key in JPA.
Question 14: What is the primary purpose of including the `spring-boot-starter-hateoas` dependency in a Spring Boot project?
- To add support for building hypermedia-driven RESTful services by easily creating links to related resources. (Correct answer)
- To provide a centralized mechanism for handling exceptions across all controllers.
- To enable automatic generation of OpenAPI (Swagger) documentation for the REST API.
- To configure content negotiation to support both JSON and XML response formats automatically.
Correct answer: To add support for building hypermedia-driven RESTful services by easily creating links to related resources.
The `spring-boot-starter-hateoas` dependency integrates Spring HATEOAS, a library for creating REST representations that follow the HATEOAS (Hypermedia as the Engine of Application State) principle. Its main feature is to make it easy to add hypermedia links to your API responses, guiding the client on what actions they can take next.
Question 15: Which file name pattern loads configuration only when the 'staging' profile is active?
- application.staging.properties
- staging-application.properties
- application-staging.properties (Correct answer)
- config-staging.properties
Correct answer: application-staging.properties
Profile-specific files follow the pattern application-{profile}.properties or application-{profile}.yml.
Question 16: Which Actuator endpoint exposes the current values of all @ConfigurationProperties beans?
- /actuator/config
- /actuator/env/props
- /actuator/properties
- /actuator/configprops (Correct answer)
Correct answer: /actuator/configprops
The /actuator/configprops endpoint lists all @ConfigurationProperties beans and their current effective values.
Question 17: What is the effect of annotating a Spring @RestController method with @ResponseStatus(HttpStatus.CREATED)?
- Sets the HTTP response status to 201 Created automatically (Correct answer)
- Creates a new HTTP session
- Throws an exception with status 201
- Requires the method to return a ResponseEntity
Correct answer: Sets the HTTP response status to 201 Created automatically
@ResponseStatus(HttpStatus.CREATED) instructs Spring to set the response status to 201 Created without needing to wrap the return value in ResponseEntity.
Question 18: What is the purpose of Spring HATEOAS in RESTful service development?
- Compressing REST responses for faster delivery
- Documenting REST APIs with OpenAPI specifications
- Securing REST endpoints with OAuth2
- Adding hypermedia links to REST responses so clients can discover actions dynamically (Correct answer)
Correct answer: Adding hypermedia links to REST responses so clients can discover actions dynamically
Spring HATEOAS provides tools to add hypermedia links (following the HATEOAS constraint of REST) to responses, enabling clients to navigate the API without hardcoded URLs.
Question 19: What is the purpose of the @CrossOrigin annotation on a Spring REST controller?
- Redirects requests to another origin
- Enables CORS for the annotated controller or method (Correct answer)
- Encrypts cross-origin requests
- Blocks requests from other domains
Correct answer: Enables CORS for the annotated controller or method
@CrossOrigin configures Cross-Origin Resource Sharing (CORS) headers, allowing browsers to make requests from different origins to the annotated endpoint.
Question 20: Which annotation on a Spring service method ensures it runs within an existing transaction or creates a new one if none exists?
- @Transactional(propagation = Propagation.NEVER)
- @Transactional(propagation = Propagation.SUPPORTS)
- @Transactional(propagation = Propagation.REQUIRES_NEW)
- @Transactional(propagation = Propagation.REQUIRED) (Correct answer)
Correct answer: @Transactional(propagation = Propagation.REQUIRED)
Propagation.REQUIRED (the default) joins an active transaction or starts a new one, ensuring the method always runs transactionally.
Question 21: What is the correct way to inject a property named 'app.max-retries' into a Spring bean field?
- @Inject("app.max-retries")
- @Value("app.max-retries")
- @Value("#{app.max-retries}")
- @Value("${app.max-retries}") (Correct answer)
Correct answer: @Value("${app.max-retries}")
@Value uses ${...} syntax for property placeholders to resolve values from the Environment.
Question 22: What is a 'phantom read' in database transactions?
- A query returning different sets of rows due to inserts by another concurrent transaction (Correct answer)
- Reading the same row twice and getting different values
- Reading a row that was deleted in the same transaction
- A read that fails due to a network partition
Correct answer: A query returning different sets of rows due to inserts by another concurrent transaction
A phantom read happens when a transaction re-executes a range query and sees new rows inserted by another committed transaction.
Question 23: What annotation is used to inject a value from application.properties into a Spring bean field?
- @Inject
- @Property
- @ConfigParam
- @Value (Correct answer)
Correct answer: @Value
@Value("${property.key}") reads the specified property from the environment and injects it into the annotated field.
Question 24: What does the @PostConstruct annotation indicate in a Spring-managed bean?
- The method runs inside a transaction after bean creation
- The method runs after all dependencies have been injected (Correct answer)
- The method runs before the bean's constructor
- The method runs when the context is refreshed
Correct answer: The method runs after all dependencies have been injected
@PostConstruct marks a method to be executed after dependency injection is complete, serving as an init callback.
Question 25: Which annotation is used to embed a non-entity object as columns inside an entity's table?
- @SecondaryTable
- @OneToOne with shared PK
- @Embedded / @Embeddable (Correct answer)
- @ElementCollection
Correct answer: @Embedded / @Embeddable
@Embeddable marks a class whose fields are stored in the owning entity's table, and @Embedded is placed on the field in the entity.
Question 26: Which Spring Security component is responsible for converting a successful authentication into a granted authority list?
- RoleHierarchyImpl
- GrantedAuthoritiesMapper (Correct answer)
- AuthoritiesPopulator
- GrantedAuthorityConverter
Correct answer: GrantedAuthoritiesMapper
GrantedAuthoritiesMapper maps the collection of GrantedAuthority objects after authentication, allowing you to add, remove, or transform authorities before they are stored in the SecurityContext.
Question 27: Which Spring Data JPA keyword in a method name generates an IS NULL condition?
- WhereNull
- EqualsNull
- IsNull (Correct answer)
- Null
Correct answer: IsNull
Appending `IsNull` or `Null` to a field name in a repository method name generates a WHERE field IS NULL clause.
Question 28: Which Spring feature allows you to conditionally register a bean based on the presence of a class on the classpath?
- @ConditionalOnProperty
- @EnableAutoConfiguration
- @Profile
- @ConditionalOnClass (Correct answer)
Correct answer: @ConditionalOnClass
@ConditionalOnClass registers the bean only when the specified class is present on the classpath.
Question 29: A REST service needs to support different versions of its API. A decision is made to include the version number in the URL path (e.g., `/api/v1/products` and `/api/v2/products`). Which of the following API versioning strategies does this describe?
- URI Path Versioning (Correct answer)
- Content Negotiation Versioning
- Query Parameter Versioning
- Custom Header Versioning
Correct answer: URI Path Versioning
URI Path Versioning is a common strategy where the API version is embedded directly into the URL path. This makes the version explicit and easy for clients to see and use. Other methods include passing the version as a query parameter, in a custom HTTP header, or via the `Accept` header (content negotiation).
Question 30: Which interface should a Spring Data JPA repository extend to get CRUD operations plus pagination support?
- PagingAndSortingRepository
- JpaRepository (Correct answer)
- CrudRepository
- SimpleJpaRepository
Correct answer: JpaRepository
JpaRepository extends PagingAndSortingRepository and CrudRepository, providing the full set including pagination, sorting, and batch operations.
Question 31: What does the @DataJpaTest annotation do by default regarding the database?
- Uses an in-memory embedded database and rolls back each test (Correct answer)
- Disables all transaction management
- Connects to the configured production datasource
- Starts a full Spring context including all beans
Correct answer: Uses an in-memory embedded database and rolls back each test
@DataJpaTest auto-configures an embedded in-memory database and wraps each test in a transaction that rolls back after the test.
Question 32: Adding spring-boot-starter-cache to your project auto-configures which default cache provider when no other provider is detected?
- ConcurrentMapCache (simple in-memory) (Correct answer)
- Caffeine
- Redis
- Ehcache
Correct answer: ConcurrentMapCache (simple in-memory)
When no specific cache provider is on the classpath, Spring Boot defaults to a simple ConcurrentMapCache-backed CacheManager.
Question 33: A developer is configuring a `SecurityFilterChain` and wants to ensure that all requests to endpoints starting with `/api/` require authentication, while requests to `/public/` are permitted for everyone. Which of the following configurations correctly implements this requirement?
- `.authorizeHttpRequests(auth -> auth.requestMatchers("/api/**").permitAll().requestMatchers("/public/**").authenticated())`
- `.authorizeHttpRequests(auth -> auth.requestMatchers("/public/**").permitAll().requestMatchers("/api/**").authenticated())` (Correct answer)
- `.authorizeHttpRequests(auth -> auth.requestMatchers("/api/**").authenticated().requestMatchers("/public/**").permitAll().anyRequest().denyAll())`
- `.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())`
Correct answer: `.authorizeHttpRequests(auth -> auth.requestMatchers("/public/**").permitAll().requestMatchers("/api/**").authenticated())`
Spring Security evaluates authorization rules in the order they are declared. To correctly implement the logic, the more specific rule (`/public/**` should be permitted) should be declared before the more general rule (`/api/**` should be authenticated). If `.anyRequest().authenticated()` were first, it would match all requests, and the `/public/**` rule would never be reached. The correct order is to permit the public endpoints first, then secure the API endpoints.
Question 34: Which annotation lets you define a named JPQL query directly on an entity class?
- @Query
- @JpqlQuery
- @NamedQuery (Correct answer)
- @NativeQuery
Correct answer: @NamedQuery
@NamedQuery is placed on the entity class and associates a JPQL string with a name that can be referenced at runtime.
Question 35: What is Hibernate?
- ORM framework (Correct answer)
- None of the Above
- Query Executer
- Database connectivity Tool
Correct answer: ORM framework
Explanation: <br> Hibernate is an Object/Relational Mapping (ORM) tool/solution that maps application domain model objects to relational database tables in Java settings. Hibernate is a Java Persistence API reference implementation (JPA).
Question 36: Which property prefix is used to configure the embedded Tomcat server's port in a Spring Boot application?
- spring.server.port
- embedded.server.port
- spring.tomcat.port
- server.port (Correct answer)
Correct answer: server.port
Spring Boot's server auto-configuration reads server.port (default 8080) to bind the embedded Tomcat.
Question 37: What does `@GeneratedValue(strategy = GenerationType.IDENTITY)` tell JPA?
- The application must assign the ID before saving
- A UUID is used as the key
- A sequence object generates the key
- The database auto-increments the primary key column (Correct answer)
Correct answer: The database auto-increments the primary key column
GenerationType.IDENTITY relies on the database's auto-increment capability to generate primary key values.
Question 38: What does `spring.jpa.show-sql=true` do in a Spring Boot application?
- Enables the H2 web console
- Prints entity schema on startup
- Activates SQL validation mode
- Logs all SQL statements generated by Hibernate to the console (Correct answer)
Correct answer: Logs all SQL statements generated by Hibernate to the console
Setting show-sql to true instructs Hibernate to print every generated SQL statement to standard output, useful for debugging.
Question 39: What is the primary benefit of marking a transactional method with `@Transactional(readOnly = true)` in a Spring Boot application using JPA and Hibernate?
- It ensures that the method will not participate in any existing transaction and will always run non-transactionally.
- It prevents the method from performing any write operations by throwing an exception if one is attempted.
- It automatically sets the transaction isolation level to `READ_UNCOMMITTED` for better performance.
- It signals to the underlying persistence provider to apply performance optimizations, such as disabling dirty checking. (Correct answer)
Correct answer: It signals to the underlying persistence provider to apply performance optimizations, such as disabling dirty checking.
The main purpose of the `readOnly = true` flag is to serve as a hint for the persistence provider. For Hibernate, this allows it to apply significant optimizations, most notably skipping the costly dirty checking process (as it doesn't need to track changes) and not maintaining snapshots of entities. This reduces memory usage and CPU overhead, improving performance for read-heavy operations.
Question 40: In a Spring Boot application, which annotation is considered the most generic stereotype for marking a class as a Spring-managed component?
- @Repository
- @Service
- @Component (Correct answer)
- @Controller
Correct answer: @Component
@Component is the generic stereotype annotation for any Spring-managed component. @Service, @Repository, and @Controller are specializations of @Component for more specific use cases in the service, persistence, and presentation layers, respectively.
Question 41: Which method in the BeanFactory interface retrieves a bean by type?
- getBean(Class<T> requiredType) (Correct answer)
- resolveBean(Type type)
- lookupBean(Class<T> type)
- getBean(String name)
Correct answer: getBean(Class<T> requiredType)
BeanFactory.getBean(Class<T>) looks up a bean by its type and returns it without needing to know its name.
Question 42: What is the default bean scope in a Spring ApplicationContext?
- singleton (Correct answer)
- session
- request
- prototype
Correct answer: singleton
Spring beans default to singleton scope, meaning one shared instance per ApplicationContext.
Question 43: Which HTTP method is idempotent but NOT safe, meaning it can modify server state but repeated calls produce the same result?
- DELETE
- PATCH
- PUT (Correct answer)
- POST
Correct answer: PUT
PUT is idempotent because calling it multiple times with the same payload results in the same server state, but it is not safe because it modifies the resource.
Question 44: Which Spring Boot feature automatically registers an endpoint at /actuator/health for REST APIs?
- Spring Boot Actuator (Correct answer)
- Spring Boot DevTools
- Spring Boot Admin
- Spring Data REST
Correct answer: Spring Boot Actuator
Spring Boot Actuator provides production-ready endpoints including /actuator/health, which reports the application's health status.
Question 45: What is the purpose of @DeclareParents in Spring AOP?
- To introduce new interfaces and default implementations to existing beans (Correct answer)
- To set the order of aspect execution
- To declare a parent aspect
- To mark a class as a pointcut library
Correct answer: To introduce new interfaces and default implementations to existing beans
@DeclareParents enables introduction, adding new interface implementations to existing target objects without modifying them.
Question 46: Which of the following correctly describes field injection vs. constructor injection in Spring?
- Field injection is preferred by the Spring team for production code
- Field injection makes dependencies mandatory; constructor injection makes them optional
- Both approaches are equivalent in terms of testability
- Constructor injection makes dependencies mandatory and supports immutability; field injection does not (Correct answer)
Correct answer: Constructor injection makes dependencies mandatory and supports immutability; field injection does not
Constructor injection enforces required dependencies at object creation and enables immutable (final) fields, which field injection cannot do.
Question 47: What does `orphanRemoval = true` do on a JPA relationship?
- Automatically deletes child entities when they are removed from the parent collection (Correct answer)
- Cascades persist to orphaned records
- Prevents deletion of the parent if it has children
- Lazily loads orphaned child records
Correct answer: Automatically deletes child entities when they are removed from the parent collection
With `orphanRemoval = true`, JPA deletes a child entity from the database when it is removed from the parent's collection.
Question 48: Which ApplicationContext implementation is best suited for a standalone Spring Boot application reading properties from the classpath?
- GenericWebApplicationContext
- AnnotationConfigApplicationContext (Correct answer)
- ClassPathXmlApplicationContext
- AnnotationConfigServletWebServerApplicationContext
Correct answer: AnnotationConfigApplicationContext
AnnotationConfigApplicationContext loads bean definitions from @Configuration classes without needing XML or a web server.
Question 49: Which Spring Boot feature allows you to override property values specifically for a test class?
- @ConfigurationProperties
- @TestPropertySource (Correct answer)
- @PropertySource
- @Profile('test')
Correct answer: @TestPropertySource
@TestPropertySource lets you specify properties files or inline key-value pairs that override application properties during a specific test.
Question 50: In a Spring Boot project, what triggers auto-configuration of AOP support?
- Adding @EnableAspectJAutoProxy manually
- Including spring-boot-starter-aop on the classpath (Correct answer)
- Setting spring.aop.enabled=true in application.properties
- Defining a @Configuration class
Correct answer: Including spring-boot-starter-aop on the classpath
spring-boot-starter-aop pulls in the AspectJ weaver and auto-configures AOP proxying without any extra annotation.
Question 51: What is the role of spring-boot-autoconfigure JAR in relation to individual starters?
- It replaces all starters and must be added separately
- It is only used by Spring Boot DevTools
- It contains the auto-configuration classes that starters activate when the right dependencies are present (Correct answer)
- It provides starter POMs but no actual configuration code
Correct answer: It contains the auto-configuration classes that starters activate when the right dependencies are present
spring-boot-autoconfigure holds the auto-configuration classes for hundreds of integrations; starters pull it in along with the required libraries to trigger the relevant conditions.
Question 52: Which PCD matches join points where the subject has a given annotation at the type level?
- @args
- @target
- @within (Correct answer)
- @annotation
Correct answer: @within
@within() matches join points in types that carry the specified annotation, whereas @annotation() matches methods carrying it directly.
Question 53: What is the purpose of the `@CacheEvict` annotation?
- Removes one or all entries from a named cache (Correct answer)
- Populates the cache on application startup
- Marks a method to bypass the cache entirely
- Configures the serialization strategy for cached objects
Correct answer: Removes one or all entries from a named cache
`@CacheEvict` triggers removal of specific entries (or all entries with `allEntries=true`) from the named cache when the annotated method is called.
Question 54: In Spring Boot's Kafka auto-configuration, what property sets the address of the Kafka broker?
- spring.kafka.broker-url
- spring.kafka.bootstrap-servers (Correct answer)
- spring.kafka.host
- spring.kafka.server-address
Correct answer: spring.kafka.bootstrap-servers
`spring.kafka.bootstrap-servers` configures the comma-separated list of host:port pairs used to establish the initial connection to the Kafka cluster.
Question 55: Which method of UriComponentsBuilder is used to construct a URI for a newly created resource in a Spring REST response?
- newUri().append(id).build()
- createPath(id).toUri()
- buildUri(id).toString()
- fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri() (Correct answer)
Correct answer: fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri()
UriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri() dynamically constructs the location URI from the current request context.
Question 56: What does the antMatcher (or requestMatchers in Spring Security 6) method do in an HttpSecurity configuration?
- It assigns roles to matching URL patterns automatically
- It applies the security configuration only to requests matching the specified pattern (Correct answer)
- It blocks all requests that do not match the pattern
- It enables anti-CSRF protection for matched URLs
Correct answer: It applies the security configuration only to requests matching the specified pattern
requestMatchers() (the Spring Security 6+ replacement for antMatcher) scopes the security rules that follow to only the HTTP requests whose paths match the given pattern.
Question 57: Which interface must be added alongside the BindingResult parameter in a controller method to capture validation errors without throwing an exception?
- The BindingResult parameter must immediately follow the @Valid parameter (Correct answer)
- BindingResult must be a separate method annotated with @ErrorHandler
- BindingResult is not supported in Spring Boot controllers
- BindingResult must be declared before the @Valid parameter
Correct answer: The BindingResult parameter must immediately follow the @Valid parameter
Spring MVC requires the BindingResult parameter to immediately follow the @Valid/@Validated parameter so that validation errors are captured rather than propagated as exceptions.
Question 58: Which annotation would you add to a bean so Spring always creates a fresh instance for every injection point?
- @Prototype
- @Transient
- @Singleton
- @Scope("prototype") (Correct answer)
Correct answer: @Scope("prototype")
@Scope("prototype") tells Spring to create a new bean instance each time it is requested.
Question 59: A developer creates a custom exception, `ResourceNotFoundException`, and wants any controller that throws it to automatically result in an HTTP `404 Not Found` response without using `@ExceptionHandler`. Which annotation should be placed on the `ResourceNotFoundException` class itself to achieve this?
- @ResponseStatus(HttpStatus.NOT_FOUND) (Correct answer)
- @ResponseBody
- @RequestMapping("/error")
- @ControllerAdvice
Correct answer: @ResponseStatus(HttpStatus.NOT_FOUND)
The `@ResponseStatus` annotation can be placed directly on an exception class. When that exception is thrown from a controller and not handled by any `@ExceptionHandler`, Spring will use the status code defined in the `@ResponseStatus` annotation to construct the HTTP response. This allows for a direct mapping between an exception type and an HTTP status.
Question 60: Which Spring annotation is a specialization of @Component intended for data-access classes?
- @Mapper
- @Repository (Correct answer)
- @Service
- @Controller
Correct answer: @Repository
@Repository marks DAO classes and additionally enables Spring's persistence exception translation.
VMware Spring Certified Professional (2V0-72.22)
Industry-recognized certification validating expertise in building enterprise applications using the Spring Framework and Spring Boot, covering core container management, AOP, data persistence, RESTful services, reactive programming, and production-ready features.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds