Sitemap
Javarevisited

A humble place to learn Java and Programming better.

50 Free Spring Professional Developer Practice Questions [Mock Test]

27 min readJan 9, 2023

--

50 Free Spring Framework Practice Questions for Java Programmers

Hello guys, preparing for IT certification like Oracle’s Java certification or VMware's Spring Professional Certification required a lot of hard-work. I have seen many experienced Java developers failing these certifications and losing money and time due to over-confidence and lack of preparation.

Now that this exam become free of mandatory training again, its a great chance to become a certified spring developer in 2024.

A structured and complete certification preparation involves reading books, joining course and doing practice questions. So apart from Joining Spring Academy courses, which are also free, you should also give as many mock exam and solve as many practice question as possible.

When it comes to Spring certification, practice questions are quite hard to find and that’s why I created my Udemy course with 280+ Spring Certification questions. This course has helped more than 10000 students in their Spring certification preparation journey.

Since many of you asked me about Free Spring certification questions, I decided to post 50 practice questions from my paid Spring certification course for FREE, just for you, my readers and motivates.

This also makes a lot of sense because I have in past used many free resources to pass my own Java and Spring certification and this way I can give something back to the community.

It also helps me to get more feedback to improve the paid course even better to provide better learning experience to people who have trusted me with their money.

In the full course you will get:

  • 5 Full length practice tests + 1 bonus test
  • 280+ Questions with Answers and explanations
  • Topic wise questions like you can practice all spring boot or spring security questions
  • Lifetime access
  • 30-days money back guarantee with no questions asked

If you like to buy the course you can use this link to buy the course with the best price available. I usually give $9.9 discount coupon to my readers, so if you ever need, you can always ask in the comments below or you can drop me an email.

I have created new discount code for those who wants to take my updated test on Udemy, just use code GET_SPRING_CERTIFIED to get the course for just $9.9 now

Top 50 Spring Framework Practice Questions Answers and Explanations

Anyway, enough of words, here are the 50+ Spring questions you can solve or practice as part of your Spring professional certification.

These questions are from full length test which means they cover almost every topics like Core Spring, Bean lifecycle, AOP, Spring Boot, Testing, Microservices, Spring Data JPA and more.

1. Which of the following Spring MVC-related information types are collected in metrics by Spring Boot Actuator by default?

1. Requesting user

2. HTTP method

3. Accessed endpoint

4. Response status

Correct answer is 2,3,4

Explanation: By default, Spring MVC-related metrics are tagged with the following information:

  • exception — Simple class name of any exception that was thrown while handling the request.
  • method — Request’ s method (for example, GET or POST)
  • outcome — Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR
  • status — Response’s HTTP status code (for example, 200 or 500)
  • uri — Requests URI template prior to variable substitution, if possible (for example, /api/person/{id})

2. What do SpEL expressions starting with # reference?

1. Properties in the application environment

2. Spring Beans

3. Literal Values

4. JVM Properties

Correct Answer is 2 “Spring Beans”

Explanation: “A Spring bean is referenced using its name prefixed with @ in SpEL. Chains of property

references can be accessed using the period character.

  • Example accessing property on Spring bean: @mySuperComponent.injectedValue
  • Example invoking method on Spring bean: @mySuperComponent.toString()

3. Which of the following methods will be called first in the bean lifecycle?

1. afterPropertiesSet() method in InitializingBean interface

2. init-method as specified in the Spring XML Configuration

3. Any methods annotated with @PostConstruct

4. Any method named “init”

Correct Answer is 3"Any methods annotated with @PostConstruct

Explanation: For each bean in the container the lifecycle happens as follows:

An instance of the bean is created using the bean metadata.

Properties and dependencies of the bean are set.

Any instances of BeanPostProcessor are given a chance to process the new bean

instance before and after initialization.

- Any methods in the bean implementation class annotated with @PostConstruct are

invoked.

This processing is performed by a BeanPostProcessor.

- Any afterPropertiesSet method in a bean implementation class implementing the

InitializingBean interface is invoked.

This processing is performed by a BeanPostProcessor. If the same initialization

method has already been invoked, it will not be invoked again.

- Any custom bean initialization method is invoked.

Bean initialization methods can be specified either in the value of the init-method

attribute in the corresponding <bean> element in a Spring XML configuration or in

the initMethod property of the @Bean annotation.

This processing is performed by a BeanPostProcessor. If the same initialization

method has already been invoked, it will not be invoked again.

  • The bean is ready for use.

4. Which of the following are auto-configured when using @DataJpaTest?

1. Spring Repositories

2. Spring Security

3. DataSource

4. Message source

Correct Answer is 1,3

Explanation: “The @DataJpaTest annotation auto-configures the following:

- Caching

- Spring Data JPA repositories

- Flyway database migration tool

