Op 100 Spring Interview Questions and Answers (Part 1)
Op 100 Spring Interview Questions and Answers (Part 1)
It has many extensions and jars for developing web applications on top of Java EE platform.
With Spring we can develop large-scale complex Java applications very easily. It is also
based on good design patterns like Dependency Injection, Aspect oriented programming
for developing extensible feature rich software.
Core module
Bean module
Context module
Spring Expression Language module
12.What are the benefits of JDBC abstraction layer module in Spring framework?
Spring provides JDBC abstraction layer module. Main benefits of this module are:
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.
Developer provides configuration metadata to Spring container for creating and managing
the lifecycle of Spring Bean.
In general a Spring Bean is singleton. Evert bean has an attribute named “singleton”. If its
value is true then bean is a singleton. If its value is false then bean is a prototype bean.
By default the value of this attribute is true. Therefore, by default all the beans in spring
framework are singleton in nature.
1 <bean id="userService"
class="com.um.UserService"
scope="prototype"/>
This is an example of userService bean with prototype scope.
36. Is it safe to assume that a Singleton bean is thread safe in Spring Framework?
No, Spring framework does not guarantee anything related to multithreaded
behavior of a singleton bean. Developer is responsible for dealing with concurrency
issues and maintaining thread safety of a singleton bean.
39. What are the two main groups of methods in a Bean’s lifecycle?
A Bean in Spring has two main groups of lifecycle methods.
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.
Destruction Callbacks: When the Container of a Bean is destroyed, it calls the methods in
DisposableBean to do any cleanup work. There is a method called destroy() that can be
used for this purpose to make Destruction Callbacks.
Recent recommendation from Spring is to not use these methods, since it can strongly
couple your code to Spring code.
1 <bean id="employee"
2 class="com.dept.Employee">
3 <property name="manager"
4 ref="manager" />
</bean>
<bean id="manager"
class="com.dept.Manager" />
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.
E.g. In following example, Manager bean is wired to Employee bean by Name.
1 <bean id="employee"
2 class="com.dept.Employee" autowire="byName"
/>
<bean id="manager"
class="com.dept.Manager" />
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.
E.g. In following example, Manager bean is wired by type toEmployee bean.
1 <bean id="employee"
2 class="com.dept.Employee"
autowire="byType" />
<bean id="manager"
class="com.dept.Manager" />
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.
E.g. In following example “constructor” mode is used for autowiring.
1 <bean id="employee"
2 class="com.dept.Employee"
autowire="constructor" />
<bean id="manager"
class="com.dept.Manager" />
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.
E.g. This is an example of autodetect Autowiring.
1 <bean id="employee"
2 class="com.dept.Employee"
autowire="autodetect" />
<bean id="manager"
class="com.dept.Manager" />
46. What are the cases in which Autowiring may not work in Spring framework?
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.
50. 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.
In the “lite” mode, @Bean methods cannot declare inter-bean dependencies.
It is recommended that one @Bean method should not invoke another @Bean method in
‘lite’ mode.
Spring recommends that @Bean methods declared within @Configuration classes should be
used for full configuration. This kind of full mode can prevent many bugs.
Spring container can use this information from annotation for creating and wiring the
beans.
configuration file.
E.g.
1 <beans
2 ...
3 xmlns:context="http://www.springframework.or
4 g/schema/context"
5 ...
6 http://www.springframework.org/schema/conte
7 xt
8 http://www.springframework.org/schema/conte
9 xt/spring-context-2.5.xsd">
10 ...
<context:annotation-config />
...
</beans>
Include RequiredAnnotationBeanPostProcessor in bean configuration file
E.g.
1 <beans
2 xmlns="http://www.springframework.org/schem
3 a/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchem
5 a-instance"
6 xsi:schemaLocation="http://www.springframew
7 ork.org/schema/beans
8 http://www.springframework.org/schema/beans
9 /spring-beans- 2.5.xsd">
10 <beanclass="org.springframework.beans.f
11 actory.annotation.RequiredAnnotationBean
12 P
13 <bean id="BookBean" class="com.foo.Book">
<property name="action" value="price" />
<property name="type" value="1" />
</bean>
<bean id="AuthorBean"
class="com.foo.Author">
<property name="name" value="Rowling" />
</bean>
</beans>
56. 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.
1. It makes it easier to work on different data access methods likeJDBC, Hibernate etc.
2. It provides a consistent and common way to deal with different data access
methods.
3. Spring DAO makes it easier to switch between different data persistence
frameworks.
4. No need for catching framework specific exceptions.
63. What are the different types of the Transaction Management supported by Spring
framework?
Spring framework provides support for two types of Transaction Management:
68.In Spring AOP, what is the main difference between a Concern and a Cross cutting
concern?
A Concern in Spring is the behavior or expectation from an application. It can be the
main feature that we want to implement in the application.
A Cross cutting concern is also a type of Concern. It is the feature or functionality
that is spread throughout the application in a thin way. E.g. Security, Logging,
Transaction Management etc. are cross cutting concerns in an application.
21. Before Advice: This type of advice runs just before a method executes. We can use
@Before annotation for this.
22. 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.
23. After Returning Advice: This type of advice runs after a method executes successfully.
@AfterReturning annotation can be used here.
24. After Throwing Advice: This type of advice runs after a method executes and throws
an exception. The annotation to be used is @AfterThrowing.
25. Around Advice: This type of advice runs before and after the method is invoked. We
use @Around annotation for this.
1 <beans
2 xmlns="http://www.springframework.org/schem
3 a/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchem
5 a-instance"
6 xmlns:aop="http://www.springframework.org/sc
hema/aop"
xsi:schemaLocation="http://www.springframew
ork.org/schema/beans
http://www.springframework.org/schema/beans
/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/s
pring-aop-3.0.xsd">
80. What is Annotation-based aspect implementation in Spring AOP?
This is a declarative style AOP implementation. In this case, we use annotations like
@Aspect, @Pointcut, @Joinpoint etc. to annotate code with different types of AOP
elements.
This can be used Java 5 onwards, when the support for Annotations was introduced.
82.What is DispatcherServlet?
In Spring MVC, DispatcherServlet is the core servlet that is responsible for handling
all the requests and dispatching these to handlers.
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.
In case of RMI invocation, it sends back response to the client application.
1 @RequestMapping(
2 value = "/test/mapping",
3 method = GET,
4 headers = "Accept=application/json")
87.What are the main features of Spring MVC?
Spring MVC has following main features:
1. Clear separation of role: In Spring MVC, each role like- controller, validator, command
object, form
object, model object, DispatcherServlet, handler mapping, view resolver etc. is fulfilled by a
specialized object.
2. Reusability: Spring MVC promotes reusable business code that reduces the need for
duplication. We can use existing business objects as command or form objects instead of
copying them to extend a particular framework base class.
3. Flexible Model Transfer: Spring MVC Model transfer supports easy integration with other
view technologies as well.
4. Customizable binding and validation: In Spring MVC, we can to custom binding between
Requests and Controllers. Even validation can be done on non-String values as well.
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.
6. Customizable locale, time zone and theme resolution: Spring MVC supports
customization in locale, timezone etc.
88. What is the difference between a Singleton and Prototype bean in Spring?
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.
This single instance is limited to a specific ApplicationContext. If there are multiple
ApplicationContext then we can have more than one instance of bean.
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.
89.How will you decide which scopePrototype 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.
In a stateful bean, there is a need to maintain the state in each request, it is
necessary to use a new instance of object with each call. A Prototype scope bean
ensures that we get a new instance each time we request for the object.
90. What is the difference between Setter and Constructor based Dependency
Injection (DI) in Spring
framework?
Main differences between Setter and Constructor based Dependency Injection (DI) in
Spring are:
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.
Readability: Setter injection is more readable than Constructor injection. Generally
Setter method name is similar to dependency class being used in setter method.
91.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.
No Guarantee: In Setter based DI, there is no guarantee that a certain dependency is
injected or not. We may have an object with partial or no dependency. Whereas in
Constructor based DI, an object in not created till the time all the dependencies are ready.
Security: One can use Setter based DI to override another dependency. This can cause
Security breach in a Spring application.
Circular Dependency: Setter based DI can cause circular dependency between objects.
Where as Constructor based DI will throw ObjectCurrentlyInCreationException if there is a
circular dependency during the creation of an object.
92. What are the differences between Dependency Injection (DI) and Factory Pattern?
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.
Flexibility: DI allows for switching between different DI frameworks easily. It gives flexibility
in the choice of DI framework.
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.
94. Name some popular Spring framework annotations that you use in your project?
Spring has many Annotations to serve different purposes. For regular use we refer
following popular Spring annotations:
@Controller: This annotation is for creating controller classes in a Spring MVC project.
@RequestMapping: This annotation maps the URI to a controller handler method in Spring
MVC.
@ResponseBody: For sending an Object as response we use this annotation.
@PathVariable: To map dynamic values from a URI to handler method arguments, we use
this annotation.
@Autowired: This annotation indicates to Spring for auto-wiring dependencies in beans.
@Service: This annotation marks the service classes in Spring.
@Scope: We can define the scope of Spring bean by this annotation.
@Configuration: This an annotation for Java based Spring configuration.
@Aspect, @Before, @After, @Around, @Joinpoint, @Pointcut: These are the annotations in
Spring for AspectJ AOP.
96. What are the different types of events provided by Spring framework?
Spring framework provides following five events for Context:
ContextRefreshedEvent: Whenever ApplicationContext is initialized or refreshed, Spring
publishes this event. We can also raise it by using refresh() method on
ConfigurableApplicationContext interface.
ContextStartedEvent: When ApplicationContext is started using start() method on
ConfigurableApplicationContext interface, ContextStartedEvent is published. We can poll
database or restart
any stopped application after receiving this event.
ContextStoppedEvent: Spring publishes this event when ApplicationContext is stopped
using stop() method on ConfigurableApplicationContext interface. This is used for doing
any cleanup work.
ContextClosedEvent: Once the ApplicationContext is closed using close() method,
ContextClosedEvent is published. Once a context is closed, it is the last stage of its lifecycle.
After this it cannot be refreshed or restarted.
RequestHandledEvent: This is a web specific event that informs to all beans that an HTTP
request has been serviced.
Spring Boot is a ready made solution to create Spring applications with production grade
features. It favors convention over configuration.
We can embed Tomcat or Jetty in in an application created with Spring Boot. Spring Boot
automatically configures Spring in an application.
It does not require any code generation or xml configuration. It is an easy solution to create
applications that can run stand-alone.
That’s all about Spring Interview Questions and Answers. You might study more about the
Spring framework tutorials
In simple words, it is a framework to retrieve and store data from database tables from
Java.
8.How will you map the columns of a DB table to the properties of a Java class in
Hibernate?
We can map the class properties and table columns by using one of the two ways:
XML: We can map the column of a table to the property of a class in XML file. It is generally
with extension hbm.xml
Annotation: We can also use annotations @Entity and @Table to map a column to the
property of a class.
9.Does Hibernate make it mandatory for a mapping file to have .hbm.xml extension?
No. It is a convention to have.hbm.xml extension in the name of a mapping file. It is
not a requirement enforced by Hibernate. We can use any other extension of our
convenience for this.
1 Query query
2 =session.getNamedQuery("callEmployeeStorePr
3 ocedure")
4 .setParameter("employeeId", “1234”);
5 List result = query.list();
6 for(int i=0; i<result.size(); i++){
7 Employee employee =
(Employee)result.get(i);
System.out.println(employee.getEmployeeCode(
));
}
Native SQL: We can use Native SQL to call a store procedure query directly. In this example
GetEmployees() stored procedure is being called.
System.out.println(employee.getEmployeeCode(
));
}
Use annotation: We can also mark out stored procedure with @NamedNativeQueries
annotation.
1 //Employee.java
2 @NamedNativeQueries({
3 @NamedNativeQuery(
4 name = "callEmployeeStoreProcedure",
5 query = "CALL GetEmployees(:employeeId)",
6 resultClass = Employee.class
7 )})
8 @Entity@Table(name = "employee")
9 public class Employee implements
10 java.io.Serializable {
...
Call it with getNamedQuery().
1 Query query =
2 session.getNamedQuery("callEmployeeStoreProc
3 edure")
4 .setParameter("employeeId", “1234”);
5 List result = query.list();
6 for(int i=0; i<result.size(); i++){
7 Employee employee =
(Employee)result.get(i);
System.out.println(employee.getEmployeeCode(
));
}
14. What is Criteria API in Hibernate?
Criteria is a simplified API in Hibernate to get entities from database by creating
Criterion objects.
It is a very intuitive and convenient approach for search features.
Users can specify different criteria for searching entities and Criteria API can handle
these.
Criterion instances are obtained through factory methods on Restrictions.
16. How can you see SQL code generated by Hibernate on console?
To display the SQL generated by Hibernate, we have to turn on the show_sql flag.
This can be done in Hibernate configuration as follows:
1 <property
name=”show_sql”>true</property>
17. What are the different types of collections supported by Hibernate?
Hibernate supports following two types of collections:
Indexed Collections: List and Maps
Sorted Collections: java.util.SortedMap and java.util.SortedSet
28. What are the different types of Association mappings supported by Hibernate?
Hibernate supports following four types of Association mappings:
Unidirectional association: This kind of association works in only one
direction.Unidirectional association with join tables
Bidirectional association: This kind of association works in both directions. Bidirectional
association with join tables
Many to one
One to one
One to many
32. How will you order the results returned by a Criteria in Hibernate?
Hibernate provides an Order criterion that can be used to order the results. This can
be order objects based on their property in ascending or descending order. Class is
org.hibernate.criterion.Order. One example is as follows:
Egg.
1 List employees =
2 session.createCriteria(Employee.class)
3 .add( Restrictions.like("name", "F%")
4 .addOrder( Order.asc("name") )
5 .addOrder( Order.desc("age") )
6 .setMaxResults(10)
.list();
33. How does Example criterion work in Hibernate?
In Hibernate, we can create an object with desired properties. Then we can use this
object to search for objects with similar object. For this we can use
org.hibernate.criterion.Example criterion.
Egg. First we create a sample book object of author Richard and category mystery.
Then we search for similar books.
1 Session s = null;
2 Transaction trans = null;
3 try {
4 s = sessionFactory.openSession();
5 trans = s.beginTransaction();
6 doTheAction(s);
7 trans.commit();
8 } catch (RuntimeException exc) {
9 trans.rollback();
10 } finally {
11 s.close();
12 }
35. How can we mark an entity/collection as immutable in Hibernate?
In Hibernate, by default an entity or collection is mutable. We can add, delete or
update an entity/collection.
To mark an entity/collection as immutable, we can use one of the following:
@Immutable: We can use the annotation @Immutable to mark an entity/collection
immutable.
XML file: We can also set the property mutable=false in the XML file for an entity to make it
immutable.
36. What are the different options to retrieve an object from database in Hibernate?
In Hibernate, we can use one of the following options to retrieve objects from
database:
Identifier: We can use load() or get() method and pass the identifier like primary key to
fetch an object from database.
HQL: We can create a HQL query and get the object after executing the query.
Criteria API: We can use Criteria API to create the search conditions for getting the objects
from database.
Native SQL: We can write native SQL query for a database and just execute it to get the
data we want and convert it into desired object.
1 @Id
2 @GeneratedValue(strategy=GenerationType.AUT
3 O)
private int id;
We can leave it null/0 while persisting and Hibernate automatically generates a primary key
for us.
Sometimes, AUTO strategy refers to a SEQUENCE instead of an IDENTITY .
40. What are the different second level caches available in Hibernate?
In Hibernate, we can use different cache providers for implementing second level cache at
JVM/SessionFactory level. Some of these are:
Hashtable
EHCache
OSCache
SwarmCache
JBoss Cache 1.x
JBoss Cache 2
42. What are the options to disable second level cache in Hibernate?
This is a trick question. By default Second level cache is already disabled in
Hibernate.
In case, your project is using a second level cache you can use one of the following
options to disable second level cache in Hibernate:
We can set hibernate.cache.use_second_level_cache to false.
We can use CacheMode.IGNORE to stop interaction between the session and second-level
cache. Session will interact with cache only to invalidate cache items when updates occur
44. What is the difference between Immediate fetching and Lazy collection fetching?
In Immediate fetching an association, collection or attribute is retrieved at the same
time when the owner is loaded.But in Lazy collection fetching, a collection is fetched
only when an operation is invoked on that collection by client application.
This is the default fetching strategy for collections in Hibernate. Lazy fetching is
better from performance perspective.
46. How can we check is a collection is initialized or not under Lazy Initialization
strategy?
Hibernate provides two convenient methods, Hibernate.initialize() and
Hibernate.isInitialized() to check whether a collection is initialized or not.
By using Hibernate.initialize() we can force the initialization of a collection in
Hibernate.
47. What are the different strategies for cache mapping in Hibernate?
Hibernate provides following strategies for cache mapping:
Read only: If an application requires caching only for read but not for write operations,
then we can use this strategy. It is very simple to use and give very good performance
benefit. It is also safe to use in a cluster environment.
Read/Write: If an application also needs caching for write operations, then we use
Read/Write strategy.
Read/write cache strategy should not be used if there is requirement for serializable
transaction isolation level. If we want to use it in a cluster environment, we need to
implement locking mechanism.
Nonstrict Read/Write: If an application only occasionally updates the data, then we can use
this strategy. It cannot be used in systems with serializable transaction isolation level
requirement.
Transactional: This strategy supports full transactional cache providers like JBoss
TreeCache.
1 <property name="profitMargin"
formula="( SELECT (i.salePrice – i.buyPrice)
FROM item i WHERE i.Id = Id)"/>
56. How can we use Named Query in Hibernate?
A Named SQL query is the HQL query that is associated with a string name and can
be referenced in the application by name. It can be used in following ways:
XML Mapping File: We can define it in XML mapping file.
Egg.
1 <query name="findBookByAuthor”>
2 <![CDATA[from Book s where s.author =
3 :author]]>
</query>
Annotation: We can also mark Named SQL with annotation.
1 @NamedQueries({
2 @NamedQuery(
3 name = "findBookByAuthor”,
4 query = "from Book s where s.author = :author”
5 )
6 })
57. What are the two locking strategies in Hibernate?
There are two popular locking strategies that can be used in Hibernate:
Optimistic: In Optimistic locking we assume that multiple transactions can complete
without affecting each other. So we let the transactions do their work without locking the
resources initially.
Just before the commit, we check if any of the resource has changed by another
transaction, then we throw exception and rollback the transaction.
Pessimistic: In Pessimistic locking we assume that concurrent transactions will conflict
while working with same resources. So a transaction has to first obtain lock on the
resources it wants to update.
The other transaction can proceed with same resource only after the lock has been
released by previous transaction.
58. What is the use of version number in Hibernate?
Version number is used in optimistic locking in Hibernate. When a transaction
modifies an object, it increments its version. Based on version number, second
transaction can determine if the object it has
read earlier has changed or not.
If the version number at the time of write is different than the version number at
the time of read, then we should not commit the transaction.