You are on page 1of 23

1

1. What is Dependency injection?


Inversion of control is a design paradigm with the goal of giving more control to the targeted components
of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without
knowing at compile time which class will be used to provide that functionality. Inversion of control relies
on dependency injection because a mechanism is needed in order to activate the components providing
the specific functionality.
The two concepts work together in this way to allow for much more flexible, reusable, and encapsulated
code to be written. As such, they are important concepts in designing object-oriented solutions.
2. What is inversion of control (IoC)
inversion of control (IoC) is a programming technique, expressed here in terms of object-oriented
programming, in which object coupling is bound at run time by an assembler object and is typically not
known at compile time using static analysis.In object-oriented programming, there are several basic
techniques to implement inversion of control.
1. using a factory pattern
2. using a service locator pattern
3. using a dependency injection of any given below type:
a constructor, a setter injection, an interface injection
4. Using a contextualized lookup
5. Using Template method design pattern
6. Using strategy design pattern
3. What is Dependency Injection in spring?
The basic principle behind Dependency Injection (DI) is that objects define their dependencies. Then
container to actually inject those dependencies when it creates the bean.
The basic concept of the Inversion of Control pattern (also known as Dependency Injection (DI)) is that
you do not create your objects but describe how they should be created. You don't directly connect your
components and services together in code but describe which services are needed by which components
in a configuration file.
A container (in the case of the spring framework, the IOC container) is then responsible for hooking it all
up. In a typical IOC scenario, the container creates all the objects, wires them together by setting the
necessary properties, and determines when methods will be invoked.The two major flavors of
Dependency Injection are Setter Injection (injection via JavaBean setters) and Constructor Injection
(injection via constructor arguments).
4. What is spring?
Spring is an open source development framework for enterprise Java. spring is a lightweight inversion of
control and aspect-oriented container framework The core features of the Spring Framework can be used
in developing any Java application, but there are extensions for building web applications on top of the
Java EE platform. Spring framework targets to make J2EE development easier to use and promote good
programming practice by enabling a POJO-based programming model.
5. Overview of the Spring Framework
Core package is the most fundamental part of the framework and provides the IoC and Dependency
Injection features. The basic concept here is the BeanFactory, which provides a sophisticated

2
implementation of the factory pattern which removes the need for programmatic singletons and allows
you to decouple the configuration and specification of dependencies from your actual program logic.
BeanFactory create object for you based on XML configuration.
Context package build on the solid base provided by the Core package: it provides a way to access
objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The context
package inherits its features from the beans package and adds support for internationalization (I18N)
(using for example resource bundles), event-propagation, resource-loading, and the transparent creation
of contexts.
DAO package provides a JDBC-abstraction layer that removes the need of JDBC coding and parsing of
database-vendor specific error codes. JDBC package provides a way to do programmatic as well as
declarative transaction management, not only for classes implementing special interfaces, but for all your
POJOs (plain old Java objects).
ORM package provides integration layers for popular object-relational mapping APIs, including
JPA,JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R-mappers in
combination with all the other features Spring offers, such as the simple declarative transaction
management feature mentioned previously.
AOP Aspect-oriented programming, or AOP, is a programming technique that allows

programmers to modularize crosscutting concerns, or behavior that cuts across the typical
divisions of responsibility, such as logging and transaction management. The core construct of
AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable
modules.
Web package provides basic web-oriented integration features, such as multipart file-upload functionality,
the initialization of the IoC container using servlet listeners and a web-oriented application context. When
using Spring together with WebWork or Struts, this is the package to integrate with.
MVC package provides a Model-View-Controller (MVC) implementation for web-applications. Spring's
MVC framework is not just any old implementation; it provides a clean separation between domain
model code and web forms, and allows you to use all the other features of the Spring Framework.
6. Benefits of Using Spring Framework
1.
2.
3.
4.
5.
6.
7.
8.

Spring is Lightweight container


No App Server Dependent like EJB JNDI Calls
Objects are created Lazily , Singleton - configuration
Components can added Declaratively
Initialization of properties is easy no need to read from properties file
Declarative transaction, security and logging service - AOP
application code is much easier to unit test
With a Dependency Injection approach, dependencies are explicit, and evident in constructor or
JavaBean properties
9. Spring's configuration management services can be used in any architectural layer, in whatever
runtime environment.

7. What are features of spring?


1. Lightweight:
Spring is lightweight when it comes to size and transparency. The basic version of spring
framework is around 1MB. And the processing overhead is also very negligible.