- A DataSource — The data-source will, as default, use an embedded in-memory database (test database).

- Data source transaction manager — A transaction manager for a single DataSource.

- A JdbcTemplate

- Liquibase database migration tool

- JPA based configuration for Hibernate

- Spring transaction

- A test database

  • A JPA entity manager for tests

5. What one of these ensures that if anything goes wrong, the changes will be preserved once the system is back?

1. Atomicity

2. Consistency

3. Isolation

4. Durability

Correct Answer: 4

Explanation: The effect of one transaction will not have any impact on another transaction so they are independent to one another. They are totally isolated from one another.

6. Which of the following properties are required in order to configure an external MySQL Database?

1. spring.datasource.password

2. spring.datasource.username

3. spring.datasource.url

4. spring.datasource.driver-class-name

Correct Answer: 1,2,3,4

Explanation: All of these are required. Depending on the Database Provider, sometimes it is not necessary to provide the driver-class-name.

7. Which class is used for programmatic usage of transactions?

1. TransactionTemplate

2. TransactionExecutor

3. @Transactional

4. RollbackManager

Correct Answer: 1

Explanation: @Transactional annotation in Spring is used for declarative usage, not programmatic.

8. What effect does setting the attribute “readOnly” on the @Transactional annotation to true have?

1. It does not allow write operations

2. It may optimize query performance

3. Sets the lock mode to READ

4. Nothing. It is there only for documentation.

Correct Answer is 2 “

Explanation: Only some databases reject the INSERT and UPDATE statements inside a read only transaction.

9. Which of the following does Spring Boot provide regarding error handling?

1. Global error page

2. JSON error response

3. Checked exceptions for most common problems

4. Logging errors stack traces separately

Correct Answer: 1,2

Explanation: By default, Spring Boot provides an /error mapping that handles all errors in a sensible way, and it is registered as a “global error page” in the servlet container.

For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. For browser clients, there is a “whitelabel” error view that renders the same data in HTML format (to customize it, add a View that resolves to error). Spring only throws unchecked exceptions in the case of problems.

10. Which of the following are web environment options offered by @SpringBootTest?

1. RANDOM_PORT

2. WEB

3. MINIMAL

4. DEFINED_PORT

Correct Answer: 1,4

Explanation: Four different types of web environments can be specified using the webEnvironment attribute of the @SpringBootTest annotation:

  • MOCK — Loads a web ApplicationContext and provides a mock web environment. Does not start a web server.
  • RANDOM_PORT — Loads a WebServerApplicationContext, provides a real web environment and starts an embedded web server listening on a random port. The port allocated can be obtained using the @LocalServerPort annotation or @Value(“”${local.server.port}””). Web server runs in a separate thread and server-side transactions will not be rolled back in transactional tests.
  • DEFINED_PORT — Loads a WebServerApplicationContext, provides a real web environment and starts an embedded web server listening on the port configured in the application properties, or port 8080 if no such configuration exists. Web server runs in a separate thread and server-side transactions will not be rolled back in transactional tests.
  • NONE — Loads an ApplicationContext without providing any web environment.

11. On which of these database system isolation levels can phantom reads occur?

1. READ_UNCOMMITED

2. SERIALIZABLE

3. REPEATABLE_READ

4. READ_COMMITED

Correct Answer: 1,3,4

Explanation: Phantom reads can occur in all database system isolation levels except for SERIALIZABLE.

12. Which of the following are valid ways of adding a Bean definition to the IoC Container?

1. <bean/> in XML

2. Calling DefaultListableBeanFactory.registerBeanDefinition

3. @Bean annotated method in a @Configuration class

4. Java Class annotated with @Component

Correct Answer: 1,2,3,4

Explanation: All of these are valid ways of adding a bean definition to the IoC Container.

13. In order to define a bean, one can create a class annotated with ________ and add a method annotated with _________ to it.

1. @Service @BeanDefinition

2. @Configuration, @Bean

3. @Configuration, @Inject

4. @Component, @ManagedBean

Correct Answer: 2

Explanation: The Annotation @BeanDefinition does not exist. The annotation @ManagedBean is not part of Spring (it is a JEE class annotation similar to @Component).

14. Which of the following are true about Spring MVC Controllers?

1. When using annotations, specific class or interface inheritance is not required.

2. Endpoint paths mapped by a controller must all have the same prefix.

3. @Controller is a stereotype annotation.

4. Controllers implemented using annotations do not have direct dependencies on Portlet or Servlet APIs.

Correct Answer: 1,3,4

Explanation: Endpoint Paths do not necessarily need to have the same path prefix.

@Controller is a stereotype annotation because it is meta annotated with @Component.

Before annotation based controller declaration, controllers needed to extend certain classes, such as MultiActionController.

15. What does the abbreviation MVC stand for?

1. Multi Variable Control

2. Multi Variable Compiler

