General Spring Interview Questions
General Spring Interview Questions
Spring 2.5 This version was released in 2007. It was the first version
which supported annotations.
Spring 3.0 This version was released in 2009. It made full-fledged use of
improvements in Java5 and also provided support to JEE6.
Spring 4.0 This version was released in 2013. This was the first version
to provide full support to Java 8.
2. What is a Spring Framework?
5. How many modules are there in Spring Framework and what are they?
There are around 20 modules which are generalized into Core Container, Data
Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and
Test.
● Spring Core Container – This layer is basically the core of Spring Framework. It
contains the following modules :
a. Spring Core
b. Spring Bean
c. SpEL (Spring Expression Language)
d. Spring Context
● Data Access/Integration – This layer provides support to interact with the
database. It contains the following modules :
a. JDBC (Java DataBase Connectivity)
b. ORM (Object Relational Mapping)
c. OXM (Object XML Mappers)
d. JMS (Java Messaging Service)
e. Transaction
● Web – This layer provides support to create web application. It contains the
following modules :
a. Web
b. Web – MVC
c. Web – Socket
d. Web – Portlet
● Aspect Oriented Programming (AOP) – In this layer you can use Advices,
Pointcuts etc., to decouple the code.
● Instrumentation – This layer provides support to class instrumentation and
classloader implementations.
● Test – This layer provides support to testing with JUnit and TestNG.
● Constructor Injection
● Setter Injection
● Interface Injection
It will create a new instance if any It will not create new instance if any
modification is done. modification is done.
It works better for many properties. It works better for few properties.
13. How many types of IOC containers are there in spring?
a. BeanFactory: BeanFactory is like a factory class that contains a collection of
beans. It instantiates the bean whenever asked for by clients.
b. ApplicationContext: The ApplicationContext interface is built on top of the
BeanFactory interface. It provides some extra functionality on top BeanFactory.
BeanFactory ApplicationContext
It explicitly provides a resource object using the syntax It creates and manages resource objects on its own
The @Controller annotation is used in the Spring Framework for Java to mark a class
as a controller component. It is part of the Spring MVC (Model-View-Controller)
architecture, which is used to build web applications in a structured and organized way.
When you annotate a class with @Controller, Spring recognizes it as a controller and
allows it to handle HTTP requests and generate HTTP responses. Controllers are
responsible for processing user requests, interacting with the application’s business
logic (services), and returning the appropriate view to render the response.
Yes, you can create a controller in Spring without using the @Controller or
@RestController annotations. The @Controller and @RestController annotations are
just convenience annotations that provide specific functionalities, but you can achieve
the same functionality by using other annotations or configuration.
To create a controller without using @Controller or @RestController, you can use the
following approach:
● Implement the Controller Logic: Create a regular Java class that contains the
logic for handling HTTP requests and generating responses.
● Use Appropriate Annotations: Instead of @Controller or @RestController, you
can use other annotations to specify the request mappings and the response
type.
19. What is ContextLoaderListener and what does it do?
@requestParam @pathVariable
Purpose Extracts query parameters from the Extracts values from the URI
URL’s query string. path itself (URL template).
Use Case Suitable for optional parameters or Useful for extracting dynamic
data in the query string. values from the URL path.
21. What is the use of @Autowired annotation?
The key role of @ModelAttribute is to facilitate data transfer between the Controller and
the View. It allows you to pre-populate form data when displaying forms to users and
automatically bind user inputs to model attributes when processing form submissions.
Additionally, it helps in adding common attributes (like reference data) to the model
across multiple controller methods.
The web.xml file in Spring MVC is used for configuring the DispatcherServlet, defining
context parameters, filters, and listeners, as well as handling error pages. While newer
Spring applications rely more on annotation-based configuration, web.xml remains
essential for certain settings and legacy support.
The session scope in Spring is an important mechanism for managing beans in web
applications. It allows you to create and maintain a separate instance of a bean for each
user session, ensuring that data associated with a specific user is preserved throughout
their interactions with the application.
The @Required annotation was used in earlier versions of Spring to indicate that a
property of a bean must be set (or wired) with a value before the bean can be fully
initialized. However, starting from Spring 3.0, the @Required annotation has been
deprecated and is no longer recommended for use.
@autowired @inject
Yes, singleton beans in Spring are thread-safe by default. When you define a bean with
singleton scope in Spring, the container ensures that only one instance of that bean is
created and shared across all requests within the container’s context.
Yes, singleton beans in Spring are thread-safe by default. When you define a bean with
singleton scope in Spring, the container ensures that only one instance of that bean is
created and shared across all requests within the container’s context.
singleton beans in Spring are thread-safe as long as they are stateless or properly
synchronized when dealing with mutable state. The Spring container manages singleton
bean instantiation and synchronization to ensure their thread safety within the context.
The root application context in Spring MVC is loaded automatically during web
application startup by the ContextLoaderListener. It handles overall configuration and
bean management for the application, while the DispatcherServlet handles web-specific
components and request handling.
33. How does the Spring MVC flow look like? In other words, How does a
DispatcherServlet know what Controller needs to be called when there is an incoming
request to the Spring MVC?
The Spring MVC flow involves several components working together to handle incoming
requests and route them to the appropriate controllers for processing.
The DispatcherServlet plays a central role in the Spring MVC flow. It receives incoming
requests, selects the appropriate controller based on the URL mapping, invokes the
controller method to handle the request, prepares the model data and view, resolves the
view, and finally sends the response back to the client. The flow is orchestrated through
a combination of handler mappings, controllers, view resolvers, and views, allowing
Spring MVC to handle various types of requests and produce dynamic responses.
34. Where does the access to the model from the view come from?
In Spring MVC, the Model object acts as a container to pass data from the Controller to
the View for rendering. The Model is automatically made available to the View by the
DispatcherServlet, and the View can access the data using expression language or
template-specific syntax. This allows for separation of data handling and presentation
concerns in the application.
BindingResult is used in Spring MVC for data binding and validation. It captures errors
during form submission, helps prevent exceptions, and allows you to handle errors
gracefully by displaying error messages to the user.
Spring Interceptors are components in the Spring MVC framework that allow you to
intercept and process HTTP requests and responses. They provide a way to perform
pre-processing and post-processing tasks before and after the actual request is handled
by a controller or after the response is generated.
The spring-mvc.jar file is not part of the spring-core library, and they serve different
purposes.
● spring-core: This is the core Spring framework, which provides fundamental parts
of the framework such as dependency injection and inversion of control.
● spring-webmvc: This is the Spring MVC framework (typically named as
spring-webmvc.jar not spring-mvc.jar), which is built on top of the core Spring
framework and provides Model-View-Controller (MVC) architecture for building
web applications.
So, if you’re building an application using the Spring MVC framework, you would need
both spring-core and spring-webmvc on your classpath. These libraries are usually
managed by a build tool like Maven or Gradle, and are automatically included when you
specify them as dependencies in your build file.
In the context of Spring MVC, the term “Model” represents the data layer. It is a map
(similar to a java.util.Map) that contains data to be rendered by the View. This data is
typically the outcome of executing your business logic, which you want to show to the
user.
40. How is the form data validation done in Spring Web MVC Framework?
● Defining Validation Rules: Use Bean Validation API (JSR-303) annotations like
@NotNull, @Size, @Min, @Max, etc., on your model fields to set the validation
rules.
● Activating Validation: In your controller, annotate the model attribute with @Valid
when handling the form submission. This triggers the validation process.
● Handling Validation Errors: Spring MVC validates the form data and any errors
are put into a BindingResult object. You can check this object for errors and
handle them accordingly, typically by sending the user back to the form with error
messages.
● Displaying Errors: In your view (e.g., Thymeleaf or JSP), display any validation
error messages from the BindingResult to the user.
41. How to get ServletConfig and ServletContext objects in spring bean?
BeanFactory
ApplicationContext
Internationalization (i18n) and localization (L10n) are important features for applications
that need to support multiple languages or locales. In Spring MVC, these are supported
using a combination of LocaleResolver, LocaleChangeInterceptor, and message source
properties files.
45. How is it possible to use the Tomcat JNDI DataSource in the Spring applications?
container.
3</bean>
1<beans>
2<context:annotation-config/>
4</beans>
For example:
1@Configuration
3{
4@Bean
7}
● Singleton: This provides scope for the bean definition to single instance per
Spring IoC container.
● Prototype: This provides scope for a single bean definition to have any number of
object instances.
● Request: This provides scope for a bean definition to an HTTP-request.
● Session: This provides scope for a bean definition to an HTTP-session.
● Global-session: This provides scope for a bean definition to an Global
HTTP-session.
The last three are available only if the users use a web-aware ApplicationContext.
49. What is the Bean life cycle in Spring Bean Factory Container?
Bean life cycle in Spring Bean Factory Container is as follows:
1. The Spring container instantiates the bean from the bean’s definition in the XML
file.
2. Spring populates all of the properties using the dependency injection, as
specified in the bean definition.
3. The factory calls setBeanName() by passing the bean’s ID, if the bean
implements the BeanNameAware interface.
4. The factory calls setBeanFactory() by passing an instance of itself, if the bean
implements the BeanFactoryAware interface.
5. preProcessBeforeInitialization() methods are called if there are any
BeanPostProcessors associated with the bean.
6. If an init-method is specified for the bean, then it will be called.
7. Finally, postProcessAfterInitialization() methods will be called if there are any
BeanPostProcessors associated with the bean.
Student.java
2{
5}
7{
11}
studentbean.xml
2<property name="person">
4<bean class="com.edureka.Person">
7</bean>
8</property>
9</bean>
52. What do you understand by auto wiring and name the different modes
of it?
The Spring container is able to autowire relationships between the collaborating beans.
That is, it is possible to let Spring resolve collaborators for your bean automatically by
inspecting the contents of the BeanFactory.
Different modes of bean auto-wiring are:
a. no: This is default setting which means no autowiring. Explicit bean reference
should be used for wiring.
b. byName: It injects the object dependency according to name of the bean. It
matches and wires its properties with the beans defined by the same names in
the XML file.
c. byType: It injects the object dependency according to type. It matches and wires
a property if its type matches with exactly one of the beans name in XML file.
d. constructor: It injects the dependency by calling the constructor of the class. It
has a large number of parameters.
e. autodetect: First the container tries to wire using autowire by constructor, if it
can’t then it tries to autowire by byType.
1@Configuration
3{
4@Bean
7}
<beans xmlns="<a
href="http://www.springframework.org/schema/beans">http://www.springframew
ork.org/schema/beans</a>" xmlns:xsi="<a
1href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XM
LSchema-instance</a>" xmlns:context="<a
2href="http://www.springframework.org/schema/context">http://www.springfram
ework.org/schema/context</a>">
3
<context:annotation-config/>
4
<beans ………… />
</beans>
@Component: This marks a java class as a bean. It is a generic stereotype for any
Spring-managed component. The component-scanning mechanism of spring now can
pick it up and pull it into the application context.
@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it
are automatically imported into the Dependency Injection container.
For example:
2{
4@Required
6{this.name=name; }
9}
For Example:
2{
4@Autowired
6{this.name=name; }
8{ return name; }
9}
For example, here we have two classes, Employee and EmpAccount respectively. In
EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.
Employee.java
2{
4@Autowired
6{ this.name=name; }
8{ return name; }
9}
EmpAccount.java
2{
4@Autowired
5@Qualifier(emp1)
7{
9}
10}
a. JdbcTemplate
b. SimpleJdbcTemplate
c. NamedParameterJdbcTemplate
d. SimpleJdbcInsert
e. SimpleJdbcCall
64. What are the ways by which Hibernate can be accessed using Spring?
There are two ways by which we can access Hibernate using Spring:
a. Before: These types of advices execute before the joinpoint methods and are
configured using @Before annotation mark.
b. After returning: These types of advices execute after the joinpoint methods
completes executing normally and are configured using @AfterReturning
annotation mark.
c. After throwing: These types of advices execute only if joinpoint method exits by
throwing an exception and are configured using @AfterThrowing annotation
mark.
d. After (finally): These types of advices execute after a joinpoint method,
regardless of the method’s exit whether normally or exceptional return and are
configured using @After annotation mark.
e. Around: These types of advices execute before and after a joinpoint and are
configured using @Around annotation mark.
72. Point out the difference between concern and cross-cutting concern in
Spring AOP?
The concern is the behavior we want to have in a particular module of an application. It
can be defined as a functionality we want to implement.
74. What are the difference between Spring AOP and AspectJ AOP?
Spring AOP vs AspectJ AOP
Spring AOP AspectJ AOP
Runtime weaving through proxy is done Compile time weaving through AspectJ Java
tools is done