3
2. Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The objects give
their dependencies instead of creating or looking for dependent objects.
3. Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating
application business logic from system services.
4. Container:
Spring contains and manages the life cycle and configuration of application objects.
5. MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This
framework is highly configurable via strategy interfaces, and accommodates multiple view
technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used
instead of Spring MVC Framework.
6. Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing
the developer to add the pluggable transaction managers, and making it easy to demarcate
transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE
environments and it can be also used in container less environments.
7. JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which
simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring
provides best Integration services with Hibernate, JDO and iBATIS
8. What are the benefits of IOC?

It minimizes the amount of code in your application.


It makes your application easy to test as it doesn't require any singletons or JNDI lookup
mechanisms in your unit test cases.
Loose coupling is promoted with minimal effort and least intrusive mechanism.
IOC containers support eager instantiation and lazy loading of services.

9. What is the Core container module?


This module is provides the fundamental functionality of the spring framework. In this module
BeanFactory is the heart of any spring-based application. The entire framework was built on the
top of this module. This module makes the spring container.

1. Spring Coremodule
2. Spring Beansmodule
3. Spring Contextmodule
4. Spring Expression Languagemodule
10. What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate
the applications configuration and dependencies from the actual application code.

11. What is Application context module?


1. The org.springframework.context.ApplicationContext interface represents the Spring IoC
container and is responsible for instantiating, configuring and assembling the beans.
2. ApplicationContext is a sub interface of BeanFactory. It adds easier integration with Springs
AOP features, message resource handling for use in internationalization, event publication and
application layer specific contexts such as the WebApplicationContext for use in web
applications.
3. In short, the BeanFactory provides the configuration framework and basic functionality and the
ApplicationContext adds more enterprise specific functionality. The ApplicationContext is a
complete superset of the BeanFactory.
12. What is web module?
Spring comes with a full-featured MVC framework for building web applications. Although Spring can
easily be integrated with other MVC frameworks, such as Struts, Springs MVC framework uses IoC to
provide for a clean separation of controller logic from business objects. It also allows you to decoratively
bind request parameters to your business objects. It also can take advantage of any of Springs other
services, such as I18N messaging and validation.
13. What is AOP Alliance?
AOP Alliance is an open-source project whose goal is to promote adoption of AOP and interoperability
among different AOP implementations by defining a common set of interfaces and components.
14. What is Spring configuration file?
Spring configuration file is an XML file. This file contains the classes information and describes how
these classes are configured and introduced to each other.
15. What is XMLBeanFactory?
BeanFactory has many implementations in Spring. But one of the most useful one is
org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions
contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor.
The InputStream will provide the XML to the factory. For example, the following code snippet uses a
java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
BeanFactory factory = new XmlBeanFactory( new FileInputStream('beans.xml'));
16. What are important ApplicationContext implementations in spring framework?

ClassPathXmlApplicationContext, FileSystemXmlApplicationContext,
XmlWebApplicationContext, AnnotationConfigWebApplicationContext
17. What do you mean by Bean wiring?
The act of creating associations between application components (beans) within the Spring container is
reffered to as Bean wiring.

18. Explain Bean lifecycle in spring framework?


1. The spring container finds the beans definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean
definition.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing
the beans ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(),
passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.
19. What is the difference between Bean Factory and Application Context?

ApplicationContext is a sub interface of BeanFactory hence ApplicationContext includes all


functionalities of BeanFactory.
BeanFactory provides only the basic features but ApplicationContext provides advanced features
like internationalization, event publication, etc.
ApplicationContexttakes more memory than BeanFactory.
ApplicationContextinstantiates the beans at the time of application start up but BeanFactory loads
the beans at the time of a getBean() method call.
ApplicationContextsupports more than one configuration files but BeanFactory supports only one
configuration file.

20. What do you mean by Auto Wiring?


The Spring container is able to autowire relationships between collaborating beans. This means that it is
possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the
contents of the BeanFactory. The autowiring functionality has five modes.
no
byName
byType
constructor
autodirect
21. Can there be any custom scope that can be defined and used along with other Springconfigurations
declaratively and programmatically?
Yes. We can create custom scopes that can be used along with other Spring configurations declaratively
and programmatically. For this purpose Spring provides an interface named Scope.
22. How do you turn on annotation wiring?
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotationbased wiring, we will need to enable it in our Spring configuration file by configuring
<context:annotation-config/>.

23. Bean Scopes in Spring?