3. Model View Compiler

4. Model-View-Controller

Correct Answer: 4

Explanation: MVC stands for Model-View-Controller. It is a programming paradigm which provides separation of concern, which makes it easy to develop and maintain a web application.

16. Which of the following configuration properties must be changed to allow bean definition overriding?

1. spring.beaninfo.ignore

2. management.endpoint.beans.enabled

3. spring.main.allow-bean-definition-overriding

4. Bean Definition Overriding is allowed by default

Correct Answer: 3

Explanation: Spring bean definition overriding is not on by default. The first answer refers to BeanInfo configuration, the second to default actuator properties.

17. Which of the following are condition annotations used by Spring Boot for auto-configuration?

1. @ConditionalOnResource

2. @ConditionalOnProperty

3. @ConditionalOnMissingBean

4. @ConditionalOnCloudPlatform

Correct Answer: 1,2,3,4

Explanation: Here are all of the possible auto-configuration condition annotations:

  • @ConditionalOnClass — Presence of class on classpath.
  • @ConditionalOnMissingClass — Absence of class on classpath.
  • @ConditionalOnBean — Presence of Spring bean or bean type (class).
  • @ConditionalOnMissingBean — Absence of Spring bean or bean type (class).
  • @ConditionalOnProperty — Presence of Spring environment property.
  • @ConditionalOnResource — Presence of resource such as file.
  • @ConditionalOnWebApplication — If the application is considered to be a web application, that is uses the Spring WebApplicationContext, defines a session scope or has a StandardServletEnvironment.
  • @ConditionalOnNotWebApplication — If the application is not considered to be a web application.
  • @ConditionalOnExpression — Bean or configuration active based on the evaluation of a SpEL expression.
  • @ConditionalOnCloudPlatform — If specified cloud platform, Cloud Foundry, Heroku or SAP, is active.
  • @ConditionalOnEnabledEndpoint — Specified endpoint is enabled.
  • @ConditionalOnEnabledHealthIndicator — Named health indicator is enabled.
  • @ConditionalOnEnabledInfoContributor — Named info contributor is enabled.
  • @ConditionalOnEnabledResourceChain — Spring resource handling chain is enabled.
  • @ConditionalOnInitializedRestarter — Spring DevTools RestartInitializer has been applied with non-null URLs.
  • @ConditionalOnJava — Presence of a JVM of a certain version or within Condition Annotation Condition Factor a version range.
  • @ConditionalOnJndi — Availability of JNDI InitialContext and specified JNDI locations exist.
  • @ConditionalOnManagementPort — Spring Boot Actuator management port is either: Different from server port, same as server port or disabled.
  • @ConditionalOnRepositoryType — Specified type of Spring Data repository has been enabled.
  • @ConditionalOnSingleCandidate — Spring bean of specified type (class) contained in bean factory and single candidate can be determined.

18. Which of these protocols is used to access Spring Boot actuator endpoints?

1. SOAP

2. JMX

3. FTP

4. HTTP

Correct Answer: 2,4

Explanation: Both JMX and HTTP protocol can be used to access Spring Boot Actuator endpoints. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application.

19. _________ is linking aspects with other application types or objects to create an advised object?

1. Advice

2. Aspect

3. Weaving

4. Pointcut

Correct Answer: 1

Explanation: “Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

20. Which exception can potentially be thrown when calling the JdbcTemplate.query() method in Spring?

1. SQLException

2. QueryException

3. JdbcException

4. DataAccessException

Correct Answer: 4

Explanation: DataAccessException is the root exception thrown by all Data Access methods. Any SQLExceptions will be suppressed by a DataAccessException.

21. Which of the following is a feature of Spring Boot Actuator?

1. Monitoring

2. Metrics

3. Management

4. Circuit-Breaker

Correct Answer: 1,2,3

Explanation: Monitoring, Metrics and Management are provided by Spring Boot Actuator. Ribbon and Hystrix are the tools provided by Spring as circuit breakers.

22. Which of the following symbols is used in @Value expressions?

1. &

2. $

3. ^

4. #

Correct Answer: 2,4 “Expressions starting with $.

Such expressions reference a property name in the applications environment. These

expressions are evaluated by the PropertySourcesPlaceholderConfigurer Spring bean prior to bean creation and can only be used in @Value annotations.

On the other hand, Expressions starting with # are Spring Expression Language expressions parsed by a SpEL expression parser and evaluated by a SpEL expression instance.

23. In Spring Security, how can you enable the @Secured annotations ?

1. @EnableGlobalMethodSecurity(prePostEnabled = true)

2. @EnableGlobalMethodSecurity(securedEnabled = true)

3. @EnableGlobalMethodSecurity(jsr250Enabled = true)

4. They are enabled by default.

Correct Answer: 2

