Spring
Spring
Container: Spring framework provides the basic container that creates and manages
the life cycle of application objects like Plain old Java objects (POJO). It also stores
the configuration files of application objects to be created.
Dependency Injection (DI): Spring provided loose coupling is application by
Dependency Injection. It uses Inversion of Control technique by which objects
specify their dependencies to Spring container instead of creating new objects
themselves.
Aspect Oriented Programming (AOP): Spring framework promotes and provides
support for Aspect oriented programming in Java. This helps in separating
application business logic from system services that are common across all the
business logic. E.g. Logging can be a cross cutting concern in an Application.
MVC Framework: For Web applications, Spring provides MVC framework. This
framework is based on MVC design pattern and
has better features compared to other web frameworks.
Exception Handling: Spring also gives support for a common API to handle
exceptions in various technologies like- Hibernate, JDBC etc.
Core module
Bean module
Context module
Spring Expression Language module
112. What are the modules in Data Access/Integration layer of
Spring framework?
As the name suggests, Spring Core Container is the core of Spring framework. It
gives the basic functionality of the Spring. All the parts of Spring Framework are
built on top of Core Container.
Its main use is to provide Dependency Injection (DI) and Inversion of control
(IOC) features.
115. What kind of testing can be done in Spring Test Module?
Spring Test Module provides support for Unit testing as well as Integration testing
of Spring components. It allows using JUnit or TestNG testing frameworks. It also
gives ability to mock objects to use the test code.
116. What is the use of BeanFactory in Spring framework?
Spring container reads bean configuration metadata from an XML file and creates a
fully configured application with the help of XMLBeanFactory class.
AOP module is also known as Aspect Oriented Programming module. Its uses are:
Development of aspects in a Spring based application
Provides interoperability between Spring and other AOP frameworks
Supports metadata programming to Spring
120. What are the benefits of JDBC abstraction layer module in
Spring framework?
Spring provides JDBC abstraction layer module. Main benefits of this module are:
Spring provides support for developing web application by using Web module.
This module is built on application context module that provides context for web-
based applications.
This module also supports integration with popular web frameworks like Jakarta
Struts, JSF, and Tapestry etc.
Spring IoC container uses some kind of configuration metadata. This configuration
metadata represents how an application developer tells the Spring container to
instantiate, configure, and assemble the objects in your application. This
configuration metadata is stored in Spring configuration file.
The other ways of specifying configuration metadata are Java based configuration
and Annotation based configuration.
Most important benefit is that it leads to loose coupling within objects. With loose
coupling it is easier to change the application with new requirements.
IOC Container in Spring supports both the approaches. Eager instantiation as well
as lazy loading of beans.
128. What are the benefits of ApplicationContext in
Spring?
Dependency Injection (DI) applications provide more ease and flexibility of testing.
These can be tested in isolation in Unit Test.
Dependency injection (DI) isolates client from the impact of design and
implementation changes. Therefore, it promotes reusability, testability and
maintainability.
With Dependency Injection, clients are dependent on the configuration data. This
becomes extra task for developers when the application does not need so many
custom configuration values.
A Spring Bean is a plain old Java object (POJO) that is created and managed by a
Spring container.
There can be more than one bean in a Spring application. But all these Beans are
instantiated and assembled by Spring container.
By default, the value of this attribute is true. Therefore, by default all the beans in
spring framework are singleton in nature.
Spring framework support seven types of scopes for a Bean. Out of these only five
scopes are available for a web-aware ApplicationContext application:
singleton: This is the default scope of a bean. Under this scope, there is a single
object instance of bean per Spring IoC container.
prototype: Under this scope a single bean definition can have multiple object
instances.
request: In this scope, a single bean definition remains tied to the lifecycle of a
single HTTP request. Each HTTP request will have its own instance of a bean for a
single bean definition. It is only valid in the context of a web-aware Spring
ApplicationContext.
session: Under this scope, a single bean definition is tied to the lifecycle of an
HTTP Session. Each HTTP Session will have one instance of bean. It is also valid
in the context of a web-aware Spring ApplicationContext.
globalSession: This scope, ties a single bean definition to the lifecycle of a global
HTTP Session. It is generally valid in a Portlet context. It is also valid in the
context of a web-aware Spring ApplicationContext.
In configuration xml, we can specify the scope of bean in its definition. This is used
by container to decide the scope of bean in Spring.
Spring framework uses many Design patterns. Some of these patterns are:
Singleton – By default beans defined in spring config files are singleton. These are
based on Singleton pattern.
Dependency Injection – This pattern is the core behind the design of BeanFactory
and ApplicationContext.
Proxy – Aspect Oriented Programming (AOP) heavily uses proxy design pattern.
View Helper – Spring has multiple options to separating core code from
presentation in views. Like- Custom JSP tags, Velocity macros etc.
146. What is the lifecycle of a Bean in Spring framework?
Initialization and creation: Spring container gets the definition of Bean from XML
file and instantiates the Bean. It populates all the properties of Bean as mentioned
in the bean definition.
Initialization Callbacks: Once all the necessary properties of a Bean are set by the
container, Initialization Callback methods are used for performing initialization
work. A developer can implement method afterPropertiesSet() for this work.
Recent recommendation from Spring is to not use these methods, since it can
strongly couple your code to Spring code.
A bean that is used as a property of another bean is known as Inner bean. It can be
defined as a <bean/> element in <property/> or <constructor-arg/> tags.
It is not mandatory for an Inner bean to have id or a name. These are always
anonymous.
Spring promotes Dependency Injection (DI) in code. It gives support for injecting
not only objects but also collection of objects.
<list> : This type is used for injecting a list of values. In a <list> duplicates are
allowed.
<set> : This type is used for injecting a set of values. As per set property, duplicates
are not allowed.
<map> : This type is used for injecting name-value pairs in form of map. Name and
value can be of any type that is allowed for a map.
no: This is default setting for Autowiring. In this case, we use “ref” mode to
mention the explicit bean that is being referred for wiring.
byName: In this case, Spring container tries to match beans by name during
Autowiring. If the name of a bean is same as the name of bean referred in autowire
byname, then it automatically wires it.
byType: In this case, Spring container check the properties of beans referred with
attribute byType. Then it matches the type of bean and wires. If it finds more than
one such bean of that type, it throws a fatal exception.
constructor: In this case, Spring container looks for byType attribute in constructor
argument. It tries to find the bean with exact name. If it finds more than one bean of
same name, it throws fatal exception. This case is similar to byType case.
autodetect: This is an advanced mode for autowiring. In this case, by default Spring
tries to find a constructor match. If it does not find constructor then it uses autowire
by Type.
Autowiring is a great feature in Spring. It can be used in most of the cases. But
there are certain scenarios in which Autowiring may not work.
Explicit wiring: Since Autowiring is done by Spring, developer does not have full
control on specifying the exact class to be used. It is preferable to use Explicit
wiring in case of full control over wiring.
Primitive Data types: Autowiring does not allow wiring of properties that are based
on primitive data types like- int, float etc.
This annotation is used in a class to indicate that this is class is the primary source
of bean definitions. This class can also contain inter-bean dependencies that are
annotated by @Bean annotation.
158. What is the difference between Full @Configuration and 'lite'
@Beans mode?
Spring allows for using @Bean annotation on methods that are declared in classes
not annotated with @Configuration. This is known as “lite” mode. In this mode,
bean methods can be declared in a @Component or a plain java class without any
annotation.
It is recommended that one @Bean method should not invoke another @Bean
method in 'lite' mode.
Now developer can use annotations like @Required, @Autowired, @Qualifier etc.
in a class file to specify the configuration for beans. Spring container can use this
information from annotation for creating and wiring the beans.
160. How will you switch on Annotation based wiring in Spring?
We use @Required annotation to a property to check whether the property has been
set or not.
E.g.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/be
http://www.springframework.org/schema/beans/spring-beans-
2.5.xsd">
<bean
class="org.springframework.beans.factory.annotation.RequiredAnno
</beans>
164. What is @Qualifier annotation in Spring?
We use @Qualifier annotation to mark a bean as ready for auto wiring. This
annotation is used along with @Autowired annotation to specify the exact bean for
auto wiring by Spring container.
Spring provides a mature JDBC framework to provide support for JDBC coding.
Spring JDBC handled resource management as well as error handling in a generic
way. This reduces the work of software developers.
They just have to write queries and related statements to fetch the data or to store
the data in database.
This class makes it very easy to work with database in our Application and it also
provides good support for custom error handling in database access code.
167. What are the benefits of using Spring DAO?
Hibernate
Java Persistence API (JPA)
TopLink
Java Data Objects (JDO)
Apache Object Relational Bridge (ORB)
170. How will you integrate Spring and Hibernate by using
HibernateDaoSupport?
E.g. To develop banking software, one team can work on business logic for Money
withdrawal, Money deposit, Money Transfer etc. The other team can work on
Transaction Management for committing the transaction across multiple accounts.
In an Auto company, one team can work on software to integrate with different
components of car. The other team can work on how all the components will send
signal and current information to a common dashboard.
175. What is an Aspect in Spring?
An Aspect is the core construct of AOP. It encapsulates the behavior that affects
multiple classes in a reusable module.
E.g. Security, Logging, Transaction Management etc. are cross cutting concerns in
an application.
This is the place where the code of an Aspect is inserted to add new behavior in the
existing execution flow.
An Advice in Spring AOP, is an object containing the actual action that an Aspect
introduces.
1. Before Advice: This type of advice runs just before a method executes.
We can use @Before annotation for this.
2. After (finally) Advice: This type of advice runs just after a method
executes. Even if the method fails, this advice will run. We can use
@After annotation here.
5. Around Advice: This type of advice runs before and after the method is
invoked. We use @Around annotation for this.
A Pointcut in Spring AOP refers to the group of one or more Joinpoints where an
advice can be applied.
We can apply Advice to any Joinpoint. But we want to limit the places where a
specific type of Advice should be applied. To achieve this we use Pointcut.
We can use class names, method names or regular expressions to specify the
Pointcuts for an Advice.
E.g. We can use an Introduction for making a bean implement IsModified interface.
A Target object is the object that gets Advice from one or more Aspects.
In Aspect oriented programming, linking Aspects with the other application types
creates an Advised object. This process is known as Weaving.
Without Weaving, we just have definition of Aspects. Weaving makes use realize
full potential of the AOP.
Spring allows for implementing Aspect by using regular classes and XML based
configurations. This is different from Annotation based Aspect implementation.
But it achieves the same goal of AOP.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/bea
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
188. What is Annotation-based aspect implementation in
Spring AOP?
This can be used Java 5 onwards, when the support for Annotations was
introduced.
Spring provides its own Model View Controller (MVC) framework for developing
web applications.
Dispatcher servlet knows the mapping between the method to be called and the
browser request. It calls the specific method and combines the results with the
matching JSP to create an html document, and then sends it back to browser.
Yes, a Spring MVC web application can have more than one DispatcherServlets.
Each DispatcherServlet has to operate in its own namespace. It has to load its own
ApplicationContext with mappings, handlers, etc.
Only the root application context will be shared among these Servlets.
Controller interprets user input and transforms it into a model. The model is
represented to the user by a view.
The dispatcher in Spring scans for @Controller annotated classes for mapped
methods and detects @RequestMapping.
194. What is @RequestMapping annotation in Spring?
E.g. @RequestMapping(
value = "/test/mapping",
method = GET,
headers = "Accept=application/json")
195. What are the main features of Spring MVC?
5. JSP form tag library: From Spring 2.0, there is a powerful JSP form tag
library that makes writing forms in JSP pages much easier.
Every bean in Spring has a scope that defines its existence timeframe in the
application.
Singleton scope for bean limits a bean to a single object instance per Spring IOC
container.
By default all the beans in Spring framework are Singleton scope beans.
With Prototype scope a single bean definition can have multiple object instances in
a Spring container.
In prototype scope bean, the Spring IoC container creates new bean instance of the
object every time a request for that specific bean is made.
197. How will you decide which scope-Prototype or Singleton to use for a
bean in Spring?
In general, we use prototype scope for all stateful beans and singleton scope for
stateless beans.
Since a stateless bean does not maintain any state, we can use the same object
instance again and again. Singleton scope bean serves the same purpose.
Priority: Setter based injection has higher priority than a constructor based injection
in Spring. If an application uses Setter as well as Constructor injection, Spring
container uses the Setter injection.
Partial dependency: We can inject partial dependency by using Setter injection. In
Constructor injection, it is not possible to do just a partial dependency injection.
E.g. If there are two properties in a class, we can use Setter method to inject just
one property in the class.
Flexibility: Setter injection gives more flexibility in introducing changes. One can
easily change the value by Setter injection. In case of Constructor injection a new
bean instance has to be created always.
199. What are the drawbacks of Setter based Dependency Injection (DI)
in Spring?
Although Setter based Dependency Injection has higher priority than Constructor
based DI, there are some disadvantages of it.
Security: One can use Setter based DI to override another dependency. This can
cause Security breach in a Spring application.
Main differences between Dependency Injection (DI) and Factory Pattern are:
Coupling: Factory pattern adds tight coupling between an object, factory and
dependency. In case of DI, there is no coupling between objects. We just mention
the dependencies on different objects and container resolves and introduces these
dependencies.
Easier Testing: DI is easier to test, since we can inject the mock objects as
dependency in Test environment. In case of Factory pattern, we need to create
actual objects for testing.
Container: DI always needs a container for injecting the dependencies. This leads
to extra overhead as well as extra code in your application. In factory pattern, you
can just use POJO classes to implement the application without any container.
Cleaner Code: DI code is much cleaner than Factory pattern based code. In DI, we
do not need to add extra code for factory methods.
Spring has many Annotations to serve different purposes. For regular use we refer
following popular Spring annotations:
RequestHandledEvent: This is a web specific event that informs to all beans that an
HTTP request has been serviced.
205. What is the difference between DispatcherServlet and
ContextLoaderListener in Spring?
In case we have enabled annotations in Spring config file, it also scans the
packages and configures any bean annotated with @Component, @Controller,
@Repository or @Service annotations.
We can Divide spring bean configurations based on their concerns such as spring-
jdbc.xml, spring-security.xml.
It is better to avoid version numbers in schema reference. This makes sure that we
have the latest config files.
For spring beans that are used in multiple contexts in Spring MVC, we can create
them in root context and initialize with listener.
Spring framework provides many features and modules. We should just use what
we need for our application. An extra dependency has to be removed
For application properties, it is good to create a property file and read it in Spring
configuration file.
Annotations are useful for smaller applications, but for larger applications
annotations can become an overhead. It is easier to maintain if all the
configurations are in xml files.
When we are doing AOP, we have to make sure to keep the Joinpoint as narrow as
possible to avoid Advice on unwanted methods.
We should use right annotation for components or services. For services use
@Service and for DAO beans use @Repository.
Dependency Injection (DI) has to be used when there is real benefit.
It should not be used just for the sake of loose coupling.
208. What is Spring Boot?
It does not require any code generation or xml configuration. It is an easy solution
to create applications that can run stand-alone.