Spring Framework supports exactly five scopes (of which three are available only if you are using a webaware ApplicationContext).
1. singleton :This scope available for both BeanFactory and ApplicationContext. Scopes a single
bean definition to a single object instance per Spring IoC container. when you define a bean
definition and it is scoped as a singleton, then the Spring IoC container will create exactly one
instance of the object defined by that bean definition. This single instance will be stored in a
cache of such singleton beans, and all subsequent requests and references for that named bean
will result in the cached object being returned. singleton scope is the default scope.
2. Prototype: This scope available for both BeanFactory and ApplicationContext. Scopes a single
bean definition to any number of object instances. Create a new bean instance every time a
request.
3. request :Scopes a single bean definition to the lifecycle of a single HTTP request; that is each
and every HTTP request will have its own instance of a bean created off the back of a single bean
definition. Only valid in the context of a web-aware Spring ApplicationContext like
XmlWebApplicationContext. If you try using these next scopes with regular Spring IoC
containers such as the XmlBeanFactory or ClassPathXmlApplicationContext, you will get an
IllegalStateException complaining about an unknown bean scope.
4. session : Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext like XmlWebApplicationContext.
5. global session : Scopes a single bean definition to the lifecycle of a global HTTP Session.
Typically only valid when used in a portlet context. Only valid in the context of a web-aware
Spring ApplicationContext like XmlWebApplicationContext.
24. What are the limitations with autowiring?
Overriding possibility: You can still specify dependencies using <constructor-arg> and
<property> settings which will always override autowiring.
Primitive data types: You cannot autowire so-called simple properties such as primitives,
Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using
explicit wiring.
25. What is DelegatingVariableResolver?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard
Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable
resolver is called as DelegatingVariableResolver

26. How to integrate your Struts application with spring?


To integrate your Struts application with Spring, we have two options:
Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their
dependencies in a Spring context file.
Subclass Spring's ActionSupport classes

27. What is Java Server Faces (JSF) - Spring integration mechanism?


Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard
JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following
algorithm is performed:
Does a bean with the specified name already exist in some scope (request, session,
application)? If so, return it
Is there a standard JavaServer Faces managed bean definition for this variable name? If so,
invoke it in the usual way, and return the bean that was created.
Is there configuration information for this variable name in the Spring
WebApplicationContext for this application? If so, use it to create and configure an instance,
and return that instance to the caller.
If there is no managed bean or Spring definition for this variable name, return null instead.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization
and destruction methods.
As a result of this algorithm, you can transparently use either JavaServer Faces or Spring
facilities to create beans on demand.
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>

and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.

28. What does @Required annotation mean?


This annotation simply indicates that the affected bean property must be populated at configuration time,
through an explicit property value in a bean definition or through autowiring. The container throws
BeanInitializationException if the affected bean property has not been populated.
29. What does @Autowired annotation mean?
This annotation provides more fine-grained control over where and how autowiring should be
accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like
@Required annotation, constructor, a property or methods with arbitrary names and/or multiple
arguments.
30. What does @Qualifier annotation mean?
There may be a situation when you create more than one bean of the same type and want to wire only one
of them with a property, in such case you can use @Qualifier annotation along with @Autowired to
remove the confusion by specifying which exact bean will be wired.
31. How can we control bean instantiation process? How to customize bean initialization process?

8
We can control the bean instantiation process by three ways:
1. Using @PostConstruct annotation
2. Implementing InitializingBean interface with afterPropertiesSet() method
3. Configuring init-method attribute for the bean in the xml configuration file
32. How can we control bean destruction process? How to customize bean destruction process?
We can control the bean destruction process by three ways:
1. Using @PreDestroy annotation
2. Implementing DisposableBean interface with destroy() method
3. Configuring destroy-method attribute for the bean in the xml configuration file
33. What are the JSR-250 Annotations? Explain them.
Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource
annotations.
1. @PostConstruct: This annotation can be used as an alternate of initialization callback.
2. @PreDestroy: This annotation can be used as an alternate of destruction callback.
3. @Resource : This annotation can be used on fields or setter methods. The @Resource annotation
takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it
follows by-name autowiring semantics.
34. What is Spring Java Based Configuration? Give some annotation example.
Java based configuration option enables you to write most of your Spring configuration without XML but
with the help of few Java-based annotations.
For example: Annotation @Configuration indicates that the class can be used by the Spring IoC
container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated
with @Bean will return an object that should be registered as a bean in the Spring application context.
35. How is event handling done in Spring?
Event handling in the ApplicationContext is provided through the ApplicationEvent class and
ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an
ApplicationEvent gets published to the ApplicationContext, that bean is notified.
36. Describe some of the standard Spring events.
Spring provides the following standard events:
1. ContextRefreshedEvent: This event is published when the ApplicationContext is either
initialized or refreshed. This can also be raised using the refresh() method on the
ConfigurableApplicationContext interface.
2. ContextStartedEvent: This event is published when the ApplicationContext is started using the
start() method on the ConfigurableApplicationContext interface. You can poll your database or
you can re/start any stopped application after receiving this event.
3. ContextStoppedEvent: This event is published when the ApplicationContext is stopped using
the stop() method on the ConfigurableApplicationContext interface. You can do required
housekeep work after receiving this event.