Explanation: “The attribute securedEnabled specifies whether the @Secured annotation can be used in the application. You can read more about how to enable Spring Security in my earlier post about the same.

24. Which of the following HTTP method is idempotent?

1. GET

2. PUT

3. POST

4. DELETE

Correct Answer: 1,2,4

Explanation: The GET, PUT and DELETE methods are idempotent, meaning that applying them multiple times to a resource results in the same state change of the resource as applying them once, though the response might differ.

25. Which of the following methods in JdbcTemplate is recommended for UPDATE or INSERT operations?

1. query

2. update

3. execute

4. queryForList

Correct Answer: 2

Explanation: update should be used for write operations while query should be for select queries. You can read more about JdbcTemplate in my article 10 examples of JdbcTempalte and see the examples of all these methods to learn more.

26. Which Interface which is responsible for Instantiating, Configuring, Assembling and Managing the life-cycle of spring beans.”

1. ApplicationContext

2. ApplicationBeanContext

3. ApplicationFactoryContext

4. BeanContext

Correct Answer: 1

Explanation: ApplicationContext is an Interface, which acts as a container in spring which is responsible for carrying out life cycle of beans. You can read more about that in my post difference between BeanRepository and ApplicationContext

27. Spring has mock objects to use in tests in the following areas?

1. RMI

2. Environment

3. JMX

4. JNDI

Correct Answer: 2,4

Explanation: Spring has mock objects on Environment, JNDI, and Servlet API to assist in unit testing.

28. Consider the following signature of a bean definition method:

@Bean
public BeanX beanY(BeanZ beanZ)

What is the name of the created bean?”

1. BeanX

2. beanX

3. beanY

4. beanZ

Correct Answer: 3

Explanation: When defined this way, the name of the method will same as bean name. You can also read my tutorial on @Bean annotation to learn more about it.

29. Which class associates a request URL pattern with a list of filters in Spring Security?

1.FilterChainProxy

2. FilterChain

3. DelegatingFilterProxy

4. SecurityFilterChain

Correct Answer: 4

Explanation: SecurityFilterChain is used by FilterChainProxy to determine which Spring Security Filters should be invoked for this request.

30. Which options of dependency injection exist?

1. constructor-based

2. template-based

3. field-based

4. setter-based

Correct Answer: 1,3,4

Explanation: Template-based injection does not exist

31. Which of the following AOP advice types can choose to prevent execution of the advised method, and instead return another value?

1. @Before

2. @Around

3. @AfterThrowing

4. @AfterReturning

Correct Answer: 2

Explanation: Before advice can also prevent execution of the advised method, however only if an exception is thrown. Around advice can prevent the execution of the advised method and change the return value.

32. What are limitations of using the default JDK dynamic proxies in Spring AOP?

1. Method calls inside the same class cannot be intercepted.

2. There are less available pointcut designators.

3. Only public interface method calls can be intercepted

4. It cannot intercept constructor calls

Correct Answer: 3

33. Which of the following dependencies are included in the spring-boot-starter-test starter?

1. Hamcrest

2. EasyMock

3. JUnit

4. PowerMock

Correct Answer: 1,3

Explanation: The spring-boot-starter-test starter adds the following test-scoped dependencies to the classpath:

- JUnit — Unit-testing framework.

- Spring Test and Spring Boot Test

- AssertJ — Fluent assertions for Java.

- Hamcrest — Framework for writing matchers that are both powerful and easy to read.

- Mockito — Mocking framework for Java.

- JSONassert — Tools for verifying JSON representation of data.

- JsonPath — A Java DSL for reading JSON documents.

34. Which of the following HTTP verbs can be used to create a new entity, but not modify an existing one?

1. GET

2. PUT

3. POST

4. DELETE

Correct Answer: 3

Explanation: Function of POST: Create a member resource in the collection resource using the instructions in the request body. The URI of the created member resource is automatically assigned and returned in the response Location header field.

35. Which of the following are valid ways to inject a dependency into a bean in Spring?

1. BeanFactory.getBean() method

2. @Autowired annotation

3. XML Configuration

4. Constructor argument

Correct Answer: 1,2,3,4

Explanation: All of these are valid ways.

36. “Consider the code sample below:

