Spring Interview Questions and Answers (2023) - InterviewBit
Spring Interview Questions and Answers (2023) - InterviewBit
https://www.interviewbit.com/spring-interview-questions/ 1/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
https://www.interviewbit.com/spring-interview-questions/ 3/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
https://www.interviewbit.com/spring-interview-questions/ 4/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
In case the bean has many properties, then constructor injection is preferred.
If it has few properties, then setter injection is preferred.
7. What are Spring Beans?
They are the objects forming the backbone of the user’s application and are
managed by the Spring IoC container.
Spring beans are instantiated, configured, wired, and managed by IoC
container.
Beans are created with the configuration metadata that the users supply to
the container (by means of XML or java annotations configurations.)
8. How is the configuration meta data provided to the spring
container?
There are 3 ways of providing the configuration metadata. They are as follows:
XML-Based configuration:The bean configurations and their dependencies
are specified in XML configuration files. This starts with a bean tag as shown
below:
<bean id="interviewBitBean" class="org.intervuewBit.firstSpring
<property name="name" value="InterviewBit"></property>
</bean>
methods.Note that:
@Bean annotation has the same role as the <bean/> element.
Classes annotated with @Configuration allow to define inter-bean
dependencies by simply calling other @Bean methods in the same class.
9. What are the bean scopes available in Spring?
The Spring Framework has five scope supports. They are:
Singleton:The scope of bean definition while using this would be a single
instance per IoC container.
Prototype:Here, the scope for a single bean definition can be any number of
object instances.
Request:The scope of the bean definition is an HTTP request.
Session:Here, the scope of the bean definition is HTTP-session.
Global-session:The scope of the bean definition here is a Global HTTP
session.
Note: The last three scopes are available only if the users use web-aware
ApplicationContext containers.
10. Explain Bean life cycle in Spring Bean Factory Container.
The Bean life cycle is as follows:
The IoC container instantiates the bean from the bean’s definition in the XML
file.
Spring then populates all of the properties using the dependency injection as
specified in the bean definition.
The bean factory container calls setBeanName() which take the bean ID
and the corresponding bean has to implement BeanNameAware interface.
The factory then calls setBeanFactory() by passing an instance of itself
(if BeanFactoryAware interface is implemented in the bean).
If BeanPostProcessors is associated with a bean, then
the preProcessBeforeInitialization() methods are invoked.
https://www.interviewbit.com/spring-interview-questions/ 7/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
Data types restriction: Primitive data types, Strings, and Classes can’t be
autowired.
Spring Boot Interview Questions
14. What do you understand by the term ‘Spring Boot’?
Spring Boot is an open-source, java-based framework that provides support for
Rapid Application Development and gives a platform for developing stand-alone
and production-ready spring applications with a need for very few configurations.
15. Explain the advantages of using Spring Boot for application
development.
Spring Boot helps to create stand-alone applications which can be started
using java.jar (Doesn’t require configuring WAR files).
Spring Boot also offers pinpointed ‘started’ POMs to Maven configuration.
Has provision to embed Undertow, Tomcat, Jetty, or other web servers
directly.
Auto-Configuration: Provides a way to automatically configure an application
based on the dependencies present on the classpath.
Spring Boot was developed with the intention of lessening the lines of code.
https://www.interviewbit.com/spring-interview-questions/ 9/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
internally?
As per the Spring Boot documentation, the @SpringBootApplication annotation is
one point replacement for using @Configuration, @EnableAutoConfiguration and
@ComponentScan annotations alongside their default attributes.
This enables the developer to use a single annotation instead of using multiple
annotations thus lessening the lines of code. However, Spring provides loosely
coupled features which is why we can use these annotations as per our project
needs.
19. What are the effects of running Spring Boot Application as
“Java Application”?
The application automatically launches the tomcat server as soon as it sees
that we are running a web application.
20. What is Spring Boot dependency management system?
https://www.interviewbit.com/spring-interview-questions/ 11/44
It is basically used to manage dependencies and configuration automatically
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
without the need of specifying the version for any of that dependencies.
21. What are the possible sources of external configuration?
Spring Boot allows the developers to run the same application in different
environments by making use of its feature of external configuration. This uses
environment variables, properties files, command-line arguments, YAML files,
and system properties to mention the required configuration properties for its
corresponding environments. Following are the sources of external
configuration:
Command-line properties– Spring Boot provides support for
command-line arguments and converts these arguments to properties
and then adds them to the set of environment properties.
Application Properties– By default, Spring Boot searches for the
application properties file or its YAML file in the current directory of the
application, classpath root, or config directory to load the properties.
Profile-specific properties– Properties are loaded from
the application-{profile}.properties file or its YAML file. This
file resides in the same location as that of the non-specific property files
and the {profile} placeholder refers to an active profile or an environment.
22. Can we change the default port of the embedded Tomcat
server in Spring boot?
Yes, we can change it by using the application properties file by adding a
property of server.port and assigning it to any port you wish to.
For example, if you want the port to be 8081, then you have to
mention server.port=8081 . Once the port number is mentioned, the
application properties file will be automatically loaded by Spring Boot and the
specified configurations will be applied to the application.
23. Can you tell how to exclude any package without using the
basePackages filter?
https://www.interviewbit.com/spring-interview-questions/ 12/44
We can use the exclude attribute while using the
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
If the class is not specified on the classpath, we can specify the fully qualified
name as the value for the excludeName .
//By using "excludeName"
@EnableAutoConfiguration(excludeName={Foo.class})
You can add into the application.properties and multiple classes can be added
by keeping it comma-separated.
25. Can the default web server in the Spring Boot application
be disabled?
Yes! application.properties is used to configure the web application type,
by mentioning spring.main.web-application-type=none .
26. What are the uses of @RequestMapping and
@RestController annotations in Spring Boot?
@RequestMapping:
This provides the routing information and informs Spring that any HTTP
request matching the URL must be mapped to the respective method.
org.springframework.web.bind.annotation.RequestMapping has
to be imported to use this annotation.
@RestController:
https://www.interviewbit.com/spring-interview-questions/ 13/44
This is applied to a class to mark it as a request handler thereby creating
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
RESTful web services using Spring MVC. This annotation adds the
@ResponseBody and @Controller annotation to the class.
org.springframework.web.bind.annotation.RestController has
to be imported to use this annotation.
Check out more Interview Questions on Spring Boothere.
Spring AOP, Spring JDBC, Spring Hibernate Interview
Questions
27. What is Spring AOP?
Spring AOP (Aspect Oriented Programming) is similar to OOPs (Object
Oriented Programming) as it also provides modularity.
In AOP key unit isaspectsorconcernswhich are nothing but stand-alone
modules in the application. Some aspects have centralized code but other
aspects may be scattered or tangled code like in the case of logging or
transactions. These scattered aspects are calledcross-cutting concern.
A cross-cutting concern such as transaction management,
authentication, logging, security etc is a concern that could affect the
whole application and should be centralized in one location in code as
much as possible for security and modularity purposes.
AOP provides platform to dynamically add these cross-cutting concerns
before, after or around the actual logic by using simple pluggable
configurations.
This results in easy maintainenance of code. Concerns can be added or
removed simply by modifying configuration files and therefore without the
need for recompiling complete sourcecode.
There are 2 types of implementing Spring AOP:
Using XML configuration files
Using AspectJ annotation style
28. What is an advice? Explain its types in spring.
https://www.interviewbit.com/spring-interview-questions/ 14/44
An advice is the implementation of cross-cutting concerns can be applied to other
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
does not implement an interface, then CGLIB proxies are used by default.
30. What are some of the classes for Spring JDBC API?
Following are the classes
JdbcTemplate
SimpleJdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcInsert
SimpleJdbcCall
The most commonly used one is JdbcTemplate. This internally uses the JDBC
API and has the advantage that we don’t need to create connection,
statement, start transaction, commit transaction, and close connection to
execute different queries. All these are handled by JdbcTemplate itself. The
developer can focus on executing the query directly.
31. How can you fetch records by Spring JdbcTemplate?
This can be done by using the query method of JdbcTemplate. There are two
interfaces that help to do this:
ResultSetExtractor:
It defines only one method extractData that
accepts ResultSet instance as a parameter and returns the list.
Syntax:
public T extractData(ResultSet rs) throws SQLException,DataAccessE
RowMapper:
This is an enhanced version of ResultSetExtractor that saves a lot of
code.
It allows to map a row of the relations with the instance of the user-
defined class.
It iterates the ResultSet internally and adds it into the result collection
thereby saving a lot of code to fetch records.
https://www.interviewbit.com/spring-interview-questions/ 16/44
32. What is Hibernate ORM Framework?
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
}
}
/**
* Util class to format any string value to valid date format
*/
public class FormatterUtil {
This cannot instantiate the values partially and ensures that the
dependency injection is done fully.
There are two possible ways of achieving this:
Annotation Configuration:This approach uses POJO objects and annotations
for configuration. For example, consider the below code snippet:
@Configuration
@ComponentScan("com.interviewbit.constructordi")
public class SpringAppConfig {
@Bean
public Shape shapes() {
return new Shapes("Rectangle");
}
@Bean
public Dimension dimensions() {
return new Dimension(4,3);
}
}
Here, the annotations are used for notifying the Spring runtime that the class
specified with @Bean annotation is the provider of beans and the process of
context scan needs to be performed on the
package com.interviewbit.constructordi by means
of @ComponentScan annotation. Next, we will be defining a Figure class
component as below:
@Component
public class Figure {
private Shape shape;
private Dimension dimension;
@Autowired
public Figure(Shape shape, Dimension dimension) {
this.shape = shape;
this.dimension = dimension;
}
}
https://www.interviewbit.com/spring-interview-questions/ 23/44
Spring encounters this Figure class while performing context scan and it initializes
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
The constructor-arg tag can accept either literal value or another bean’s
reference and explicit index and type. The index and type arguments are used for
resolving conflicts in cases of ambiguity.
While bootstrapping this class, the Spring ApplicationContext needs to
use ClassPathXmlApplicationContext as shown below:
ApplicationContext context = new ClassPathXmlApplicationContext("s
Figure figure = context.getBean(Figure.class);
Setter-Based:
https://www.interviewbit.com/spring-interview-questions/ 24/44
This form of DI is achieved when the Spring IoC container calls the bean’s
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
The ‘JsonArticle’ bean is injected into the InterviewBit class object by means of
the setArticle method.
In cases where both types of dependencies are used, then the setter dependency
injection has more preference by considering the specificity nature.
49. What is the importance of session scope?
https://www.interviewbit.com/spring-interview-questions/ 25/44
Session scopes are used to create bean instances for HTTP sessions. This would
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
mean that a single bean can be used for serving multiple HTTP requests. The
scope of the bean can be defined by means of using scope attribute or using
@Scope or @SessionScope annotations.
Using scope attribute:
<bean id="userBean" class="com.interviewbit.UserBean" scope="sessi
Using @SessionScope:
@Component
@SessionScope
public class UserBean {
//some methods and properties
}
@Required
public void setAge(int age) {
https://www.interviewbit.com/spring-interview-questions/ 26/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
this.age = age;
}
public Integer getAge() {
return this.age;
}
@Required
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
essentially deals with the execution of the program and the singleton is simply a
design pattern meant for the creation of objects. Thread safety nature of a bean
depends on the nature of its implementation.
53. How can you achieve thread-safety in beans?
The thread safety can be achieved by changing the scope of the bean to request,
session or prototype but at the cost of performance. This is purely based on the
project requirements.
54. What is the significance of @Repository annotation?
@Repository annotation indicates that a component is used as the repository that
acts as a means to store, search or retrieve data. These can be added to the DAO
classes.
55. How is the dispatcher servlet instantiated?
The dispatcher servlet is instantiated by means of servlet containers such as
Tomcat. The Dispatcher Servlet should be defined in web.xml The
DispatcherServlet is instantiated by Servlet containers like Tomcat. The Dispatcher
Servlet can be defined in web.xml as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xm
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java
https://www.interviewbit.com/spring-interview-questions/ 28/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
<servlet-mapping>
<servlet-name>InterviewBitServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The Spring will understand to find the corresponding validators by checking the
@Valid annotation on the parameter.
60. What are Spring Interceptors?
Spring Interceptors are used to pre-handle and post-handle the web requests in
Spring MVC which are handled by Spring Controllers. This can be achieved by
the HandlerInterceptor interface. These handlers are used for manipulating
the model attributes that are passed to the controllers or the views.
https://www.interviewbit.com/spring-interview-questions/ 30/44
The Spring handler interceptor can be registered for specific URL mappings so
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
that it can intercept only those requests. The custom handler interceptor must
implement the HandlerInterceptor interface that has 3 callback methods
that can be implemented:
preHandle()
postHandle()
afterCompletion()
The only problem with this interface is that all the methods of this interface need to
be implemented irrespective of its requirements. This can be avoided if our handler
class extends the HandlerInterceptorAdapter class that internally
implements the HandlerInterceptor interface and provides default blank
implementations.
61. Is there any need to keepspring-mvc.jar on the classpath or
is it already present as part of spring-core?
The spring-mv.jar does not belong to the spring-core. This means that the jar
has to be included in the project’s classpath if we have to use the Spring MVC
framework in our project. For Java applications, the spring-mvc.jar is placed
inside /WEB-INF/lib folder.
62. What are the differences between the
<context:annotation-config> vs <context:component-scan>
tags?
<context:annotation-config> is used for activating applied annotations in
pre-registered beans in the application context. It also registers the beans defined
in the config file and it scans the annotations within the beans and activates them.
The <context:component-scan> tag does the task
of <context:annotation-config> along with scanning the packages and
registering the beans in the application context.
<context:annotation-config> = Scan and activate annotations in pre-
registered beans.
https://www.interviewbit.com/spring-interview-questions/ 31/44
= Register Bean + Scan and activate
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
<context:component-scan>
annotations in package.
63. How is the form data validation done in Spring Web MVC
Framework?
Spring MVC does the task of data validation using the validator object which
implements the Validator interface. In the custom validator class that we have
created, we can use the utility methods of the ValidationUtils class
like rejectIfEmptyOrWhitespace() or rejectIfEmpty() to perform
validation of the form fields.
@Component
public class UserValidator implements Validator
{
public boolean supports(Class clazz) {
return UserVO.class.isAssignableFrom(clazz);
}
In the fields that are subject to validation, in case of errors, the validator methods
would create field error and bind that to the field.
To activate the custom validator as spring bean, then:
We have to add the @Component annotation on the custom validator class
and initiate the component scanning of the package containing the validator
declarations by adding the below change:
<context:component-scan base-package="com.interviewbit.validators"
https://www.interviewbit.com/spring-interview-questions/ 32/44
OR
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
The validator class can be registered in the context file directly as a bean as
shown:
<bean id="userValidator" class="com.interviewbit.validators.UserVa
Syntax:
<bean class="org.Springframework.web.servlet.mvc.annotation.Defaul
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
https://www.interviewbit.com/spring-interview-questions/ 35/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
errors?
The validation is generally performed during HTTP POST requests. During HTTP
requests, if the state of the checkbox is unchecked, then HTTP includes the
request parameter for the checkbox thereby not picking up the updated selection.
This can be fixed by making use of a hidden form field that starts with _ in the
Spring MVC.
Conclusion:
In this article, we have seen the most commonly asked Spring Interview Questions
during an interview. Spring is a very powerful framework that allows building
enterprise-level web applications. Applications developed using Spring are
generally quick, scalable, and transparent. Due to this, Spring has been embraced
by a huge Java Developer’s community thereby making it an inevitable part of any
Java Developer’s Job Role. Knowing Spring ensures that an added advantage is
with the developers to progress steadily in their careers too.
Tip: We also recommend reading guides postedhere.
Spring MCQ
1. Which among the below options needs to be registered for
loading the application’s root context at start time?
ContextLoaderListener
ContextLoaderStarter
RootContextListener
RootContextTrigger
2. Which method is used for shutting down IoC container in
Spring?
https://www.interviewbit.com/spring-interview-questions/ 37/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
registerHook(shutdown)
shutdownHook(true)
registerShutdownHook()
shutdownHandlerHook()
3. What are the types of autowire in Spring? Choose the
correct option.
byName, byType, destructor, and autodetect
byMethod, byName, autocorrect, and autodetect
byName, byType, byValue, and autodetect
byName, byType, constructor, and autodetect
4. Which method allows to start a new transaction in Spring?
startSession()
getTransaction()
startNewTransaction()
getSession()
5. What attribute is used for handling web request flow?
servlet-mapping
https://www.interviewbit.com/spring-interview-questions/ 38/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
servlet-attr
servlet-flow
servlet-flow-request
6. What advice is run once joint-point execution is complete?
@AfterFinish
@AfterJoint
@AfterPoint
@After
7. What is the output of the below code?
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
public class SampleAspectClass {
@AfterThrowing(pointcut="com.interviewbit.Oper
public void doRecoveryActions(DataAccessExcept
throw new IllegalArgumentException();
}
}
IllegalArgumentException
BeanCreationException
Runtime Error
https://www.interviewbit.com/spring-interview-questions/ 39/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
NullPointerException
8. Which method gives warning from the compiler resulting
from List to List unchecked conversion?
createNativeQuery()
findAll()
updateAll()
batchUpsert()
9. What annotation is used for finding transaction and failing it
by complaining no Hibernate session is bound to thread?
@TransactionFail
@TransactionHandler
@TransactionResolver
@Transactional
10. What property is used for loading hibernate configuration
files by the factory bean?
configLocation
config
config.xml
https://www.interviewbit.com/spring-interview-questions/ 40/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
hbm-config
11. Which of the below statements are correct about Spring?
Spring allows developers to develop enterprise-level web applications.
Spring allows developers to code in a modular way.
Spring ensures that application testing is made simple.
All of the above
12. What does the byName type of autowiring do?
byName mode means there is no autowiring and explicit reference needs to be
added.
byName mode ensures that the autowiring is done by means of the property name.
Spring matches and wires the properties with beans of the same name defined in
the configuration file.
In this mode, Spring first autowires by the constructor and if not found, it tries to
autowire by type.
This mode is similar to byType mode but is restricted to non-parameterised
constructors.
13. Which among the below classes is used for mapping
database row to java object in Spring?
RowMapper
ResultSet
https://www.interviewbit.com/spring-interview-questions/ 41/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
RowSetMapper
ResultSetMapper
14. What class is used for giving a class behaviour of
DispatcherServlet?
Repository
AbstractAction
AbstractController
Controller
15. Which among the below is the Handler method annotation
in Spring?
@RequestMapping
@Controller
@Service
@Resolve
16. What method arguments are used in handler methods
using @RequestMapping?
@Controller
@Bean
https://www.interviewbit.com/spring-interview-questions/ 42/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
@RequestParam
@Service
17. Which among the ViewResolvers resolves the view name
to the application’s directory?
InternalResolver
InternalViewResolver
InternalRequestResolver
InternalResourceViewResolver
18. Which among the below annotation represents that a field
can't be null?
@NotEmpty
@NotNull
@NeverNull
All of the above
19. What annotation receives values in the form of regular
expression?
@Pattern
@Password
https://www.interviewbit.com/spring-interview-questions/ 43/44
3/25/23, 10:53 PM Spring Interview Questions and Answers (2023) - InterviewBit
@Email
@Valid
20. What is used to notify the completion of the session
processing?
BindingResult
HttpStatus
SessionStatus
Session
https://www.interviewbit.com/spring-interview-questions/ 44/44