9
ContextClosedEvent: This event is published when the ApplicationContext is closed using the
close() method on the ConfigurableApplicationContext interface. A closed context reaches its end
of life; it cannot be refreshed or restarted.
5. RequestHandledEvent: This is a web-specific event telling all beans that an HTTP request has
been serviced.
4.

37. What is Aspect?


A module which has a set of APIs providing cross-cutting requirements. For example, a logging module
would be called AOP aspect for logging. An application can have any number of aspects depending on the
requirement. In Spring AOP, aspects are implemented using regular classes (the schema-based approach)
or regular classes annotated with the @Aspect annotation (@AspectJ style).
38. What is the difference between concern and cross-cutting concern in Spring AOP?
Concern: Concern is behavior which we want to have in a module of an application. Concern may be
defined as a functionality we want to implement. Issues in which we are interested define our concerns.
Cross-cutting concern: It's a concern which is applicable throughout the application and it affects the
entire application. e.g. logging , security and data transfer are the concerns which are needed in almost
every module of an application, hence are cross-cutting concerns.
39. What is Join point?
This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the
actual place in the application where an action will be taken using Spring AOP framework.
40. What is Advice?
This is the actual action to be taken either before or after the method execution. This is actual piece of
code that is invoked during program execution by Spring AOP framework.
41. What is Pointcut?
This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts
using expressions or patterns as we will see in our AOP examples.
42. What is Introduction?
An introduction allows you to add new methods or attributes to existing classes.
43. What is Target object?
The object being advised by one or more aspects, this object will always be a proxy object. Also referred
to as the advised object.
44. What is Weaving?
Weaving is the process of linking aspects with other application types or objects to create an advised
object.
45. What are the different points where weaving can be applied?

10
Weaving can be done at compile time, load time, or at runtime.
46. What are the types of advice?
Spring aspects can work with five kinds of advice mentioned below:
1. before: Run advice before the a method execution.
2. after: Run advice after the a method execution regardless of its outcome.
3. after-returning: Run advice after the a method execution only if method completes successfully.
4. after-throwing: Run advice after the a method execution only if method exits by throwing an
exception.
5. around: Run advice before and after the advised method is invoked.
47. What are the different points in the target objects life time where Weaving can be applied?
Weaving can take place at several points in the target objects lifetime:

Compile time: Aspects are woven when the target class is compiled. This requires a special compiler.
AspectJs weaving compiler weaves aspects this way.
Classload time: Aspects are woven when the target class is loaded into the JVM. This requires a
special ClassLoader that enhances that target classs byte code before the class is introduced into the
application. AspectJ 5s load time weaving (LTW) support weaves aspects in this way.
Runtime: Aspects are woven sometime during the execution of the application. Typically, an AOP
container will dynamically generate a proxy object that will delegate to the target object while
weaving in the aspects. Spring AOP uses this approach.

48. What is XML Schema based aspect implementation?


Aspects are implemented using regular classes along with XML based configuration.
49. What is @AspectJ? based aspect implementation?
@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.
50. How JDBC can be used more efficiently in spring framework?
JDBC can be used more efficiently with the help of a template class provided by spring framework called
as JdbcTemplate.
51. How JdbcTemplate can be used?
With use of Spring JDBC framework the burden of resource management and error handling is reduced a
lot. So it leaves developers to write the statements and queries to get the data to and from the database.
JdbcTemplate provides many convenience methods for doing things such as converting database data into
primitives or objects, executing prepared and callable statements, and providing custom database error
handling.
52. What are the types of the transaction management Spring supports?
Spring supports two types of transaction management:
Programmatic transaction management: This means that you have managed the transaction
with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.

11