public class MyClass {
@MyAnnotation
public String myMethod(){
///
}

Fill in the blank in the pointcut expression below, so that it matches the above method:

______(MyAnnotation)

1. @target

2. @args

3. @within

4. @annotation

Correct Answer: 4

Explanation: @target limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type. While @args limits matching to join points (the execution of methods when using Spring AOP)”

37. What is the name of the default prefix of all actuator endpoints?

1. endpoint/actuator/

2. management/

3. actuator/metrics/

4. actuator/

Correct Answer: 4

Explanation: “The default prefix for actuator endpoints is “”actuator/””

38. Which of these is the correct naming convention for custom find methods in Spring Data Repository Interface?

1. find(First[count]) [ordering operator] [comparison operator] By[Property Expression]

2. find(First[count]) By[Property Expression] [ordering operator] [comparison operator]

3. find(First[count]) By[Property Expression] [comparison operator] [ordering operator]

4. None of the above.

Correct Answer 3

Explanation: This is a tricky Spring Data JPA question but you need to remember that Result limit (First/Last X) comes first. After By comes the property to be queried, followed by the comparison operator. The sort order comes last.

39. Which of these act as Spring Boot dependency descriptors?

1. Starters

2. Actuator

3. Dependencies

4. Reactor

Correct Answer : 1

Explanation: “Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.

40. A HTTP Response Code of ____ means __________

1. 500, Server Side Error

2. 400, Client Side Error

3. 300, Success

3. 200, Client Side Error

Correct Answer: 1,2

Explanation: Http Response Status Codes for a request are 1x-informational, 2x- Success, 3x-Redirectional, 4x-Client Side Error, 5x-Server Side Error.

41. What are the advantages when using @Mock instead of @MockBean in Spring Boot tests?

1. Method parameters can be annotated with @Mock

2. @Mock is included without additional dependencies

3. @Mock can be used for non-bean classes

4. @Mock can be used without SpringRunner

Correct Answer: 1,3,4

Explanation: “Both the @MockBean and @Mock annotation can be used to create Mockito mocks but there are a couple of differences between the two annotations:

  • @Mock can only be applied to fields and parameters while @MockBean can only be applied to classes and fields.
  • @Mock can be used to mock any Java class or interface while @MockBean only allows for mocking of Spring beans or creation of mock Spring beans.
  • @MockBean can be used to mock existing beans but also to create new beans that will belong to the Spring application context.
  • To be able to use the @MockBean annotation, the Spring runner (@RunWith(SpringRunner.class) ) has to be used to run the associated test.
  • @MockBean can be used to create custom annotations for specific, reoccurring, needs

When running Spring Boot Tests, both @Mock and @MockBean are included in the spring-boot-starter-test.

42. Which technology is used to accomplish method-level security in Spring?

1. Transactions

2. Servlet Filters

3. AOP

4. None of the above.

Correct Answer: 3

Explanation: Method security is based on Spring AOP

43. Which of the following does Spring HATEOAS auto-configuration provide?

1. HateoasController

2. ObjectMapper

3. HATEOAS Security

4. @EnableHypermediaSupport

Correct Answer: 2,4

Explanation: If you develop a RESTful API that makes use of hypermedia, Spring Boot provides auto-configuration for Spring HATEOAS that works well with most applications. The auto-configuration replaces the need to use @EnableHypermediaSupport and registers a number of beans to ease building hypermedia-based applications, including a LinkDiscoverers (for client side support) and an ObjectMapper configured to correctly marshal responses into the desired representation.

The ObjectMapper is customized by setting the various spring.jackson.* properties or, if one exists, by a Jackson2ObjectMapperBuilder bean.

You can take control of Spring HATEOAS’ configuration by using @EnableHypermediaSupport. Note that doing so disables the ObjectMapper customization described earlier.

44. Which of these Annotation enables Spring Boot auto-configuration?

1. @Configuration

2. @EnableAutoConfiguration

3. @AutoConfiguration

4. @SpringConfiguration

Correct Answer: 2

Explanation: The @EnableAutoConfiguration is used to enable Spring Boot’s auto-configuration mechanism. While @Configuration is an annotation used on classes which contain bean definition methods. You can also use @SpringBootApplication to enable auto-configuration in Spring Boot applications.

45. Which of the following is provided by Spring Boot’s Spring MVC Auto-configuration?

1. ContentNegotiatingViewResolver bean

2. RestController testing pages

3. HttpMessageConverters support

4. Support for serving static resources

Correct Answer: 1,3,4

Explanation: “Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

The auto-configuration adds the following features on top of Spring’s defaults:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
  • Support for serving static resources, including support for WebJars (covered later in this document)).
  • Automatic registration of Converter, GenericConverter, and Formatter beans.
  • Support for HttpMessageConverters (covered later in this document).
  • Automatic registration of MessageCodesResolver (covered later in this document).
  • Static index.html support.
  • Custom Favicon support (covered later in this document).
  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

46. Which of the following HTTP methods can be mapped to a method annotated with @RequestMapping?

1. GET

2. PUT

3. POST

4. DELETE

Correct Answer: 1,2,3,4

Explanation: “RequestMapping is an annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.

By default, it will map all HTTP methods. One can specify which methods should be allowed using the “”method”” attribute or use one of the HTTP method variants such as @GetMapping.

47. Which of the following bean scopes can only be used in the context of a web-aware Spring Application Context?

1. web

2. request

3. session

4. application

