Spring Based Interview Questions
Spring Based Interview Questions
3. What are the different types of dependency injection? Explain with examples.
There are two types of dependency injection: setter injection and constructor
injection.
Setter Injection: Normally in all the java beans, we will use setter and getter
method to set and get the value of property as follows:
We will create an instance of the bean 'namebean' (say bean1) and set property as
bean1.setName("tom"); Here in setter injection, we will set the property 'name' in
spring configuration file as shown below:
The subelement < value > sets the 'name' property by calling the set method as
setName("tom"); This process is called setter injection.
We will set the property 'name' while creating an instance of the bean 'namebean'
as namebean bean1 = new namebean("tom");
Here we use the < constructor-arg > element to set the property by constructor
injection as
< bean id="bean1" class="namebean" >
< constructor-arg >
< value > My Bean Value < / value >
< / constructor-arg >
< / bean >
4. What is spring? What are the various parts of spring framework? What are the
different persistence frameworks which could be used with spring?
Spring is an open source framework created to address the complexity of enterprise
application development. One of the chief advantages of the Spring framework is its
layered architecture, which allows you to be selective about which of its
components you use while also providing a cohesive framework for J2EE application
development. The Spring modules are built on top of the core container, which
defines how beans are created, configured, and managed. Each of the modules (or
components) that comprise the Spring framework can stand on its own or be
implemented jointly with one or more of the others. The functionality of each
component is as follows:
The core container: The core container provides the essential functionality of the
Spring framework. A primary component of the core container is the BeanFactory,
an implementation of the Factory pattern. The BeanFactory applies the Inversion of
Control (IOC) pattern to separate an application’s configuration and dependency
specification from the actual application code.
Spring context: The Spring context is a configuration file that provides context
information to the Spring framework. The Spring context includes enterprise
services such as JNDI, EJB, e-mail, internalization, validation, and scheduling
functionality.
Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception
hierarchy for managing the exception handling and error messages thrown by
different database vendors. The exception hierarchy simplifies error handling and
greatly reduces the amount of exception code you need to write, such as opening
and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its
generic DAO exception hierarchy.
Spring ORM: The Spring framework plugs into several ORM frameworks to provide
its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of
these comply to Spring’s generic transaction and DAO exception hierarchies.
Spring Web module: The Web context module builds on top of the application
context module, providing contexts for Web-based applications. As a result, the
Spring framework supports integration with Jakarta Struts. The Web module also
eases the tasks of handling multi-part requests and binding request parameters to
domain objects.
5. What is AOP? How does it relate with IOC? What are different tools to utilize
AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows
programmers to modularize crosscutting concerns, or behaviour that cuts across
the typical divisions of responsibility, such as logging and transaction management.
The core construct of AOP is the aspect, which encapsulates behaviours affecting
multiple classes into reusable modules. AOP and IOC are complementary
technologies in that both apply a modular approach to complex problems in
enterprise application development. In a typical object-oriented development
approach you might implement logging functionality by putting logger statements in
all your methods and Java classes. In an AOP approach you would instead
modularize the logging services and apply them declaratively to the components
that required logging. The advantage, of course, is that the Java class doesn't need
to know about the existence of the logging service or concern itself with any related
code. As a result, application code written using Spring AOP is loosely coupled. The
best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the
byte code level and you need to use AspectJ compiler to get the aop features built
into your compiled code. Nevertheless AOP functionality is fully integrated into the
Spring context for transaction management, logging, and various other features. In
general any AOP framework control aspects in three possible ways:
7. Can you name a tool which could provide the initial ant files and directory
structure for a new spring project?
Appfuse or equinox.
This line tells the bean factory to read the bean definition from the XML file. The
bean definition includes the description of beans and their properties. But the bean
factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory',
the getBean() method is called. When getBean() method is called, factory will
instantiate the bean and begin setting the bean's properties using dependency
injection.
19. What is hibernate session and session factory? How do you configure
sessionfactory in spring configuration file?
Hibernate Session is the main runtime interface between a Java application and
Hibernate. SessionFactory allows applications to create hibernate session by
reading hibernate configurations file hibernate.cfg.xml.
A Hibernate Session object represents a single unit-of-work for a given data store
and is opened by a SessionFactory instance. You must close Sessions when all work
for a transaction is completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (UserInfo)session.load(UserInfo.class, id);
tx.commit();
} catch(Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}
20. What is the difference between hibernate get and load methods?
The load() method is older; get() was added to Hibernate’s API due to user request.
The difference is trivial:
The following Hibernate code snippet retrieves a User object from the database:
User user = (User) session.get(User.class, userID);
The get() method is special because the identifier uniquely identifies a single
instance of a class. Hence it’s common for applications to use the identifier as a
convenient handle to a persistent object. Retrieval by identifier can use the cache
when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class, userID);
If load() can’t find the object in the cache or database, an exception is thrown. The
load() method never returns null. The get() method returns
null if the object can’t be found. The load() method may return a proxy instead of a
real persistent instance. A proxy is a placeholder instance of a runtime-generated
subclass (through cglib or Javassist) of a mapped persistent class, it can initialize
itself if any method is called that is not the mapped database identifier getter-
method. On the other hand, get() never returns a proxy. Choosing between get()
and load() is easy: If you’re certain the persistent object exists, and nonexistence
would be considered exceptional, load() is a good option. If you aren’t certain there
is a persistent instance with the given identifier, use get() and test the return value
to see if it’s null. Using load() has a further implication: The application may
retrieve a valid reference (a proxy) to a persistent instance without hitting the
database to retrieve its persistent state. So load() might not throw an exception
when it doesn’t find the persistent object in the cache or database; the exception
would be thrown later, when the proxy is accessed.
22. What is lazy loading and how do you achieve that in hibernate?
Lazy setting decides whether to load child objects while loading the Parent Object.
You need to specify parent class.Lazy = true in hibernate mapping file. By default
the lazy loading of the child objects is true. This make sure that the child objects
are not loaded unless they are explicitly invoked in the application by calling
getChild() method on parent. In this case hibernate issues a fresh database call to
load the child when getChild() is actually called on the Parent object. But in some
cases you do need to load the child objects when parent is loaded. Just make the
lazy=false and hibernate will load the child when parent is loaded from the
database. Examples: Address child of User class can be made lazy if it is not
required frequently. But you may need to load the Author object for Book parent
whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy
association outside of the context of an open Hibernate session will result in an
exception.
Join fetching - Hibernate retrieves the associated instance or collection in the same
SELECT, using an OUTER JOIN.
By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property
hibernate.cache.use_query_cache to true in hibernate.properties.
27. What is the difference between sorted and ordered collection in hibernate?
A sorted collection is sorted in-memory using java comparator, while order
collection is ordered at the database level using order by clause.
28. What are the types of inheritance models and describe how they work like
vertical inheritance and horizontal?
There are three types of inheritance mapping in hibernate:
Example: Let us take the simple example of 3 java classes. Class Manager and
Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions: In this case there will be 2 tables. Tables:
Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy.
There will be only one table in database called 'Employee' that will represent all the
attributes required for all 3 classes. But it needs some discriminating column to
differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee,
Manager and Worker