Declarative transaction management: This means you separate transaction management from
the business code. You only use annotations or XML based configuration to manage the
transactions.

53. Which of the above transaction management type is preferable?


Declarative transaction management is preferable over programmatic transaction management though it
is less flexible than programmatic transaction management, which allows you to control transactions
through your code.
54. What is Spring MVC framework?
The Spring web MVC framework provides model-view-controller architecture and ready components
that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in
separating the different aspects of the application (input logic, business logic, and UI logic), while
providing a loose coupling between these elements.
55. What is a DispatcherServlet?
The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP
requests and responses.

56. What is WebApplicationContext ?


The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features
necessary for web applications. It differs from a normal ApplicationContext in that it is capable of
resolving themes, and that it knows which servlet it is associated with.
57. What are the advantages of Spring MVC over Struts MVC ?
Following are some of the advantages of Spring MVC over Struts MVC:
Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and
Form object into concrete inheritance.
Spring provides both interceptors and controllers, thus helps to factor out common behavior to the
handling of many requests.
Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity,
XLST etc. and also you can create your own custom view mechanism by implementing Spring
View interface.
In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and
integration easy.
Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced
concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
Struts force your Controllers to extend a Struts class but Spring doesn't, there are many
convenience Controller implementations that you can choose to extend.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or
globally. SpringMVC has HandlerMapping interface to support this functionality.

12

With Struts, validation is usually performed (implemented) in the validate method of an


ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the
Servlet API which makes these validators to be reused in your business logic before persisting a
domain object to a database.

58. What is Controller in Spring MVC framework?


Controllers provide access to the application behavior that you typically define through a service
interface. Controllers interpret user input and transform it into a model that is represented to the user by
the view. Spring implements a controller in a very abstract way, which enables you to create a wide
variety of controllers.
59. Explain the @Controller annotation.
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does
not require you to extend any controller base class or reference the Servlet API.
60. Explain @RequestMapping annotation.
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler
method.
61. What are ORM's Spring supports ?
Hibernate, iBatis, JPA (Java Persistence API), TopLink, JDO (Java Data Objects), OJB
62. What are the ways to access Hibernate by using Spring?
There are three ways to access Hibernate using Spring:
1.
Extending the HibernateDaoSupport abstract class
2.
Directly injecting the Hibernate SessionFactory into the DAO layer
3.
Directly injecting the HibernateTemplate into the DAO layer
63. How to wire up a transaction manager?
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
64. How to configure Spring and hibernate?
<bean id="employeeDao" class="com.roy4j.hibernate.domain.Employee">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

13
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value=" jdbc:mysql://localhost/hibernate" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
65. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Springs SessionFactory called LocalSessionFactory. The
integration process is of 3 steps.
Configure the Hibernate SessionFactory
Extend your DAO Implementation from HibernateDaoSupport
Wire in Transaction Support with AOP
66. What are the types of the transaction management Spring supports ?
Spring Framework supports:
Programmatic transaction management.
Declarative transaction management.
67. What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that delivers the
following benefits:
Provides a consistent programming model across different transaction APIs such as JTA,
JDBC, Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of
complex transaction APIs such as JTA.
68. Why most users of the Spring Framework choose declarative transaction management ?
Most users of the Spring Framework choose declarative transaction management
because it is very simple and easy to use. We can wire up a transaction manager in
the Spring configuration file and annotate a class, interface or a public method with
@Transactional and the things are done. The best practice to use @Transactional
annotation for concrete classes only.
69. When to use programmatic and declarative transaction management ?
Programmatic transaction management is usually a good idea only if you have a small number of
transactional operations.