Correct Answer: 2,3,4 “The following bean scopes are only valid in the context of a web-aware Spring ApplicationContext: session, request, application, websocket. There is no ‘web’ bean scope out of the box.

48. Which of the following annotations can be used to inject property values into Spring beans and configuration classes?

1. @Primary

2. @Value

3. @Import

4. @PropertyValue

Correct Answer: 2

Explanation: The @Value is an annotation used to inject property values into a field using SpEL.

49. What happens if you define both the “id” and “name” attributes in a bean’s XML definition?

1. “id” is used as bean identifier

2. “name” is used for bean aliases

3. An exception is thrown

4. The application will crash.

Correct Answer: 1,2

Explanation: XML-based configuration metadata, you use the id attribute, the name attribute, or both to specify the bean identifiers. The id attribute lets you specify exactly one id. Conventionally, these names are alphanumeric (‘myBean’, ‘someService’, etc.), but they can contain special characters as well. If you want to introduce other aliases for the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space.

50. Which of these testing refers to automated tests for the smallest unit of functionality. This may be a method in a class, a class or even an entire module

1. Unit

2. Integration

3. Performance

4. Interaction

Correct Answer: 1

Explanation: Unit Testing is the foremost testing done in software development life cycle. All individual units of an application are tested to make sure that they are working good.

New Spring Certification Questions on recent Exam Topics (2024)

And, if you need more challenging questions, here are few more questions for practice from recent exam topics.

Programmable Transaction Management

Question: Which of the following statements is true about programmatic transaction management in Spring?

A) Transaction status can be controlled using TransactionDefinition and TransactionManager.

B) Programmatic transactions are easier to maintain than declarative transactions.

C) @Transactional annotation is primarily used for programmatic transaction management.

D) Nested transactions are not supported in programmatic transaction management.

Answer: A) Transaction status can be controlled using TransactionDefinition and TransactionManager.

Explanation: In programmatic transaction management, transactions are controlled programmatically using TransactionDefinition and TransactionManager. Option B is incorrect because programmatic transactions can be more complex and harder to maintain than declarative transactions. Option C is incorrect because @Transactional is used for declarative transaction management. Option D is incorrect because nested transactions are supported in programmatic transaction management.

Autowire Template or use as bean

Question: When autowiring a bean in Spring, which statement is true?

A) The @Autowired annotation can be used on constructors, setters, and fields.

B) Spring always requires the bean to be defined in the @Configuration class.

C) Autowiring is only possible using XML configuration.

D) Autowiring is not supported for template classes like JdbcTemplate.

Answer: A) The @Autowired annotation can be used on constructors, setters, and fields.

Explanation: The @Autowired annotation in Spring can be used to autowire bean dependencies through constructors, setters, or directly on fields. Option B is incorrect because beans can also be defined using component scanning and other methods. Option C is incorrect because autowiring is possible using both XML and annotation-based configurations. Option D is incorrect because template classes like JdbcTemplate can also be autowired.

Names for MVC and DevTools packages

Question: Which of the following packages are correctly associated with Spring MVC and Spring DevTools?

A) org.springframework.web for MVC and org.springframework.boot.devtools for DevTools.

B) org.springframework.mvc for MVC and org.springframework.devtools for DevTools.

C) org.springframework.mvc for MVC and org.springframework.boot.tools for DevTools.

D) org.springframework.web.mvc for MVC and org.springframework.boot.devtools for DevTools.

Answer: A) org.springframework.web for MVC and org.springframework.boot.devtools for DevTools.

Explanation: The org.springframework.web package contains classes for Spring MVC, and the org.springframework.boot.devtools package contains classes for Spring DevTools. The other options are incorrect package names.

Convert a Java Singleton pattern into a Bean

Question: How can you convert a Java Singleton pattern into a Spring bean?

A) Use the @Singleton annotation on the class.

B) Define the bean with @Bean in a @Configuration class and ensure the scope is singleton.

C) Implement Serializable and ensure proper handling of serialization and deserialization.

D) Use @Scope("prototype") to ensure only one instance is created.

Answer: B) Define the bean with @Bean in a @Configuration class and ensure the scope is singleton.

Explanation: To convert a Java Singleton pattern into a Spring bean, you should define the bean in a @Configuration class using the @Bean annotation and ensure the scope is singleton, which is the default scope in Spring. Option A is incorrect as there is no @Singleton annotation in Spring. Option C relates to serialization and is not relevant here. Option D is incorrect because @Scope("prototype") creates multiple instances.

TestPropertySource: priority, configurations

Question: What is the priority order when using @TestPropertySource in Spring?

A) @TestPropertySource properties override properties from application.properties.

B) application.properties override properties defined in @TestPropertySource.

C) Both @TestPropertySource and application.properties have the same priority.

D) @TestPropertySource properties are ignored if application.properties is present.