14
On the other hand, if your application has numerous transactional operations, declarative transaction
management is usually worthwhile. It keeps transaction management out of business logic, and is not
difficult to configure.
70. Explain the similarities and differences between EJB CMT and the Spring Framework's
declarative transaction management ?
The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to
individual method level. It is possible to make a setRollbackOnly() call within a transaction context if
necessary. The differences are:
Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction
management works in any environment. It can work with JDBC, JDO, Hibernate or other
transactions under the covers, with configuration changes only.
The Spring Framework enables declarative transaction management to be applied to any class,
not merely special classes such as EJBs.
The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent.
Both programmatic and declarative support for rollback rules is provided.
The Spring Framework gives you an opportunity to customize transactional behavior, using AOP.
With EJB CMT, you have no way to influence the container's transaction management other than
setRollbackOnly().
The Spring Framework does not support propagation of transaction contexts across remote calls,
as do high-end application servers.
71. Explain about the Spring DAO support ?
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access
technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the
persistence technologies fairly easily and it also allows one to code without worrying about catching
exceptions that are specific to each technology.
72. What are the exceptions thrown by the Spring DAO classes ?
Spring
DAO
classes
throw
exceptions
which
are
subclasses
of
DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient
translation from technology-specific exceptions like SQLException to its own exception class hierarchy
with the DataAccessException as the root exception. These exceptions wrap the original exception.
73. What is SQLExceptionTranslator ?
SQLExceptionTranslator is a strategy interface for translating SQLExceptions into Springs
DataAccessException hierarchy. Implementations can be generic (for example, using SQLState codes for
JDBC) or wholly proprietary (for example, using Oracle error codes) for greater precision.
74. What is Spring's JdbcTemplate ?
The JdbcTemplate class is the central class in the JDBC core package. It handles the creation and release
of resources, which helps you avoid common errors such as forgetting to close the connection. It performs
the basic tasks of the core JDBC workflow such as statement creation and execution, leaving application
code to provide SQL and extract results. The JdbcTemplate class executes SQL queries, update statements

15
and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter
values. It also catches JDBC exceptions and translates them to the generic, more informative, exception
hierarchy defined in the org.springframework.dao package.
JdbcTemplate template = new JdbcTemplate(myDataSource);
75. How JdbcTemplate can be used? How do you write data to backend in Spring using JdbcTemplate?
<!-- EmployeeDAO -->
<bean id="employeeDAO" class="jdbc.EmployeeDAO">
<property name="template" ref="jdbcTemplate"></property>
</bean>
<!-- JDBCTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="mySQLDS"></property>
</bean>
<!-- DriverManagerDataSource -->
<bean id="mySQLDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
76. What is SQLProvider?
SqlProvider is an interface that needs to be implemented by objects that can provide SQL strings.
Typically
implemented
by
PreparedStatementCreators,
CallableStatementCreators
and
StatementCallbacks that want to expose the SQL they use to create their statements, to allow for better
contextual information in case of exceptions.
77. What is PreparedStatementCreator?
The PreparedStatementCreator callback interface creates a prepared statement given a Connection
provided by this class, providing SQL and any necessary parameters. PreparedStatementCreator is one of
the two central callback interfaces used by the JdbcTemplate class. This interface creates a
PreparedStatement given a connection provided by the JdbcTemplate class. Implementations are
responsible for providing SQL and any necessary parameters. Implementations do not need to concern
themselves with SQLExceptions that may be thrown from operations they attempt. The JdbcTemplate
class will catch and handle SQLExceptions appropriately. A PreparedStatementCreator should also
implement the SqlProvider interface if it is able to provide the SQL it uses for PreparedStatement
creation. This allows for better contextual information in case of exceptions.

16

78. Explain about BatchPreparedStatementSetter?


BatchPreparedStatementSetter is a batch update callback interface used by the JdbcTemplate class. This
interface sets values of a PreparedStatement provided by the JdbcTemplate class, for each of a number of
updates in a batch using the same SQL. Implementations are responsible for setting any necessary
parameters. SQL with placeholders will already have been supplied. Implementations do not need to
concern themselves with SQLExceptions that may be thrown from operations they attempt. The
JdbcTemplate class will catch and handle SQLExceptions appropriately.
79. What is RowCallbackHandler and why it is used?
The RowCallbackHandler interface extracts values from each row of a ResultSet. It is used by
JdbcTemplate. Implementations of this interface perform the actual work of processing each row but do
not need to worry about exception handling. SQLExceptions will be caught and handled by the calling
JdbcTemplate. It is suggested to use a RowMapper instead if we need to map exactly one result object per
row and assembling them into a List.
80. What are the various Special beans used by the WebApplicationContext?
1. handler mapping(s): a list of pre and post processors and controllers that will be executed if they
match certain criteria
2. controller(s): the beans providing the actual functionality or at least access to the functionalityas
part of the MVC triad
3. view resolver: capable of resolving view names to view definitions
4. multipart resolver: offers functionality to process multipart file uploads from HTML forms
5. handler exception resolver: offers functionality to map exceptions to views or implement other
more complex exception handling code
81. How does Spring relate to MVC framework?
Spring provides its own implementation of the MVC architecture. The DispatcherServlet plays the role of
Front Controller and delegates the request to Application Controller. Application Controllerinterprets user
input and transforms it into a Model that is represented to the user by the View. If a Model is returned by
the request handler then the View is rendered and if no Model is returned then no View is rendered.
82. What are the differences between EJB and Spring ?
Spring and EJB feature comparison.
Feature

EJB

Spring

Transaction
management

Supports
multiple
transaction
environments
through
its
Must use a JTA transaction
PlatformTransactionManager interface, including
manager.
JTA, Hibernate, JDO, and JDBC.
Supports transactions that
Does not natively support distributed
span remote method calls.
transactionsit must be used with a JTA
transaction manager.

17

Declarative
transaction
support

Can
define
transactions
Can define transactions declaratively
declaratively through the deployment
through the Spring configuration file or through
descriptor.
class metadata.
Can
define
transaction
Can define which methods to apply
behavior per method or per class by
transaction behavior explicitly or by using regular
using the wildcard character *.
expressions.
Cannot declaratively define
Can declaratively define rollback
rollback behaviorthis must be done
behavior per method and per exception type.
programmatically.

Persistence

Supports
programmatic
bean- Provides a framework for integrating with several
managed persistence and declarative persistence technologies, including JDBC,
container managed persistence.
Hibernate, JDO, and iBATIS.

Declarative
security

Supports declarative security


No security implementation out-of-the
through users and roles. The
box.
management and implementation of
Acegi, an open source security
users and roles is container specific.
framework built on top of Spring, provides
Declarative
security
is
declarative security through the Spring
configured in the deployment
configuration file or class metadata.
descriptor.

Distributed
computing

Provides container-managed remote Provides proxying for remote calls via RMI, JAXmethod calls.
RPC, and web services.

83. what are those view resolvers?


Yes. There is an interface in Spring Core named as Ordered. Any ViewResolver that has implemented the
Ordered interface supports ViewResolver chaining. For example:
BeanNameViewResolver
ResourceBundleViewResolver
XmlViewResolver
o UrlBasedViewResolver
o JasperReportsViewResolver
o TilesViewResolver
o XsltViewResolver
84. What are the ways for view resolution in Spring Web MVC?
View name resolution is highly configurable through:
file extension or Accept header content type negotiation
through bean names
using properties file
available ViewResolvers or a custom ViewResolver implementation
85. Where do we need to instantiate the container? Is there a specific class?

18

ContextLoaderListener is a bootstrap listener to start up and shut down Springs root


WebApplicationContext.
In a web application: web.xml ContextLoaderListener.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>\
</listener>
In a standalone application: ClasspathXmlApplicationContext / FileSystemXmlApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml",
"daos.xml"});
86. How input data validation is handled in Spring Web MVC framework?
Since Spring 3, the MVC framework has the ability to automatically validate @Controller inputs. To
trigger validation of a @Controller input we simply annotate the input argument as @Valid. Spring MVC
will validate a @Valid object after binding so-long as an appropriate Validator has been configured. A
Validator can be configured in two ways.
By calling binder.setValidator(Validator) within a @Controllers @InitBinder callback. This configuration
of a Validator instance is per @Controller class basis.
@Controller
public class EmployeeController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new EmployeeValidator());
}
@RequestMapping(value = "/employee", method=RequestMethod.POST)
public void processFoo(@Valid Employee employee) {
// TODO
}
}
By calling setValidator(Validator) on the global WebBindingInitializer. This configuration of a Validator
instance is across all @Controllers. This can be configured in the spring configuration file:
<mvc:annotation-driven validator="globalValidator"/>
To combine a global and a local validator we need to configure the global validator as shown above and
then add a local validator:
@Controller
public class EmployeeController {
@InitBinder

19
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new EmployeeValidator());
}
}
87. Can any object be used as command while using Spring Web MVC Framework?
In Spring Web MVC you can use any object as a command or form-backing object; you do not need to
implement a framework-specific interface or base class. Springs data binding is highly flexible: for
example, it treats type mismatches as validation errors that can be evaluated by the application, not as
system errors. Thus you need not duplicate your business objects properties as simple, untyped strings in
your form objects simply to handle invalid submissions, or to convert the Strings properly. Instead, it is
often preferable to bind directly to your business objects.
88. What is ModelAndView?
ModelAndView is a holder for both Model and View in the web MVC framework. Model and View are
entirely distinct. This class merely holds both to make it possible for a controller to return both Model and
View in a single return value. It represents a Model and View returned by a handler, to be resolved by a
DispatcherServlet. The View can take the form of a String view name which will need to be resolved by a
ViewResolver object; alternatively a View object can be specified directly. The model is a Map, allowing
the use of multiple objects keyed by name.
89. What is Spring Security?
Spring Security module provides authentication, authorization and other security features for enterprise
applications.
90. Difference between FileSystemResource and ClassPathResource?