Answer: A) @TestPropertySource properties override properties from application.properties.

Explanation: When using @TestPropertySource, properties defined there take precedence over properties defined in application.properties. This allows you to override default property values specifically for your tests.

PropertySources Vs ConfigProperties

Question: Which of the following statements correctly describes the difference between @PropertySource and @ConfigurationProperties?

A) @PropertySource is used to read properties from a file, while @ConfigurationProperties binds properties to a POJO.

B) @PropertySource binds properties to a POJO, while @ConfigurationProperties reads properties from a file.

C) @PropertySource and @ConfigurationProperties are interchangeable.

D) @PropertySource is used for environment-specific properties, while @ConfigurationProperties is not.

Answer: A) @PropertySource is used to read properties from a file, while @ConfigurationProperties binds properties to a POJO.

Explanation: @PropertySource is used to read properties from an external file and make them available in the Spring Environment, while @ConfigurationProperties is used to bind externalized properties to a POJO.

Slice tests, what are the layers

Question: Which layers are typically tested when using slice tests in Spring?

A) Controllers, Services, and Repositories

B) Only Controllers

C) Services and Repositories

D) Repositories and Database

Answer: A) Controllers, Services, and Repositories

Explanation: Slice tests in Spring focus on testing specific layers like Controllers (@WebMvcTest), Services (@MockBean), and Repositories (@DataJpaTest) without starting the full application context.

@DirtiesContext annotation, how it works

Question: What does the @DirtiesContext annotation do in a Spring test?

A) It prevents the application context from being cached.

B) It marks the application context as dirty, causing it to be closed and removed after the test.

C) It refreshes the application context before each test.

D) It disables context caching entirely.

Answer: B) It marks the application context as dirty, causing it to be closed and removed after the test.

Explanation: The @DirtiesContext annotation indicates that the context associated with the test is dirty and should be closed and removed after the test. This ensures that the next test will run with a new context.

TestRestTemplate what does it provide?

Question: What does TestRestTemplate provide in a Spring Boot test?

A) An enhanced RestTemplate specifically designed for integration testing with authentication capabilities.

B) A template for creating mock MVC requests.

C) A template for testing database interactions.

D) A mock implementation of RestTemplate.

Answer: A) An enhanced RestTemplate specifically designed for integration testing with authentication capabilities.

Explanation: TestRestTemplate is a convenience class that simplifies integration testing of RESTful services. It provides additional features like simplified configuration and authentication support.

SpringBootTest vs SpringJunitConfig, do they create context

Question: Do @SpringBootTest and @SpringJUnitConfig create application contexts?

A) Both create a full application context.

B) @SpringBootTest creates a full application context, while @SpringJUnitConfig creates a partial context.

C) @SpringJUnitConfig creates a full application context, while @SpringBootTest creates a partial context.

D) Neither creates an application context.

Answer: A) Both create a full application context.

Explanation: Both @SpringBootTest and @SpringJUnitConfig create an application context, but @SpringBootTest is more comprehensive and includes auto-configuration, while @SpringJUnitConfig can be used with specific configurations.

JDBC Template in general and RowMapper

Question: Which of the following is true about JdbcTemplate and RowMapper in Spring?

A) JdbcTemplate is used for managing transactions, and RowMapper is used to map rows of a ResultSet.

B) JdbcTemplate simplifies database operations, and RowMapper is used to map rows of a ResultSet to Java objects.

C) JdbcTemplate is used for ORM, and RowMapper is used for pagination.

D) JdbcTemplate is used for batch processing, and RowMapper is used to handle exceptions.

Answer: B) JdbcTemplate simplifies database operations, and RowMapper is used to map rows of a ResultSet to Java objects.

Explanation: JdbcTemplate is a Spring utility class that simplifies database operations like querying and updating, and RowMapper is an interface used to map rows of a ResultSet to Java objects.

If adding dependency jdbc and hsql does DataSource and JdbcTemplate get autoconfigured

Question: When you add JDBC and HSQLDB dependencies to a Spring Boot project, what happens to DataSource and JdbcTemplate?

A) Both DataSource and JdbcTemplate get auto-configured by Spring Boot.

B) Only DataSource gets auto-configured.

C) Only JdbcTemplate gets auto-configured.

D) Neither DataSource nor JdbcTemplate get auto-configured; manual configuration is required.

Answer: A) Both DataSource and JdbcTemplate get auto-configured by Spring Boot.

Explanation: When you add JDBC and HSQLDB dependencies, Spring Boot auto-configures both DataSource and JdbcTemplate, simplifying the setup process.

Actuators, type of metrics, what is Timer, does metrics need tags

Question: Which statement is correct regarding Spring Boot Actuator metrics and the Timer?

A) Actuator metrics can include gauges, counters, and timers, and timers are used to measure time taken by operations. Metrics do not require tags.