FileSystemResource will look into the file system and ClassPathResource will look into the class
path for the Spring configuration file.
FileSystemResource uses path relative to the project but ClassPathResource uses path relative to
the class path. For example:

FileSystemResource resource = new FileSystemResource("src/com/beans.xml");


ClassPathResource resource = new ClassPathResource("com/beans.xml");

91. How can we control concurrent active session using Spring Security?
We need to add HttpSessionEventPublisher in web.xml file:
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
We need to add the following lines in application context:

20
<http>
...
<session-management>
<concurrency-control max-sessions="1" />
</session-management>
</http>

92. How can you setup MessageSources in Spring?


We
can
setup
MessageSources
by
using
ResourceBundleMessageSource
ReloadableResourceBundleMessageSource.
Bean Configuration:
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>com/messages/messages</value>
</list>
</property>
</bean>

or

93. How to read properties file in spring?


database.properties
db.host=localhost
db.port=1521
db.uname=test
db.pword=test
beans.xml
<context:property-placeholder location="classpath:database.properties" />
<bean id="dbProperties" class="com.roy4j.DBProperties">
<property name="host" value="${db.host}" />
<property name="port" value="${db.port}" />
<property name="uname" value="${db.uname}" />
<property name="pword" value="${db.pword}" />
</bean>
94. How to go about reading environment specific property files?
We can use PropertyPlaceholderConfigurer or PropertySourcesPlaceholderConfigurer which will enable
other beans to access properties from environment specific properties file via ${. . .} notation.
<bean id="hello"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>

21
<value>file:E:\MyRnD\java\hello.properties</value>
</list>
</property>
</bean>
95. How to go about reading environment specific property files?
We can use PropertyPlaceholderConfigurer or PropertySourcesPlaceholderConfigurer which will enable
other beans to access properties from environment specific properties file via ${. . .} notation.
<bean id="hello"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:E:\MyRnD\java\hello.properties</value>
</list>
</property>
</bean>
Alternatively we can use the smaller syntax with <property-placeholder> element:
<context:property-placeholder location="file:E:\MyRnD\java\b.properties" />
96. How to inject a java.util.Properties into abean?
We can inject a java.util.Properties into a bean using PropertiesFactoryBean.
MyBean.java
package com;
import java.util.Properties;
public class MyBean {
private Properties map;
public Properties getMap() {
return map;
}
public void setMap(Properties map) {
this.map = map;
}
}
beans.xml
<bean id="myBean" class="com.MyBean">
<property name="map" ref="hello" />
</bean>
<bean id="hello"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:com/a.properties</value>
</list>
</property>

22
</bean>
97. How can you create a DataSource connection pool?
<bean
id="springDataSource"
class="org.apache.commons.dbcp.BasicDataSource"
method="close" >
<property name="url" value="jdbc:oracle:thin:@localhost:1521:test" />
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="removeAbandoned" value="true"/>
<property name="initialSize" value="20" />
<property name="maxActive" value="30" />
</bean>
98. Which Design Patterns are used in Spring?
The list of Design Patterns is used in Spring is huge:
1. Creational patterns:
a. Singleton Pattern: Default bean scope
b. Factory Method Pattern: BeanFactory
c. Prototype Pattern: Bean scope
2. Structural patterns:
a. Adapter Pattern: Spring Web, Spring AOP
b. Proxy Pattern: Spring AOP
3. Behavioral patterns:
a. Command Pattern: Spring MVC
b. Observer Pattern: Events
c. Strategy Pattern: SQLExceptionTranslator
d. Template Method Pattern: JdbcTemplate, HibernateTemplate
4. Presentation Tier Design Patterns:
a. Front Controller
b. Application Controller
c. Page Controller
d. Context Object
e. Intercepting Filter
f. View Helper
g. Composite View
h. Dispatcher View
i. Service to Worker
5. Business Tier Design Patterns:
a. Service Locator
b. Business Delegate
c. Session Facade
d. Application Service
e. Business Interface

destroy-

23
6. Integration Tier Design Patterns:
a. Data Access Object
b. Procedure Access Object
c. Service Activator
d. Web Service Broker
7. Crosscutting Design Patterns:
a. Authentication and Authorization Enforcer
b. Audit Interceptor
c. Domain Service Owner Transaction

You might also like