B) Actuator metrics only include counters, and timers are not supported. Metrics require tags.

C) Actuator metrics include only gauges and counters, and timers are used for logging purposes only. Metrics require tags.

D) Actuator metrics include gauges, counters, and timers. Timers measure time taken by operations and can include optional tags for detailed monitoring.

Answer: D) Actuator metrics include gauges, counters, and timers. Timers measure time taken by operations and can include optional tags for detailed monitoring.

Explanation: Spring Boot Actuator metrics include gauges, counters, and timers. Timers are used to measure the time taken by operations, and while tags are optional, they can provide detailed monitoring when used.

Actuator change logging

Question: How can you change the logging level of a Spring Boot application at runtime using Actuator?

A) Modify the application.properties file and restart the application.

B) Use the /actuator/loggers endpoint to change the logging level.

C) Change the log level in the code and redeploy the application.

D) Use a custom logging configuration file.

Answer: B) Use the /actuator/loggers endpoint to change the logging level.

Explanation: Spring Boot Actuator provides the /actuator/loggers endpoint, which allows you to change the logging level of the application at runtime without needing to restart or redeploy the application.

@Autowired and @Qualifier scenarios

Question: In which scenario would you use @Autowired and @Qualifier together in Spring?

A) When you want to inject a bean without specifying which implementation to use.

B) When you have multiple beans of the same type and want to specify which one to inject.

C) When you want to inject a bean based on its type only.

D) When you need to disable autowiring for a specific bean.

Answer: B) When you have multiple beans of the same type and want to specify which one to inject.

Explanation: @Autowired is used for dependency injection, and @Qualifier is used to specify which bean to inject when there are multiple beans of the same type.

EnableAutoConfiguration, what does it do, does package location make a difference

Question: What does the @EnableAutoConfiguration annotation do in Spring Boot, and does package location make a difference?

A) It disables auto-configuration, and package location makes no difference.

B) It enables auto-configuration of Spring Boot applications, and package location can affect component scanning.

C) It manually configures all necessary beans, and package location is irrelevant.

D) It is used only for web applications, and package location determines the main method location.

Answer: B) It enables auto-configuration of Spring Boot applications, and package location can affect component scanning.

Explanation: @EnableAutoConfiguration enables Spring Boot's auto-configuration mechanism, which automatically configures Spring application based on the jar dependencies. The package location can affect component scanning, as it determines the base package for scanning components, configurations, and services.

That’s all about the Free 50+ Spring Certification Practice Questions. You can use this practice test to check your knowledge as well as learn essential Spring concepts and topics for Spring professional certifications.

If you like these questions and my explanations, you can always buy the full test on Udemy, I would really appreciate that.

Free Coupons for My Java, Spring and Cloud Computing Udemy courses

And, if you are preparing for Java and Cloud Certifications like AWS and Azure, here are list of my Udemy courses which can help you in your certification journey.

For spring course, I have created new discount code for those who wants to take my updated test on Udemy, just use code GET_SPRING_CERTIFIED to get the course for just $9.9 now

If you need discount coupon feel free to ask

You can also use coupon “GET_SPRING_CERTIFIED” to get the course for just $9.9 (best price), I mostly created best price coupon using this code but if its not working or expired, feel free to ask in comments.

If you have any other spring questions or spring certification memory dumps to share with other developers preparing for this certification, feel free to share on comments.

Other Java and Spring articles you may like

  • The Java Developer RoadMap (roadmap)
  • 5 Spring Boot Features Every Java Developer Should Know (features)
  • How to test Spring boot application ? (spring boot testing example)
  • Spring Boot + ThyMyleaf project example (thymyleaf example)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)
  • Spring Boot Integration test example (integration test example)
  • 10 Tips to become a better Java developer (tips)
  • 3 Best Practices You can learn from Spring (best practices)
  • How to post JSON data using Postman? (postman json example)
  • 10 Spring Core Annotations Java Developers should learn (annotations)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • 5 courses to learn Spring Boot and Spring Cloud( courses)
  • Top 5 Free Courses to learn Spring and Spring Boot (courses)
  • 10 Things Java Developer should learn(goals)
  • 5 Course to Master Spring Boot online(courses)
  • 7 Courses to learn Microservices for Java developers (courses)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 10 Advanced Spring Courses for Experienced Programmers (courses)

Thanks for reading this article so far. If you like this Spring Framework Professional exam Practice Questions and answers , then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

Did you like the answer just below the question or would you guys prefer it at the end of the article? I wasn’t sure so I put the answer just below the question which is good for learning but may not be great for practice. Tell me your choices and I will rearrange them.

P. S. — If you are a new to Spring framework and want to learn the Spring MVC from scratch, and looking for some best online resources then you can also check out these best Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch.

--

--

No responses yet