[go: up one dir, main page]

0% found this document useful (0 votes)
112 views63 pages

005 Spring63

Uploaded by

JP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views63 pages

005 Spring63

Uploaded by

JP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Spring

Spring Interview Questions


To easily develop an enterprise application in java, we need to go for spring framework. There are given a list of frequently asked
spring interview questions.
1) What is Spring?
It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java.
2) What are the advantages of spring framework?
1. Predefined Templates
2. Loose Coupling
3. Easy to test
4. Lightweight
5. Fast Development
6. Powerful Abstraction
7. Declarative support
3) What are the modules of spring framework?
1. Test
2. Spring Core Container
3. AOP, Aspects and Instrumentation
4. Data Access/Integration
5. Web
4) What is IOC and DI?
IOC (Inversion of Control) and DI (Dependency Injection) is a design pattern to provide loose coupling. It removes the dependency
from the program.
Let's write a code without following IOC and DI.
1. public class Employee{  
2. Address address;  
3. Employee(){  
4. address=new Address();//creating instance  
5. }  
6. }  
Now, there is dependency between Employee and Address because Employee is forced to use the same address instance.
Let's write the IOC or DI code.
1. public class Employee{  
2. Address address;  
3. Employee(Address address){  
4. this.address=address;//not creating instance  
5. }  
6. }  
Now, there is no dependency between Employee and Address because Employee is not forced to use the same address instance. It
can use any address instance.
5) What is the role of IOC container in spring?
IOC container is responsible to:
 create the instance
 configure the instance, and
 assemble the dependencies
6) What are the types of IOC container in spring?
There are two types of IOC containers in spring framework.
1. BeanFactory
2. ApplicationContext

7) What is the difference between BeanFactory and ApplicationContext?


BeanFactory is the basic container whereas ApplicationContext is the advanced container. ApplicationContext extends the
BeanFactory interface. ApplicationContext provides more facilities than BeanFactory such as integration with spring AOP, message
resource handling for i18n etc.
8) What is the difference between constructor injection and setter injection?
No. Constructor Injection Setter Injection

1) No Partial Injection Partial Injection

2) Desn't override the setter property Overrides the constructor property if both are defined.

3) Creates new instance if any modification Doesn't create new instance if you change the property
occurs value
4) Better for too many properties Better for few properties.
9) What is autowiring in spring? What are the autowiring modes?
Autowiring enables the programmer to inject the bean automatically. We don't need to write explicit injection logic.
Let's see the code to inject bean using dependency injection.
1. <bean id="emp" class="com.javatpoint.Employee" autowire="byName" />  
The autowiring modes are given below:
No. Mode Description

1) No this is the default mode, it means autowiring is not enabled.

2) byname injects the bean based on the property name. It uses setter method.

3) byType injects the bean based on the property type. It uses setter method.

4) Constructor It injects the bean using constructor

The "autodetect" mode is deprecated since spring 3.


10) What are the different bean scopes in spring?
There are 5 bean scopes in spring framework.
No. Scope Description

1) singleton The bean instance will be only once and same instance will be returned by the IOC container.
It is the default scope.

2) prototype The bean instance will be created each time when requested.

3) request The bean instance will be created per HTTP request.

4) session The bean instance will be created per HTTP session.

5) globalsession The bean instance will be created per HTTP global session. It can be used in portlet context
only.
11) In which scenario, you will use singleton and prototype scope?
Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.
12) What are the transaction management supports provided by spring?
Spring framework provides two type of transaction management supports:
1. Programmatic Transaction Management: should be used for few transaction operations.
2. Declarative Transaction Management: should be used for many transaction operations.
13) What are the advantages of JdbcTemplate in spring?
Less code: By using the JdbcTemplate class, you don't need to create connection,statement,start transaction,commit transaction
and close connection to execute different queries. You can execute the query directly.
14) What are classes for spring JDBC API?
1. JdbcTemplate
2. SimpleJdbcTemplate
3. NamedParameterJdbcTemplate
4. SimpleJdbcInsert
5. SimpleJdbcCall
15) How can you fetch records by spring JdbcTemplate?
You can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:
1. ResultSetExtractor
2. RowMapper
16) What is the advantage of NamedParameterJdbcTemplate?
NamedParameterJdbcTemplate class is used to pass value to the named parameter. A named parameter is better than ? (question
mark of PreparedStatement).
It is better to remember.
17) What is the front controller class of Spring MVC?
The DispatcherServlet class works as the front controller in Spring MVC.
18) What is AOP?
AOP is an acronym for Aspect Oriented Programming. It is a methodology that divides the program logic into pieces or parts or
concerns.
It increases the modularity and the key unit is Aspect.
19) What are the advantages of spring AOP?
AOP enables you to dynamically add or remove concern before or after the business logic. It is pluggableand easy to maintain.
20) What are the AOP terminology?
AOP terminologies or concepts are as follows:
 JoinPoint
 Advice
 Pointcut
 Aspect
 Introduction
 Target Object
 Interceptor
 AOP Proxy
 Weaving
1) What is spring framework? Why Java programmer should use Spring framework
Very common Spring interview question, Spring is a framework which helps Java programmer in development. Spring provides
dependency Injection and IOC container, Spring MVC flow and several useful API for Java programmer.

2) What is default scope of bean in Spring framework ?


default scope of bean is Singleton, you can read this article which explains about all possible scope of a spring bean : What is bean
scope in Spring

3) Does Spring singleton beans are thread-safe ?


No, Spring singleton beans are not thread-safe. Singleton doesn't mean bean would be thread-safe.

4) What is dependency Injection?


Dependency Injection is one of the design pattern, which allows to inject dependency on Object, instead of object resolving
dependency.

5) What is Inversion of Control concept, how does Spring support IOC?


6) What is Spring MVC ? Can you explain How one request is processed ?
7) How to you create controller in Spring ?

8) What is view Resolver pattern ? how it work in Spring MVC


View Resolver patter is a J2EE pattern which allows a web application to dynamically choose it's view technology e.g. HTML, JSP,
Tapestry, JSF, XSLT or any other view technology. In this pattern, View resolver holds mapping of different views, controller return
name of view, which is than passed to View Resolver for selecting appropriate view. Spring MVC framework supplies inbuilt view
resolver for selecting views.
9) What is Spring Security ?
Spring security is a project under spring framework umbrella, which provides support for security requirements of enterprise Java
projects. Spring Security formerly known as aegis security provides out of box support for creating login screen, remember me
cookie support, securing URL, authentication provider to authenticate user from database, LDAP and in memory, concurrent active
session management support and many more. In order to use Spring security in a Spring MVC based project, you need to include
spring-security.jar and configure it in application-Context-security.xml file, you can name it whatever you want, but make sure to
supply this to ContextLoaderListener, which is responsible for creating Spring context and initializing dispatcher servlet.
Q: What is Spring?
A: Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in
developing any Java application, but there are extensions for building web applications on 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.
Q: what are benefits of using spring?
A: Following is the list of few of the great benefits of using Spring Framework:
 Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
 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.
 Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application
business logic from system services.
 Container: Spring contains and manages the life cycle and configuration of application objects.
 MVC Framework: Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web
frameworks such as Struts or other over engineered or less popular web frameworks.
 Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction
(using a single database, for example) and scale up to global transactions (using JTA, for example).
 Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or
JDO, for example) into consistent, unchecked exceptions.
Q: What are the different modules in Spring framework?
A: Following are the modules of the Spring framework:
 Core module
 Bean module
 Context module
 Expression Language module
 JDBC module
 ORM module
 OXM module
 Java Messaging Service(JMS) module
 Transaction module
 Web module
 Web-Servlet module
 Web-Struts module
 Web-Portlet module
Q: What is Spring configuration file?
A: 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.
Q: What is Dependency Injection?
A: Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely
one concrete example of Inversion of Control.
This concept says 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 (the IOC container) is then responsible for hooking it all up.
Q: What are the different types of IoC (dependency injection)?
A: Types of IoC are:
 Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with
a number of arguments, each representing a dependency on other class.
 Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after
invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Q: Which DI would you suggest Constructor-based or setter-based DI?
A: Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory
dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make
setters required dependencies.
Q: What are the benefits of IOC?
A: The main benefits of IOC or dependency injection are:
 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.
Q: What is AOP?
A: 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.
Q: What is Spring IoC container?
A: The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till
destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.
Q: What are types of IoC containers? Explain them.
A: There are two types of IoC containers:
 Bean Factory container: This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the
resources are limited like mobile devices or applet based applications
 Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual
messages from a properties file and the ability to publish application events to interested event listeners.
Q: Give an example of BeanFactory implementation.
A: The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration
metadata from an XML file and uses it to create a fully configured system or application.
Q: What are the common implementations of the ApplicationContext?
A: The three commonly used implementation of 'Application Context' are:
 FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the
full path of the XML bean configuration file to the constructor.
 ClassPathXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you do not need to
provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration
XML file in CLASSPATH.
 WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.
Q: What is the difference between Bean Factory and ApplicationContext?
A: Following are some of the differences:
 Application contexts provide a means for resolving text messages, including support for i18n of those messages.
 Application contexts provide a generic way to load file resources, such as images.
 Application contexts can publish events to beans that are registered as listeners.
 Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean
factory, can be handled declaratively in an application context.
 The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation
being pluggable.
Q: What are Spring beans?
A: The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A
bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with
the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions.
Q: What does a bean definition contain?
A: The bean definition contains the information called configuration metadata which is needed for the container to know the
followings:
 How to create a bean
 Bean's lifecycle details
 Bean's dependencies
Q: How do you provide configuration metadata to the Spring Container?
A: There are following three important methods to provide configuration metadata to the Spring Container:
 XML based configuration file.
 Annotation-based configuration
 Java-based configuration
Q: How do add a bean in spring application?
A: Check the following example:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="helloWorld" class="com.tutorialspoint.HelloWorld">


<property name="message" value="Hello World!"/>
</bean>

</beans>
Q: How do you define a bean scope?
A: When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce
a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you
want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to
be singleton.
Q: What bean scopes does Spring support? Explain them.
A: The Spring Framework supports following five scopes, three of which are available only if you use a web-aware
ApplicationContext.
 singleton: This scopes the bean definition to a single instance per Spring IoC container.
 prototype: This scopes a single bean definition to have any number of object instances.
 request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
 session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
 global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring
ApplicationContext.
Q: What is default scope of bean in Spring framework?
A: The default scope of bean is Singleton for Spring framework.
Q: Are Singleton beans thread safe in Spring Framework?
A: No, singleton beans are not thread-safe in Spring framework.
Q: Explain Bean lifecycle in Spring framework?
A: Following is sequence of a bean lifecycle in Spring:
 Instantiate - First the spring container finds the bean's definition from the XML file and instantiates the bean..
 Populate properties - Using the dependency injection, spring populates all of the properties as specified in the bean definition..
 Set Bean Name - If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
 Set Bean factory - If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
 Pre Initialization - Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls
postProcesserBeforeInitialization() method.
 Initialize beans - If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method
declaration, the specified initialization method is called.
 Post Initialization - If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will
be called.
 Ready to use - Now the bean is ready to use by the application.
 Destroy - If the bean implements DisposableBean , it will call the destroy() method .
Q: What are inner beans in Spring?
A: A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean
definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are
always anonymous and they are always scoped as prototypes.
Q: How can you inject Java Collection in Spring?
A: Spring offers four types of collection configuration elements which are as follows:
 <list>: This helps in wiring i.e. injecting a list of values, allowing duplicates.
 <set>: This helps in wiring a set of values but without any duplicates.
 <map>: This can be used to inject a collection of name-value pairs where name and value can be of any type.
 <props>: This can be used to inject a collection of name-value pairs where the name and value are both Strings.
Q: What is bean auto wiring?
A: 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 without using
<constructor-arg> and <property> elements.
Q: What are different Modes of auto wiring?
A: The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency
injection:
 no: This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do
special for this wiring. This is what you already have seen in Dependency Injection chapter.
 byName: Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to
byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the
configuration file.
 byType: Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to
byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans
name in configuration file. If more than one such beans exist, a fatal exception is thrown.
 constructor: Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor
argument type in the container, a fatal error is raised.
 autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Q: What are the limitations with autowiring?
A: Limitations of autowiring are:
 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.
Q: Can you inject null and empty string values in Spring?
A: Yes.
Q: What is Annotation-based container configuration?
A: An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up
components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the
configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Q: How do you turn on annotation wiring?
A: Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will
need to enable it in our Spring configuration file by configuring <context:annotation-config/>.
Q: What does @Required annotation mean?
A: 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.
Q: What does @Autowired annotation mean?
A: 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.
Q: What does @Qualifier annotation mean?
A: 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.
Q: What are the JSR-250 Annotations? Explain them.
A: Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.
 @PostConstruct: This annotation can be used as an alternate of initialization callback.
 @PreDestroy: This annotation can be used as an alternate of destruction callback.
 @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.
Q: What is Spring Java Based Configuration? Give some annotation example.
A: 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.
Q: How is event handling done in Spring?
A: Event handling in the ApplicationContext is provided through the ApplicationEvent class andApplicationListener interface. So if a
bean implements the ApplicationListener, then every time anApplicationEvent gets published to the ApplicationContext, that bean is
notified.
Q: Describe some of the standard Spring events.
A: Spring provides the following standard events:
 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.
 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 sped application after receiving this
event.
 ContextSpedEvent: This event is published when the ApplicationContext is sped using the s() method on the
ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event.
 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.
 RequestHandledEvent: This is a web-specific event telling all beans that an HTTP request has been serviced.
Q: What is Aspect?
A: 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).
Q: What is the difference between concern and cross-cutting concern in Spring AOP?
A: 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.
Q: What is Join point?
A: 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.
Q: What is Advice?
A: 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.
Q: What is Pointcut?
A: 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.
Q: What is Introduction?
A: An introduction allows you to add new methods or attributes to existing classes.
Q: What is Target object?
A: The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object.
Q: What is Weaving?
A: Weaving is the process of linking aspects with other application types or objects to create an advised object.
Q: What are the different points where weaving can be applied?
A: Weaving can be done at compile time, load time, or at runtime.
Q: What are the types of advice?
A: Spring aspects can work with five kinds of advice mentioned below:
 before: Run advice before the a method execution.
 after: Run advice after the a method execution regardless of its outcome.
 after-returning: Run advice after the a method execution only if method completes successfully.
 after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
 around: Run advice before and after the advised method is invoked.
Q: What is XML Schema based aspect implementation?
A: Aspects are implemented using regular classes along with XML based configuration.
Q: What is @AspectJ? based aspect implementation?
A: @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.
Q: How JDBC can be used more efficiently in spring framework?
A: JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.
Q: How JdbcTemplate can be used?
A: 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.
Q: What are the types of the transaction management Spring supports?
A: 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.
 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.
Q: Which of the above transaction management type is preferable?
A: 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.
Q: What is Spring MVC framework?
A: 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.
Q: What is a DispatcherServlet?
A: The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.
Q: What is WebApplicationContext ?
A: 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.
Q: What are the advantages of Spring MVC over Struts MVC ?
A: 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.
 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.
Q: What is Controller in Spring MVC framework?
A: 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.
Q: Explain the @Controller annotation.
A: 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.
Q: Explain @RequestMapping annotation.
A: @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
Q: What are the ways to access Hibernate by using Spring?
A: There are two ways to access hibernate using spring:
 Inversion of Control with a Hibernate Template and Callback.
 Extending HibernateDAOSupport and Applying an AOP Interceptor node.
Q: What are ORM's Spring supports ?
A: Spring supports the following ORM's :
 Hibernate
 iBatis
 JPA (Java Persistence API)
 Link
 JDO (Java Data Objects)
 OJB

Spring overview
1. What is Spring?
Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in
developing any Java application, but there are extensions for building web applications on of the Java EE platform. Spring
framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based
programming model.
2. What are benefits of Spring Framework?
 Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around
2MB.
 Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their
dependencies instead of creating or looking for dependent objects.
 Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system
services.
 Container: Spring contains and manages the life cycle and configuration of application objects.
 MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web
frameworks.
 Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local
transaction and scale up to global transactions (JTA).
 Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate,
or JDO) into consistent, unchecked exceptions.
3. Which are the Spring framework modules?
The basic modules of the Spring framework are :
 Core module
 Bean module
 Context module
 Expression Language module
 JDBC module
 ORM module
 OXM module
 Java Messaging Service(JMS) module
 Transaction module
 Web module
 Web-Servlet module
 Web-Struts module
 Web-Portlet module
4. Explain the Core Container (Application context) module
This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of
any spring-based application. Spring framework was built on the of this module, which makes the Spring container.
5. BeanFactory – BeanFactory implementation example
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s
configuration and dependencies from the actual application code.
The most commonly used BeanFactory implementation is the XmlBeanFactory class.
6. XMLBeanFactory
The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory , which loads its beans based on the definitions
contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured
system or application.
7. Explain the AOP module
The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the
AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces
metadata programming to Spring.
8. Explain the JDBC abstraction and DAO module
With the JDBC abstraction and DAO module we can be sure that we keep up the database code clean and simple, and prevent
problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on of the error
messages given by several database servers. It also makes use of Spring’s AOP module to provide transaction management services
for objects in a Spring application.
9. Explain the object/relational mapping integration module
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring
provides support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction
management supports each of these ORM frameworks as well as JDBC.
10. Explain the web module
The Spring web module is built on the application context module, providing a context that is appropriate for web-based
applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for
file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with
Jakarta Struts.
11. Explain the Spring MVC module
MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks,
butSpring’s MVC framework is a better choice, since it uses IoC to provide for a clean separation of controller logic from business
objects. With Spring MVC you can declaratively bind request parameters to your business objects.
12. 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.
13. What is Spring IoC container?
The Spring IoC is responsible for creating the objects,managing them (with dependency injection (DI)), wiring them together,
configuring them, as also managing their complete lifecycle.
14. What are the benefits of IOC?
IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons
or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive
mechanism. IOC containers support eager instantiation and lazy loading of services.
15. What are the common implementations of the ApplicationContext?
The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean
configuration file must be provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to
setCLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.
16. What is the difference between Bean Factory and ApplicationContext?
Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can
publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which
have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The
application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation
being pluggable.
17. What does a Spring application look like?
 An interface that defines the functions.
 The implementation that contains properties, its setter and getter methods, functions etc.,
 Spring AOP
 The Spring configuration XML file.
 Client program that uses the function
 
Dependency Injection
18. What is Dependency Injection in Spring?
Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different
ways.This concept says 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 (the IOC container) is then responsible for hooking it all up.
19. What are the different types of IoC (dependency injection)?
 Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class
constructor with a number of arguments, each representing a dependency on other class.
 Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans
after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
20. Which DI would you suggest Constructor-based or setter-based DI?
You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for
mandatory dependencies and setters for optional dependencies.
 
Spring Beans
21. What are Spring beans?
The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed
by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example,
in the form of XML <bean/> definitions.
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named "singleton" if specified true then
bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in
spring framework are by default singleton beans.
22. What does a Spring Bean definition contain?
A Spring Bean definition contains all configuration metadata which is needed for the container to know how to create a bean, its
lifecycle details and its dependencies.
23. How do you provide configuration metadata to the Spring Container?
There are three important methods to provide configuration metadata to the Spring Container:
 XML based configuration file.
 Annotation-based configuration
 Java-based configuration
24. How do you define the scope of a bean?
When defining a <bean> in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the
bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute
to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the
beanscope attribute must be set to singleton.
25. Explain the bean scopes supported by Spring
There are five scoped provided by the Spring Framework supports following five scopes:
 In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container.
 In prototype scope, a single bean definition has any number of object instances.
 In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
 In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring
ApplicationContext.
 In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring
ApplicationContext.
The default scope of a Spring Bean is Singleton.
26. Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.
27. Explain Bean lifecycle in Spring framework
 The spring container finds the bean’s definition from the XML file and instantiates the bean.
 Spring populates all of the properties as specified in the bean definition (DI).
 If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
 If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
 If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization()method.
 If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the
specified initialization method is called.
 If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
 If the bean implements DisposableBean, it will call the destroy() method.
28. Which are the important beans lifecycle methods? Can you override them?
There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container.
The second method is the teardown method which is called when the bean is unloaded from the container.
The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom
initialization and destroy methods. There are also the correspondive annotations( @PostConstruct and @PreDestroy).
29. What are inner beans in Spring?
When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration
metadata provides the use of <bean/> element inside the <property/> or <constructor-arg/> elements of a bean definition, in order
to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.
30. How can you inject a Java Collection in Spring?
Spring offers the following types of collection configuration elements:
 The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
 The <set> type is used for wiring a set of values but without any duplicates.
 The <map> type is used to inject a collection of name-value pairs where name and value can be of any type.
 The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.
31. What is bean wiring?
Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the
Spring container needs to know what beans are needed and how the container should use dependency injection to tie them
together.
32. What is bean 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 a bean by inspecting the contents of the BeanFactory without using <constructor-
arg> and <property> elements.
33. Explain different modes of auto wiring?
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency
injection:
 no: This is default setting. Explicit bean reference should be used for wiring.
 byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is
set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same
names in the configuration file.
 byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is
set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of
the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
 constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the
constructor argument type in the container, a fatal error is raised.
 autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
34. Are there limitations with autowiring?
Limitations of autowiring are:
 Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override
autowiring.
 Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
 Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
35. Can you inject null and empty string values in Spring?
Yes, you can.
 
Spring Annotations
36. 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.
An example is the @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of
bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in
the Spring application context.
37. What is Annotation-based container configuration?
An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up
components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the
configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
38. How do you turn on annotation wiring?
Annotation wiring is not turned on in the Spring container by default. In order to use annotation based wiring we must enable it in
our Spring configuration file by configuring <context:annotation-config/< element.
39. @Required annotation
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.
40. @Autowired annotation
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. It can be
used to autowire bean on the setter method just like @Required annotation, on the constructor, on a property or pn methods with
arbitrary names and/or multiple arguments.
41. @Qualifier annotation
When there are more than one beans of the same type and only one is needed to be wired with a property,
the @Qualifier annotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will
be wired.
 
Spring Data Access
42. How can JDBC be used more efficiently in the Spring framework?
When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need
to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a
template class provided by Spring framework, which is the JdbcTemplate (example here).
43. JdbcTemplate
JdbcTemplate class 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.
44. 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 us to switch between the persistence technologies fairly easily and to code without
worrying about catching exceptions that are specific to each technology.
45. What are the ways to access Hibernate by using Spring?
There are two ways to access Hibernate with Spring:
 Inversion of Control with a Hibernate Template and Callback.
 Extending HibernateDAOSupport and Applying an AOP Interceptor node.
46. ORM’s Spring support
Spring supports the following ORM’s:
 Hibernate
 iBatis
 JPA (Java Persistence API)
 Link
 JDO (Java Data Objects)
 OJB
47. How can we integrate Spring and Hibernate using HibernateDaoSupport?
Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:
 Configure the Hibernate SessionFactory
 Extend a DAO Implementation from HibernateDaoSupport
 Wire in Transaction Support with AOP
48. Types of the transaction management Spring support
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.
 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.
49. What are the benefits of the Spring Framework’s transaction management?
 It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
 It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
 It supports declarative transaction management.
 It integrates very well with Spring’s various data access abstractions.
50. Which Transaction management type is more preferable?
Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on
application code, and hence is most consistent with the ideals of a non-invasive lightweight container. 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.
 
Spring Aspect Oriented Programming (AOP)
51. Explain 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.
52. Aspect
The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It ia 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 annotated with the @Aspect annotation (@AspectJ style).
53. What is the difference between concern and cross-cutting concern in Spring AOP
The Concern is behavior we want to have in a module of an application. A Concern may be defined as a functionality we want to
implement.
The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For
example, logging, security and data transfer are the concerns which are needed in almost every module of an application, hence
they are cross-cutting concerns.
54. Join point
The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where
an action will be taken using Spring AOP framework.
55. Advice
The advice is the actual action that will be taken either before or after the method execution. This is actual piece of code that is
invoked during the program execution by the Spring AOP framework.
Spring aspects can work with five kinds of advice:
 before: Run advice before the a method execution.
 after: Run advice after the a method execution regardless of its outcome.
 after-returning: Run advice after the a method execution only if method completes successfully.
 after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
 around: Run advice before and after the advised method is invoked.
56. Pointcut
The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or
patterns.
57. What is Introduction?
An Introduction allows us to add new methods or attributes to existing classes.
58. What is Target object?
The target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the
advised object.
59. What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the
proxy object are the same.
60. What are the different types of Auroxying?
 BeanNameAuroxyCreator
 DefaultAdvisorAuroxyCreator
 Metadata auroxying
61. What is Weaving? What are the different points where weaving can be applied?
Weaving is the process of linking aspects with other application types or objects to create an advised object.
Weaving can be done at compile time, at load time, or at runtime.
62. Explain XML Schema-based aspect implementation?
In this implementation case, aspects are implemented using regular classes along with XML based configuration.
63. Explain annotation-based (@AspectJ based) aspect implementation
This implementation case (@AspectJ based implementation) refers to a style of declaring aspects as regular Java classes annotated
with Java 5 annotations.
 
Spring Model View Controller (MVC)
64. What is Spring MVC framework?
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, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business
objects. It also allows to declaratively bind request parameters to business objects.
65. DispatcherServlet
The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.
66. 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.
67. 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.
68. @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.
69. @RequestMapping annotation
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

Q: Why Spring framework ? 


Or 
What are the benefits of Spring Framework?
Or 
What are the advantages of using Spring Framework ?
A:  Because Spring does not use much memory and CPU for loading beans, It is Comparatively light weight container in
comparison to other J2EE containers.
 Provides services like transaction control, AOP management, JDBC interaction.
 Spring Helps in creating loosely coupled applications.
 It is not dependent on any Application servers.
 Through aspect oriented programming logging, transaction, security etc. set of activities can be easily managed.
 Supports for data access techniques such as DAO, JDBC, Hibernate, IBATIS, JDO etc.
 Spring configuration is done in standard XML format which easy to write and understand.
 
Q: What is the idea of using Spring instead?
A:  Spring works on IOC (inversion of control) or DI (dependency injection) design pattern.
 Spring provides container to create and manage objects and also provides enterprise services to those objects.
 Spring is an open source application development framework.
 It provides components for different tiers of application e.g. web, middle/business and data access.
 
Q: What are the different types of modules in Spring?
or
On what modules Spring framework is based?
A: Spring has seven different modules to cater an enterprise application. These are :
 Core container: BeanFactory, an implementation of the Factory pattern is an essential component of core container.
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: Spring context comprise of configuration file that provides context information to the Spring framework.
The Spring context includes enterprise services such as internalization, validation, JNDI, and scheduling functionality.
 Spring AOP: Spring AOP module integrates aspect-oriented programming functionality directly into the Spring
framework, through its configuration management feature. Through AOP services like transaction control, logging etc
can be easily managed.
 Spring DAO: Spring DAO makes it easy to work with relational database management systems on the Java platform
using JDBC and object-relational mapping tools. 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 ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including
JDO, Hibernate, and iBatis SQL Maps.
 Spring Web module: Built on 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.
 Spring MVC framework: Model-View-Controller (MVC) framework is a full-featured MVC implementation for building
Web applications. The MVC framework is highly configurable via strategy interfaces and assembles various view
technologies including JSP, Tiles, iText, and POI.
 
Q: What is new in Spring 2.5 as compared to 2.0?
A: Spring 2.5 comes with some new and some enhanced features. Such as:
 IOC container: New bean scopes, easier xml configuration, extensible xml authoring, annotations.
 AOP: Easier xml configuration, support for @AspectJ aspects, support for bean name pointcut element, support for
AspectJ load-time waving.
 Middle tier: Declarative transactions in xml, full Websphere transaction management support, JPA, Asynchronous JMS,
JDBC improvements.
 Web tier: Changes in Spring MVC, Portlet framework, Tiles, JSF, JAX-WS support, etc.
 
Q: What is the significance of BeanFactory interface? 
Or 
What is the use of BeanFactory interface?
A: BeanFactory helps in creating Spring object with some basic functionality around object management through a well defined
configuration framework.
  BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml")); 
 
Q: What is the significance of ApplicationContext? 
Or
What is the use of ApplicationContext?
A: ApplicationContext basically revolves around Spring’s BeanFactory and provides enterprise features e.g. message resourcing,
event propagating, application-layer-specific contexts to applications, etc. It is derived from BeanFactory, so has all the
functionality of BeanFactory and adds lots more.
 
Q: Difference between BeanFactory and ApplicationContext?
A: BeanFactory represents core configuration which provides basic functionality while ApplicationContext is more about enterprise-
centric functionality support.
BeanFactory ApplicationContext
Instantiates beans lazily i.e. Beans are instantiated when you Beans are instantiated when ApplicationContext is loaded/up.
want them from BeanFactory, not on loading // Loading Application Context and instantiating bean
// loading bean factory  ApplicationContext appCtx = new
 BeanFactory factory = new XMLBeanFactory(new ClassPathXmlApplicationContext(“spring-beans.xml”);
ClassPathResource(“spring-beans.xml”));
// instantiating bean from factory or get bean
 Emp emp = factory.getBean(”myBean”);
No support for Message Internationalization Supports Message Internationalization
No event handling or event propagation mechanism. Provides event-propagation to the beans which are participating
in listening to ApplicationContext i.e. the beans implementing
ApplicationListener interface.
Access to low level resources is not convenient in Access is very convenient. Application contexts has a
BeanFactory. generic/common way to load file resources. It is a resource
loader, can load resources including
- FileSystemResource
- ClassPathResource
- ServletContextResource
- InputStreamResource
 

Q: Which is more used BeanFactory or ApplicationContext? 


Or 
Which one you prefer BeanFactory or ApplicationContext?
A: ApplicationContext. It covers almost all features which are there in BeanFactory and in addition also provides enterprise related
features, which your application might require in future.
 
Q: What are Lazily-instantiated beans?
A: Spring by default instantiate all beans at startup. This helps in overcoming any problems which came across while instantiating
beans at startup only. But sometimes, some beans are not required to be initialized during startup, rather we want them to be
initialized in later stages of application. For such beans, we include “lazy-init="true"” while configuring beans.
<bean lazy-init="true">
    <!-- this bean will not be pre-instantiated... --> 
</bean>
 
Q: What is XmlBeanFactory ?
A: XmlBeanFactory class is one of the many implementations of BeanFactory interface. This implementation helps to define your
application objects and dependencies between such objects, in terms of XML format. XmlBeanFactory extends
DefaultListableBeanFactory and defines two constructors.
 
Q: What are the common implementations of the Application Context ?
A: There are three most commonly used implementation of ‘Application Context’ as:

ClassPathXmlApplicationContext : It loads the context definition from an XML file present in the classpath, treating context
definitions as classpath resources. File ‘beans.xml’ should be present in classpath of application.
  ApplicationContext appContext = new ClassPathXmlApplicationContext(“beans.xml”);

FileSystemXmlApplicationContext : It loads the context definition from an XML file present in the filesystem. Need to give
absolute path of the file ‘beans.xml’ as given below :
ApplicationContext appContext = new  FileSystemXmlApplicationContext(“F:/java_program/SpringProject/src/com/
thecafetechno/beans.xml”);

XmlWebApplicationContext : It loads the context definition from an XML file present within a web application.
 
Q: Does Spring Framework support Transaction context propagation across remote calls ?
A: No
 
Q: What will be the outcome of using FileSystemXmlApplicationContext or ClassPathXmlApplicationContext class for request,
session and global session scopes for beans defined in the Spring's Application Context?
A: There will be an exception IllegalStateException thrown as the bean scope is not known for these implementation of Application
context from SpringFramework.
 
Q: How does spring implementation look like?
A: For a typical Spring Application we need the following files:
 An interface that defines the functions.
 An Implementation that contains properties, its setter and getter methods, functions etc.,
 A XML file called Spring configuration file.
 Client program that uses the function.
 
Q: What is the typical Bean life cycle in Spring Bean Factory Container ?
A: Bean life cycle in Spring Bean Factory Container is as follows:
 The spring container finds the bean’s definition from the XML file and instantiates the bean.
 Using the dependency injection, spring populates all of the properties as specified in the bean definition.
 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be
called.
 If an init-method is specified for the bean, it will be called.
 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will
be called.
Q: What is DelegatingVariableResolver?
A: DelegatingVariableResolver is an implementation of custom JSF VariableResolver provided by Spring which extends the standard
JSF managed bean mechanism which lets you use JSF and Spring together.
 
Q: How can I integrate Java Server Faces (JSF) with Spring?
A: Declare JSF managed-beans in the faces-config.xml configuration file, this will allow the FacesServlet to instantiate that bean at
startup. With this your JSF pages now have access to these beans and all of their properties.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
   "http://www.springframework.org/dtd/spring-beans.dtd">
<faces-config>
  <application>
    <variable-resolver>
        org.springframework.web.jsf.DelegatingVariableResolver
    </variable-resolver>
  </application>
</faces-config>

We can integrate JSF and Spring in two ways: 


1) DelegatingVariableResolver : Spring provides a JSF variable resolver that lets you use JSF and Spring together. The
DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and
then to WebApplicationContext , Spring's business context. This will allow easy injection of dependencies into JSF-managed
beans.
2) FacesContextUtils: The Custom VariableResolver works fine when mapping properties to beans in faces-config.xml, but at
times you may need to get a bean explicitly. The FacesContextUtils class makes this task easy. It is almost like
WebApplicationContextUtils, except that it takes a FacesContext as parameter instead of ServletContext.
ApplicationContextctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
 
 
Q: How can I integrate my Struts application with Spring?
A: There are two options to integrate struts application with Spring:
1) Using ContextLoaderPlugin, configure your spring app to manage actions as beans and then set their dependencies in a
spring context file.
2) Extend Spring’s ActionSupport classes and get your spring-managed beans using getWebApplicationContext() method.
 
Q: What are the different ways to access Hibernate using Spring ?
A: There are two ways to integrate Spring and hibernate:
1) By applying Inversion of control of HibernateTemplate and Callback.
2) Extend HibernateDaoSupport and applying an AOP interceptor mechanism.
 
Q: What are the different ORM’s does Spring supports ?
A: Spring provides the support of various ORMs like Hibernate, iBatis, Jav Persistence Api(JPA), OJB, Link,Java Data Objects(JDO).

 
Q: How can we integrate Spring and Hibernate using HibernateDaoSupport?
A: There is a 3 step process to integrate sparing and hibernate using spring’s SessionFactory known as LocalSessionFactory.
1) Configure Hibernate SessionFactory.
2) Extend HibernateDaoSupport
3) Through AOP wire Transaction support.
 
Q: How can we configure spring in a web application?
A: To configure your J2EE application to be Spring reach. You need to add Spring’sContextLoaderListener to your web.xml file:
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 

Q: Can you have a mycontext.xml file instead of applicationcontext.xml?


A: By default, ContextLoaderListener which is a ServletContextListener gets initialized when your webapp starts up. looks for
Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a <context-
param> element named “contextConfigLocation.” Example:
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mycontext.xml</param-value>
      </context-param>
    </listener-class>
  </listener>
 
Q: How does Spring relate to MVC framework ?
A: In Spring's Web MVC framework : a DispatcherServlet that dispatches requests to handlers.The default handler is a very simple
Controller interface, just offering a ModelAndViewhandleRequest(request,response) method.
 
Q: How can you setup MessageSources in Spring ?
A: By using ResourceBundleMessageSource and the StaticMessageSource
 
Q: What is JdbcTemplate in Spring ?
A: JdbcTemplate class is the central class packaged in the JDBC core package.
• It makes usage of JDBC very easy by handling the overhead of creation and release of resources. less chances of most common
errors like forgetting to close the connection and leaving application code to only provide SQL and fetch the results. 
• It also executes SQL queries, update statements or stored procedure calls, 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.
In the bean.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd">
<bean id="event" class="com.example.JdbcEventDao">
  <property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
</beans>
And In Java class
public class JdbcEventDao implements EventDao { 
    private JdbcTemplatejdbcTemplate; 
    public void setDataSource(DataSourcedataSource) { 
    this.jdbcTemplate = new JdbcTemplate(dataSource); 
    }
/// DO METHODS 
}

 
Q: Lifecycle interfaces in spring ?
A: 1) InitializingBean
2) DisposableBean
1) InitializingBean
<bean id="initBean" class="com.Spring.InitBean" init-method="init"/>
package com.Spring;
public class InitBean { 
public void init() { // do some initialization work } 

OR Another way,

<bean id="initBean" class=" com.Spring.InitBean "/>


package com.Spring;
public class com.Spring.InitBean implements InitializingBean { 
    public void afterPropertiesSet() { // do some initialization work } 

2) DisposableBean
<bean id="disposeBean" class=" com.Spring.DisposeBean" destroy-method="cleanup"/>
package com.Spring;
public class DisposeBean { 
    public void cleanup() { 
    // do some destruction work  
    } 
}

OR another way,

<bean id=" disposeBean " class=" com.Spring.DisposeBean"/>


package com.Spring;
public class DisposeBean implements DisposableBean { 
    public void destroy() { // do some destruction work  } 
}
 
Q: What is inversion of control (IOC) or Dependency Injection?
A: Inversion of control (IOC) or dependency injection (DI) is a design pattern used to give control to the assembler of classes.
Generally, if a class wants to use another class, it instantiates desired class. But using this design pattern, the instantiation
control is provided to the assembler. Assembler instantiates the required class and injects it in using class.
 
Q: What are different types of DI?
A: - Constructor Injection
- Setter Injection
- Interface Injection
Q: What is IoC container of Spring?
A: Spring IoC container take care of instantiation of objects, injection of objects in each other and providing enterprise services (e.g.
AOP, transaction management) to these objects.
Q: How to instantiate IoC container?

A: ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {“services.xml”, “daos.xml”});

Q: How does a web application use Spring’s configuration xmls?


A: Spring container/configuration xmls can be integrated with web application through web.xml. Following entries in web.xml can
integrate Spring container with web container.
  <context-param>
    <description>
        Context parameter to integrate Spring and Web containers
    </description>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath: services.xml,
        classpath: daos.xml
    </param-value>
  </context-param>
  
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
 
Q: How to integrate multiple bean configuration xmls?
A: Multiple bean configuration xmls are created to separate configurations according to layers so that it becomes easy to manage
and maintain them. These configuration xmls can be imported in single xml to combine all of them.
<beans>
<import resource="services.xml"/>
<import resource="daos.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
 
Q: What is autowiring?
A: By Autowiring, Spring injects dependencies without having to specify those explicitly. Spring inspects bean factory contents and
establishes relationships amongst collaborating beans. To implement it, just add autowire property in xml configuration.

 
Q: What are different modes of autowiring?
A: Autowiring has following five modes
- no: No autowiring.
- byName: Autowiring by property name, means bean matching property name is autowired.
- byType: Bean having type as that of property type is autowired.
- constructor: Similar to byType just that the property is in constructor.
- autodetect: Spring is allowed to select autowiring from byType and constructor.
 
Q: What are different bean scopes available to configure?
A: Following scopes can be assigned to different beans.
- singleton: One bean instance per IoC container
- prototype: Any number of instances of bean
- request: Within HTTPRequest object scope
- session: As long as HttpSession is alive
- globalsession: Within life-cycle of global HttpSession. Applicable in portlet context usually.
 
Q: What is default scope in Spring?
A: Singleton

Q: How can you control bean instantiation process?


A: Bean instantiation by Spring can be controlled using initialization call backs. There are two ways of doing it. First is having a
initialization method (say init()) and specifying it in bean configuration as ‘init-method’ property. Second is implementing
InitializingBean interface and implementing afterPropertiesSet() method in it.
 
Q: How can you control bean destruction process?
A: There are two ways of doing it. First is add a destroy() method and specify it in bean configuration as ‘destroy-method’ property.
Second is implement DisposableBean interface and implement destroy() method of it.
 
Q: How do you implement inheritance in bean definition?
A: Bean definition inheritance can be implemented by specifying ‘parent’ property of the bean equal to its parent bean definition
id. This bean class must have extended itself from the parent bean class.
 
Q: Difference between FileSystemResource and ClassPathResource ?
A: In FileSystemResource you need to give path of spring-config.xml (Spring Configuration) file relative to your project or the
absolute location of the file.

In ClassPathResource spring looks for the file using ClassPath so spring-config.xml should be included in classpath. If spring-
config.xml is in “src” so we can give just its name because src is in classpath path by default.

Exmple:

If in our project we put the spring-config.xml in src/com.springorg then our FileSystemResource would be:

FileSystemResource resource = newFileSystemResource("src/com/springorg/spring-config.xml");


And ClassPathResource would be:
ClassPathResource resource = newClassPathResource("com/springorg/spring-config.xml");
 
Q: How to customize bean destruction process ?
A:  
Destruction callbacks, Lifecycle callbacks, DisposableBean, destroy(), destroy-method

The Spring offers several callback interfaces to modify the behaviour of your bean. By implementing DisposableBean interface
Spring Container will call destroy() method just before the container is destroyed.

This can be achieved by following two ways

(a) ImplemetDisposableBean interface and provide implementation of destroy() method.


<bean id="disposeBean" class="com.spring.DisposeBean"/>
  public class DisposeBean implements DisposableBean {
  public void destroy() {
    // do cleanup task
  }
}

(b) Usually the above described way of customizing the bean initialization process is avoided as it forces our bean class to
implement an interface (DisposableBean) thus couples the client code to Spring Container. Same thing can be achieved by using
‘init-method’ attribute of ‘bean’ tag in Spring configuration file as given below.

<bean id=" disposeBean" class=" com.spring.DisposeBean" destroy-method="cleanup"/>


  public class DisposeBean {
  public void cleanup() {
    // do cleanup task
  }
}

 
Q: How to customize bean initialization process ?
A: Initialization callbacks, Lifecycle callbacks, InitializingBean, afterPropertiesSet(), init-method
The Spring offers several callback interfaces to modify the behaviour of your bean. By implementing InitializingBean interface
Spring Container will call afterPropertiesSet() method to allow the bean to perform certain initialization tasks after all properties
on the bean have been injected by the container .This can be achieved by following two ways

(a) ImplemetInitializingBean interface and provide implementation of afterPropertiesSet() method.

<bean id="initBean" class="com.spring.InitBean "/>


  public class InitBean implements InitializingBean {
  public void afterPropertiesSet() {
    // do initialization task
  }
}

(b) Usually the above described way of customizing the bean initialization process is avoided as it forces our bean class to
implement an interface (InitializingBean) thus couples the client code to Spring Container. Same thing can be achieved by using
‘init-method’ attribute of ‘bean’ tag in Spring configuration file as given below.

<bean id=" initBean " class=" com.spring.InitBean " init-method="init"/>


  public class InitBean {
  public void init() {
    // do initialization task
  }
}
 
Q: How to implement inheritance in Bean definition ? 
or 
What is the use of parent attribute in Spring Bean ?
A: Inheritance can be implemented by specifying the ‘parent’ attribute in bean and passing id of (parent) bean that you want to
inherit .
In the example below Employee bean inherits properties(name, age, sex) of Person bean, no need to specify these properties in
child bean (Employee).
  <!--?xml version="1.0" encoding="UTF-8"?-->
    <beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      <bean id="personBean" class="com.spring.Person">
        <property name="name" value="David"/>
        <property name="age" value="21"/>
        <property name="sex" value="male"/>
      </bean>
      <bean id="employeeBean" class=" com.spring.Employee" parent="personBean">
        <property name="company" value="XYZCompany"/>
        <property name="address" ref="addressBean"/>
      </bean>
      <bean id="addressBean" class=" com.spring.Address">
        <property name="city" value="Pune"/>
        <property name="state" value="Maharashtra"/>
      </bean>
  </beans>
 
Q: Explain inner bean in Spring ? 
or 
What is inner bean in Spring ? 
or 
What are inner beans in Spring ?
A: A bean which is defined or embedded inside the property tag of other bean is called an inner bean. Inner beans cannot be
referred by other beans except the enclosing one. In following configuration “addressBean” is an inner bean as it is defined
inside the property tag of “employeeBean”.
  <!--?xml version="1.0" encoding="UTF-8"?-->
    <beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      <bean id="employeeBean" class=" com.spring.Employee" parent="personBean">
        <property name="company" value="thecafetechno.com"/>
        <property name="address">
          <bean id="addressBean" class=" com.spring.Address">
            <property name="city" value="Pune"/>
            <property name="state" value="Maharashtra"/>
          </bean>
        </property>
      </bean>
  </beans>
Q: What is Aspect Oriented programming (AOP) ?And Howdoes AOP used in Spring ?

A: Aspect-oriented programming, or AOP, is a programming technique that allowsprogrammers 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.
AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement
for EJB declarative services. The most important such service is declarative transaction management, which
builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects,
complementing their use of OOP with AOP.
 

Q: What do you mean by Aspect in AOP?


A: Aspects mean modularization of a concern that cuts across multiple classes. Transaction management is a good example of a
crosscutting concern in J2EE applications. In my words: a trigger which can affect the multiple classes at one point.

Q: What do you mean by JointPoint?


A: A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a
join point always represents a method execution. 

Q: What do you mean by Advice?


A: Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many
AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join
point.

Q: What are the types of Advice?


A: Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow
proceeding to the join point (unless it throws an exception).
After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without
throwing an exception.
After throwing advice: Advice to be executed if a method exits by throwing an exception.
After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around
advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to
proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an
exception.

Q: What do you mean by pointcut?


A: A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the
pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut
expressions is central to AOP, and Spring uses the AspectJpointcut expression language by default. In my words a criteria used to
locate point.
Q: What do you understand by aop proxy?
A: An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In
the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Q: Are there any ways to pass value of property of a bean as NULL ?


A: Yes, By using NULL tag for passing as property's value.

Q: If the Value tag is empty then what will be passed as value to the property of the bean?
A: An empty string "" will be passed as value to the property tag if empty valuetag is present in property tag of a bean such as
follows:
<property name="">< value/><property/>

Q: Can there be any custom scope that can be defined and used along with other Springconfigurations declaratively and
programmatically?
A: Yes, one can define custom scope for the bean while scope can be registeredprogrammatically and can be used in configuration
file declaratively.

Q: What represents a Model in Spring's MVC architecture?


A: Spring's Model is based on Map interface, so by this abstraction of Model, loose coupling between View and Model is achieved
in Spring Web MVC implementation.

Q: In Spring's Web MVC Architecture, is it required to have the Model class uses frameworkspecific class or interface?
A: No, it is not required to have the model implementation depend on Spring's Frameworkspecific class or interface. Spring's Model
can be a POJO with no dependency on Spring's Framework class files.
   

Q: In Spring Web MVC, can the Controller implementation be able to write directly to the output/response stream?
A: Yes, in Spring Web MVC, Controller can write content to the output/response stream.

Q: What are the ways one can achive view resolution in Spring Web MVC?
A: One can achive view resolution in Spring Web MVC by view configuration using bean names,a properties file or custom
ViewResolver implementation by user.

Q: Are there any view resolver those having caching mechanism associated with? If yes, what are those view resolver?
A: ResourceBundleViewResolver, UrlBasedViewResolver, XmlViewResolver are the resolvers having caching mechanism associated
with these.

Q: How input data validation is handled while using Spring's Web MVC?
A: Input data type mismatch is captured as validation error while workingwith Spring Web MVC Framework.

Q: Can any object is used as command while using Spring Framework Web MVC?
A: Yes, any object can be used as Command object while using Spring Web MVC.

Q: What basic elements ModelAndView instance contains?


A: View name and Model as Map element can be found in ModelAndView instance.

Q: What are the different values a View element can have?


A: View name or value can be bean name, a properties file name or a customViewResolver name.
Q: What are the various Special beans instances can be found/associated with Spring's WebApplicationContext instance?
A: Controller instance, Handling mapping, various resolvers such as view resolvers, locale resolvers, Theme resolver, exception
handler resolvers, multipart file resolvers.

1.  What is IOC (or Dependency Injection)? 


The basic concept of the Inversion of Control pattern (also known as dependency injection) 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.

i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the
system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object
obtains references to collaborating objects. 
2. What are the different types of IOC (dependency injection) ? 
There are three types of dependency injection:
 Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
 Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
 Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection

3. What are the benefits of IOC (Dependency Injection)?


Benefits of IOC (Dependency Injection) are as follows:
 Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and
how you get references to the ones you need. You can also
easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
 Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC
containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects
into the object under test.
 Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive
because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting
piece of code. Also some containers promote the design to interfaces not to implementations design concept by
encouraging managed objects to implement a well-defined service interface of your own.
 IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of
managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.
4.  What is 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.

5. What are the advantages of Spring framework?


The advantages of Spring are as follows:
 Spring has layered architecture. Use what you need and leave you don't need now.
 Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous
integration and testability.
 Dependency Injection and Inversion of Control Simplifies JDBC
 Open source and no vendor lock-in.
6. What are features of Spring ?
 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.
 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.
 Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating application business logic
from system services.
 Container:
Spring contains and manages the life cycle and configuration of application objects.
 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.
 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.
 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
7. How many modules are there in Spring? What are they?
       Spring comprises of seven modules. They are..
 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 AOP:
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through
its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework.
The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring
AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
 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.
 Spring MVC framework:
The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The
MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP,
Velocity, Tiles, iText, and POI.
8. What are the types of Dependency Injection Spring supports?>
 Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-
argument static factory method to instantiate your bean.

 Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
9. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans
within itself and then instantiates the bean whenever asked for by clients.
 BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden
of configuration from bean itself and the beans client.
 BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

10. What is Application Context?


A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to
move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean
factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
 A means for resolving text messages, including support for internationalization.
 A generic way to load file resources.
 Events to beans that are registered as listeners.

11. What is the difference between Bean Factory and Application Context ?  


On the surface, an application context is same as a bean factory. But application context offers much more..
 Application contexts provide a means for resolving text messages, including support for i18n of those messages.
 Application contexts provide a generic way to load file resources, such as images.
 Application contexts can publish events to beans that are registered as listeners.
 Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a
bean factory, can be handled declaratively in an application context.
 ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An
application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource
instances.
 MessageSource support: The application context implements MessageSource, an interface used to obtain localized
messages, with the actual implementation being pluggable
12. What are the common implementations of the Application Context ?
   The three commonly used implementation of 'Application Context' are
 ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context
definitions as classpath resources. The application context is loaded from the application's classpath by using the code .

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");


 FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is
loaded from the file system by using the code .

ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");


 XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

13. How is a typical spring implementation look like ?


   For a typical Spring Application we need the following files:
 An interface that defines the functions.
 An Implementation that contains properties, its setter and getter methods, functions etc.,
 Spring AOP (Aspect Oriented Programming)
 A XML file called Spring configuration file.
 Client program that uses the function.
14.  What is the typical Bean life cycle in Spring Bean Factory Container ?
   Bean life cycle in Spring Bean Factory Container is as follows:
 The spring container finds the bean’s definition from the XML file and instantiates the bean.
 Using the dependency injection, spring populates all of the properties as specified in the bean definition
 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be
called.
 If an init-method is specified for the bean, it will be called.
 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be
called.

15. 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.
16. 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
17. 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

18. How to integrate  Java Server Faces (JSF) with Spring?


   JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in
the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to
these beans and all of their properties.We can integrate JSF and Spring in two ways:
 DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<faces-config>
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
</faces-config>

The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF
implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject
dependencies into one's JSF-managed beans.
 FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at
times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to
WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
19. 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.
20. What is Significance of JSF- Spring integration ?
Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such
as a bean that encapsulates the business logic to be performed when a submit button is pressed.
21. 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 and grab your Spring-managed beans explicitly using
a getWebApplicationContext() method.
22. What are ORM’s Spring supports ? 
   Spring supports the following ORM’s :
 Hibernate
 iBatis
 JPA (Java Persistence API)
 TopLink
 JDO (Java Data Objects)
 OJB
23. What are the ways to access Hibernate using Spring ?
   There are two approaches to Spring’s Hibernate integration:
 Inversion of Control with a HibernateTemplate and Callback
 Extending HibernateDaoSupport and Applying an AOP Interceptor
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
   Spring and Hibernate can integrate using Spring’s 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
25. What are Bean scopes in Spring Framework ?
   The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware
ApplicationContext). The scopes supported are listed below:
Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP
Request 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.
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context
Session
of a web-aware Spring ApplicationContext.
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only
global session
valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

26. What is 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.
27. How the AOP used in Spring?
   AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative
services. The most important such service is declarative transaction management, which builds on the Spring Framework's
transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP. 
28. What do you mean by Aspect ?
   A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting
concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular
classes annotated with the @Aspect annotation (@AspectJ style).
29. What do you mean by JointPoint?
A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join
point always represents a method execution.
30. What do you mean by Advice?
Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many
AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.
31. What are the types of Advice?
Types of advice:
 Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow
proceeding to the join point (unless it throws an exception).
 After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns
without throwing an exception.
 After throwing advice: Advice to be executed if a method exits by throwing an exception.
 After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional
return).
 Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice.
Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing
whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or
throwing an exception
32. What are the types of the transaction management Spring supports ?
   Spring Framework supports:
 Programmatic transaction management.
 Declarative transaction management.
33. 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.
 Integrates very well with Spring's various data access abstractions.
34.  Why most users of the Spring Framework choose declarative transaction management ?
   Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on
application code, and hence is most consistent with the ideals of a non-invasive lightweight container.
35. 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.
37. 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. 
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. 
38. 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.
39. What are the exceptions thrown by the Spring DAO classes ?
Spring DAO classes throw exceptions which are subclasses
ofDataAccessException(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.
40. What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own
data-access-strategy-agnosticorg.springframework.dao.DataAccessException.
41. What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC. 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. 
JdbcTemplate template = new JdbcTemplate(myDataSource);
42. What is PreparedStatementCreator ?
   PreparedStatementCreator:
 Is one of the most common used interfaces for writing data to database.
 Has one method – createPreparedStatement(Connection)
 Responsible for creating a PreparedStatement.
 Does not need to handle SQLExceptions.
43. What is SQLProvider ?
   SQLProvider:
 Has one method – getSql()
 Typically implemented by PreparedStatementCreator implementers.
 Useful for debugging.
44. What is RowCallbackHandler ?
   The RowCallbackHandler interface extracts values from each row of a ResultSet.
 Has one method – processRow(ResultSet)
 Called for each row in ResultSet.
 Typically stateful.
45. What are the differences between EJB and Spring ?
   Spring and EJB feature comparison.
Feature EJB Spring
Transaction  Must use a JTA transaction manager.  Supports multiple transaction environments through
management  Supports transactions that span  itsPlatformTransactionManager interface, including JTA,
remote method calls. Hibernate, JDO, and JDBC.
 Does not natively support distributed transactions—
it must be used with a JTA transaction manager.
Declarative  Can define transactions declaratively  Can define transactions declaratively through the Spring
transaction through the deployment descriptor. configuration file or through class metadata.
support  Can define transaction behavior per  Can define which methods to apply transaction
method or per class by using the behavior explicitly or by using regular expressions.
wildcard character *.  Can declaratively define rollback behavior per method
 Cannot declaratively define rollback and per exception type.
behavior—this must be done
programmatically.
Persistence Supports programmatic bean-managed Provides a framework for integrating with several persistence
persistence and declarative container technologies, including JDBC, Hibernate, JDO, and iBATIS.
managed persistence.
Declarative  Supports declarative security  No security implementation out-of-the box.
security through users and roles. The  Acegi, an open source security framework built on top
management and implementation of of Spring, provides declarative security through the
users and roles is container specific. Spring configuration file or class metadata.
 Declarative security is configured in
the deployment descriptor.
Distributed Provides container-managed remote method Provides proxying for remote calls via RMI, JAX-RPC, and
computing calls. web services.

Ques 1. What is Spring?


Ans. 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.
Ques 2. What are the advantages of Spring framework?
Ans. The advantages of Spring are as follows: 

► Spring has layered architecture. Use what you need and leave you don't need now. 
► Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration
and testability. 
► Dependency Injection and Inversion of Control Simplifies JDBC 
► Open source and no vendor lock-in.
Ques 3. What are features of Spring?
Ans. ► 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. 
► 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. 
► Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating
application business logic from system services. 
► Container: Spring contains and manages the life cycle and configuration of application objects. 
► 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. 
► 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. 
► JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the
error handling
Ques 4. How many modules are there in Spring? What are they?
Ans. Spring comprises of seven modules. They are.. 

► 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 AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework,
through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework.
The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you
can incorporate declarative transaction management into your applications without relying on EJB components.
Ques 5. What are the types of Dependency Injection Spring supports?
Ans. ► Setter Injection: Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor
or no-argument static factory method to instantiate your bean. 
► Constructor Injection: Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing
a collaborator.
Ques 6. What is Bean Factory?
Ans. A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple
beans within itself and then instantiates the bean whenever asked for by clients. 

► BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of
configuration from bean itself and the beans client. 
► BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
Ques 7. What is Application Context?
Ans. A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to
move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean
factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides: 

► A means for resolving text messages, including support for internationalization. 


► A generic way to load file resources. 
► Events to beans that are registered as listeners.
Ques 8. What is the difference between Bean Factory and Application Context?
Ans. On the surface, an application context is same as a bean factory. But application context offers much more.. 
► Application contexts provide a means for resolving text messages, including support for i18n of those messages. 
► Application contexts provide a generic way to load file resources, such as images. 
► Application contexts can publish events to beans that are registered as listeners. 
► Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean
factory, can be handled declaratively in an application context. 
► ResourceLoader support: Springs Resource interface us a flexible generic abstraction for handling low-level resources. An
application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances. 
► MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages,
with the actual implementation being pluggable.
Ques 9. How is a typical spring implementation look like?
Ans. For a typical Spring Application we need the following files: 
► An interface that defines the functions. 
► An Implementation that contains properties, its setter and getter methods, functions etc., 
► Spring AOP (Aspect Oriented Programming) 
► A XML file called Spring configuration file. 
► Client program that uses the function.
Ques 10. What is the typical Bean life cycle in Spring Bean Factory Container?
Ans. Bean life cycle in Spring Bean Factory Container is as follows: 
► The spring container finds the bean�s definition from the XML file and instantiates the bean. 
► Using the dependency injection, spring populates all of the properties as specified in the bean definition 
► If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean�s ID. 
► If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself. 
► If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called. 
► If an init-method is specified for the bean, it will be called. 
► Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Ques 11. What do you mean by Bean wiring?
Ans. The act of creating associations between application components (beans) within the Spring container is reffered to as Bean
wiring.
Ques 12. What do you mean by Auto Wiring?
Ans. 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
Ques 13. What is DelegatingVariableResolver?
Ans. 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.
Ques 14. What are the different modules in Spring framework?
Ans. ► The Core container module 
► Application context module 
► AOP module (Aspect Oriented Programming) 
► JDBC abstraction and DAO module 
► O/R mapping integration module (Object/Relational) 
► Web module 
► MVC framework module
Ques 15. What is the Core container module?
Ans. 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.
Ques 16. What is Application context module?
Ans. The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support
for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.
Ques 17. What is AOP module?
Ans. The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by
the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces
metadata programming to Spring. Using Spring's metadata support, we will be able to add annotations to our source code that
instruct Spring on where and how to apply aspects.
Ques 18. What is JDBC abstraction and DAO module?
Ans. Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close
database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought
in this module. In addition, this module uses Spring's AOP module to provide transaction management services for objects in a
Spring application.
Ques 19. What are object/relational mapping integration module?
Ans. Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module.
Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring's
transaction management supports each of these ORM frameworks as well as JDBC.
Ques 20. What is web module?
Ans. This module is built on the application context module, providing a context that is appropriate for web-based applications. This
module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and
programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.
Ques 21. What is AOP Alliance?
Ans. 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.
Ques 22. What is Spring configuration file?
Ans. 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.
Ques 23. What does a simple spring application contain?
Ans. These applications are like any Java application. They are made up of several classes, each performing a specific purpose within
the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to
configure the classes, known as theSpring configuration file.
Ques 24. What is XMLBeanFactory?
Ans. 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.
Ques 25. Explain Bean lifecycle in Spring framework?
Ans. 1. The spring container finds the bean�s 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 bean�s 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 post- ProcessBeforeInitialization() 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.
Ques 26. What is Significance of JSF- Spring integration?
Ans. Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand,
such as a bean that encapsulates the business logic to be performed when a submit button is pressed.
Ques 27. How to integrate your Struts application with Spring?
Ans. 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 and grab your Spring-managed beans explicitly using a getWebApplicationContext()
method.
Ques 28. What are the important beans lifecycle methods?
Ans. There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the
container. The second method is the teardown method which is called when the bean is unloaded from the container.
Ques 29. What are Inner Beans?
Ans. When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The
drawback of this bean is that it cannot be reused anywhere else.
Ques 30. What are the different types of bean injections?
Ans. There are two types of bean injections. 

1. By setter 
2. By constructor
Ques 31. What are different types of Autowire types?
Ans. There are four different types by which autowiring can be done. 

► byName 
► byType 
► constructor 
► autodetect
Ques 32. What is an Aspect?
Ans. An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing.
An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications
tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense.
However, you can create a logging aspect and apply it throughout your application using AOP.
Ques 33. What is a Jointpoint?
Ans. A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being
called, an exception being thrown, or even a field being modified. These are the points where your aspect's code can be inserted
into the normal flow of your application to add new behavior.
Ques 34. What is an Advice?
Ans. Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice
is inserted into an application at joinpoints.
Ques 35. What is a Pointcut?
Ans. A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint
that is supported by the AOP framework. These Pointcuts allow you to specify where theadvice can be applied.
Ques 36. What is an Introduction in AOP?
Ans. An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing
class without having to change the structure of the class, but give them the new behavior and state.
Ques 37. What is a Target?
Ans. A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your
own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to anyadvice
that is being applied.
Ques 38. What is a Proxy?
Ans. A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object
and the proxy object are the same.
Ques 39. What is meant by Weaving?
Ans. The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into
the target object at the specified joinpoints.
Ques 40. What are the different points where weaving can be applied?
Ans. ► Compile Time 
► Classload Time 
► Runtime
Ques 41. What are the different advice types in spring?
Ans. ► Around : Intercepts the calls to the target method 
► Before : This is called before the target method is invoked 
► After : This is called after the target method is returned 
► Throws : This is called when the target method throws and exception 
► Around : org.aopalliance.intercept.MethodInterceptor 
► Before : org.springframework.aop.BeforeAdvice 
► After : org.springframework.aop.AfterReturningAdvice 
► Throws : org.springframework.aop.ThrowsAdvice
Ques 42. What are the different types of AutoProxying?
Ans. ► BeanNameAutoProxyCreator 
► DefaultAdvisorAutoProxyCreator 
► Metadata autoproxying
Ques 43. How do you setup LDAP Authentication using Spring Security?
Ans. Spring provides out of the box support to connect Windows Active directory for LDAP authentication and with few
configuration in Spring config file you can have this feature enable.
Ques 44. How do you control concurrent Active session using Spring Security?
Ans. You can easily control How many active session a user can have with a Java application by using Spring Security.

In fact is all declarative and no code is require to enable concurrent session disable functionality. You will need to include following
xml snippet in your Spring Security Configuration file mostly named as applicaContext-security.xml. Here is sample spring security
Example of limiting user session in Java web application:

<session-management invalid-session-url="/logout.html">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>

As you see you can specify how many concurrent session per user is allowed, most secure system like online banking portals allow
just one authenticate session per user. You can even specify a URL where user will be taken if they submit an invalid session
identifier can be used to detect session timeout. Session-management element is used to capture session related stuff. Max-session
specify how many concurrent authenticated session is allowed and if error-if-maximum-exceeded set to true it will flag error if user
tries to login into another session.
Ques 45. What is IOC or inversion of control?
Ans. As the name implies Inversion of control means now we have inverted the control of creating the object from our own using
new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml
file where we configure our components, services, all the classes and their property. We just need to mention which service is
needed by which component and container will create the object for us. This concept is known as dependency injection because all
object dependency (resources) is injected into it by framework.

Example:
<bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont"> 
<property name="newBid"/>
</bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the
value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done
automatically by Spring, refereed as auto-wiring of bean in Spring.
Ques 46. Explain Bean-LifeCycle.
Ans. Spring framework is based on IOC so we call it as IOC container also So Spring beans reside inside the IOC container. Spring
beans are nothing but Plain old java object (POJO).
Following steps explain their life cycle inside container.
1. Container will look the bean definition inside configuration file (e.g. bean.xml).
2 using reflection container will create the object and if any property is defined inside the bean definition then it will also be set.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s 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 post- ProcessBeforeInitialization() methods will be called
before the properties for the Bean are set.
6. If an init() method is specified for the bean, it will be called.
7. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no
longer needs the bean reference.
8. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in
the Bean class will be called.
Ques 47. what is Bean Factory, have you used XMLBeanFactory?
Ans. BeanFactory is factory Pattern which is based on IOC design principles.it is used to make a clear separation between application
configuration and dependency from actual code.
XmlBeanFactory is one of the implementation of bean Factory which we have used in our project.
org.springframework.beans.factory.xml.XmlBeanFactory is used to create bean instance defined in our xml file.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
Or
ClassPathResource resorce = new ClassPathResource("beans.xml"); 
XmlBeanFactory factory = new XmlBeanFactory(resorce);
Ques 48. What are different modules in spring?
Ans. spring have seven core modules
1. The Core container module
2. Application context module
3. AOP module (Aspect Oriented Programming)
4. JDBC abstraction and DAO module
5. O/R mapping integration module (Object/Relational)
6. Web module
7. MVC framework module
Ques 49. What is difference between singleton and prototype bean?
Ans. Basically a bean has scopes which defines their existence on the application
Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.
Whatever beans we defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified
true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the
beans in spring framework are by default singleton beans.
<bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont" singleton="false"> 
<property name="newBid"/> 
</bean>
Ques 50. What type of transaction Management Spring support?
Ans. transaction management is a complex concept and not every developer familiar with it. Transaction management is critical in
any applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the
data is maintained. Two type of transaction management is supported by spring
1. Programmatic transaction management
2. Declarative transaction management.
Ques 51. What is AOP?
Ans. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP is a
programming technique that allows developer to modularize crosscutting concerns, that cuts across the typical divisions of
responsibility, such as logging and transaction management. Spring AOP, aspects are implemented using regular classes or regular
classes annotated with the @Aspect annotation.
Ques 52. Explain Advice?
Ans. It’s an implementation of aspect; advice is inserted into an application at join points. Different types of advice include “around,”
“before” and “after” advice.
Ques 53. What is layered architecture in spring?
Ans. Spring is one-stop shop for all your enterprise applications, however, Spring is modular, layered, allowing you to pick and
choose which modules are applicable to you, without having to bring in the rest. 
The Spring Framework provides about 20 modules which can be used based on an application requirement. 
Following section gives detail about all the modules available in Spring Framework.

Core Container:
The Core Container consists of the Core, Beans, Context, and Expression Language modules whose detail is as follows:

The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.

The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern.

The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects
defined and configured. The ApplicationContext interface is the focal point of the Context module.

The Expression Language module provides a powerful expression language for querying and manipulating an object graph at
runtime.

Data Access/Integration:
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as follows:
The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.
The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans,
JiBX and XStream.
The Java Messaging Service JMS module contains features for producing and consuming messages.
The Transaction module supports programmatic and declarative transaction management for classes that implement special
interfaces and for all your POJOs.

Web:
The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules whose detail is as follows:
The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of
the IoC container using servlet listeners and a web-oriented application context.
The Web-Servlet module contains Spring\'s model-view-controller (MVC) implementation for web applications.
The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application.
The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of
Web-Servlet module.

Miscellaneous:
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules whose detail is as follows:
The AOP module provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts
to cleanly decouple code that implements functionality that should be separated.
The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented programming (AOP)
framework.
The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain
application servers.
The Test module supports the testing of Spring components with JUnit or TestNG frameworks.
1) What is Spring Framework?
Spring is a lightweight inversion of control and aspect-oriented container framework. Spring Framework’s contribution towards java
community is immense and spring community is the largest and most innovative community by size. They have numerous projects
under their portfolio and have their own spring dmServer for running spring applications. This community is acquired by VMWare, a
leading cloud compting company for enabling the java application in the cloud by using spring stacks. If you are looking to read more
about the spring framework and its products, please read in their official site Spring Source.
2) Explain Spring?
 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.
 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.
 Aspect oriented (AOP) : Spring supports Aspect oriented programming and enables cohesive development by separating application
business logic from system services.
 Container : Spring contains and manages the life cycle and configuration of application objects.
 Framework : Spring provides most of the intra functionality leaving rest of the coding to the developer.

3) What are the different modules in Spring framework?


 The Core container module
 Application context module
 AOP module (Aspect Oriented Programming)
 JDBC abstraction and DAO module
 O/R mapping integration module (Object/Relational)
 Web module
 MVC framework module
4) What is the structure of Spring framework?

5) 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.
6) What is Application context module?
The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for
internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services
such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.
7) What is AOP module?
The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the
AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces
metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that
instruct Spring on where and how to apply aspects.
8)What is JDBC abstraction and DAO module?
Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close
database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought
in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a
Spring application.
9) What are object/relational mapping integration module?
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring
provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction
management supports each of these ORM frameworks as well as JDBC.
10) What is web module?
This module is built on the application context module, providing a context that is appropriate for web-based applications. This
module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and
programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.
11) 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, Spring’s 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 Spring’s other services, such as I18N messaging and validation.
12) What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s
configuration and dependencies from the actual application code.
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 does a simple spring application contain?
These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the
application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to
configure the classes, known as the Spring configuration file.
16) 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.
1 BeanFactory factory = new XmlBeanFactory(
2        new FileInputStream('beans.xml'));
To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.
1 MyBean myBean = (MyBean) factory.getBean('myBean');
17) What are important ApplicationContext implementations in spring framework?
 ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in the class path, treating context
definition files as class path resources.
 FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.
 XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.
18) Explain Bean lifecycle in Spring framework?
1. The spring container finds the bean’s 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 bean’s 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 post- ProcessBeforeInitialization() 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 bean wiring?
Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the
container what beans are needed and how the container should use dependency injection to tie them together.
20) How do add a bean in spring application?
1 <?xml version='1.0' encoding='UTF-8'?>
2   <!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN'
3             'http://www.springframework.org/dtd/spring-beans.dtd'>
4 <beans>

5    <bean id='foo' class='com.act.Foo'/>
6         <bean id='bar' class='com.act.Bar'/
7 </beans>
In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.
21) What are singleton beans and how can you create prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then
bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in
spring framework are by default singleton beans.
1 <beans>
2   <bean id='bar' class='com.act.Foo'
3       singleton='false'/>
4 </beans>
22) What are the important beans lifecycle methods?
There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container.
The second method is the teardown method which is called when the bean is unloaded from the container.
23) How can you override beans default lifecycle methods?
The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods.
Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.
1 <beans>
2   <bean id='bar' class='com.act.Foo'
3      init-method='fooSetup' destroy='fooTeardown'/>
4   </beans>
24) What are Inner Beans?
When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback
of this bean is that it cannot be reused anywhere else.
25) What are the different types of bean injections?
There are two types of bean injections.
1. By setter
2. By constructor
26) What is Auto wiring?
You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together.
All you have to do is just set the autowire attribute of bean tag to an autowire type.
1 <beans>
2      <bean id='bar' class='com.act.Foo' Autowire='autowire type'/>
3 </beans>
27) What are different types of Autowire types?
There are four different types by which autowiring can be done.
o byName
o byType
o constructor
o autodetect
28) What are the different types of events related to Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses
of org.springframework.context.Application-Event. They are
 ContextClosedEvent – This is fired when the context is closed.
 ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
 RequestHandledEvent – This is fired when the web context handles any request.
29) What is an Aspect?
An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An
example of an aspect is logging. Logging is something that is required throughout an application. However, because applications
tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense.
However, you can create a logging aspect and apply it throughout your application using AOP.
30) What is a Jointpoint?
A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being
called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted
into the normal flow of your application to add new behavior.
31) What is an Advice?
Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is
inserted into an application at joinpoints.
32) What is a Pointcut?
A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is
supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.
33) What is an Introduction in AOP?
An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing
class without having to change the structure of the class, but give them the new behavior and state.
34) What is a Target?
A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own
custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is
being applied.
35) What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the
proxy object are the same.
36) What is meant by Weaving?
The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the
target object at the specified joinpoints.
37) What are the different points where weaving can be applied?
 Compile Time
 Classload Time
 Runtime
38) What are the different advice types in spring?
o Around : Intercepts the calls to the target method
o Before : This is called before the target method is invoked
o After : This is called after the target method is returned
o Throws : This is called when the target method throws and exception
 Around : org.aopalliance.intercept.MethodInterceptor
 Before : org.springframework.aop.BeforeAdvice
 After : org.springframework.aop.AfterReturningAdvice
 Throws : org.springframework.aop.ThrowsAdvice
39) What are the different types of AutoProxying?
 BeanNameAutoProxyCreator
 DefaultAdvisorAutoProxyCreator
 Metadata autoproxying
40) What is the Exception class related to all the exceptions that are thrown in spring applications?
1 DataAccessException -
2    org.springframework.dao.DataAccessException
41) What kind of exceptions those spring DAO classes throw?
The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are
subclasses of DataAccessException.
42) What is DataAccessException?
DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of
exceptions.
43) How can you configure a bean to get DataSource from JNDI?
1 <bean id='dataSource'
2       class='org.springframework.jndi.JndiObjectFactoryBean'>
3     <property name='jndiName'>
4       <value>java:comp/env/jdbc/myDatasource</value>
5     </property>
6 </bean>
44) How can you create a DataSource connection pool?
1 <bean id='dataSource'
2      class='org.apache.commons.dbcp.BasicDataSource'>
3         <property name='driver'>
4           <value>${db.driver}</value>
5         </property>
6         <property name='url'>
7           <value>${db.url}</value>
8         </property>

9         <property name='username'>
10           <value>${db.username}</value>
11         </property>
12         <property name='password'>
13            <value>${db.password}</value>
14         </property>
15  </bean>
45) 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.
46) 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.
1 <strong>JdbcTemplate</strong> template = new <strong>JdbcTemplate</strong>(myDataSource);
A simple DAO class looks like this.
1 public class StudentDaoJdbc implements StudentDao {
2     private JdbcTemplate jdbcTemplate;
3     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
4        this.jdbcTemplate = jdbcTemplate;
5     } more..
6}
The configuration is shown below.
1 <bean id='jdbcTemplate' class='org.springframework.jdbc.core.JdbcTemplate'>
2        <property name='dataSource'>
3            <ref bean='dataSource'/>
4            </property>

5        </bean>
6        <bean id='studentDao' class='StudentDaoJdbc'>
7           <property name='jdbcTemplate'>
8           <ref bean='jdbcTemplate'/>
9           </property>
10        </bean>
11       <bean id='courseDao' class='CourseDaoJdbc'>
12           <property name='jdbcTemplate'>
13           <ref bean='jdbcTemplate'/>
14           </property>
15        </bean>
47) How do you write data to backend in spring using JdbcTemplate?
The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these
interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface
is BatchPreparedStatementSetter.
48) Explain about PreparedStatementCreator?
PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method
createPreparedStatement().
1 PreparedStatement <strong>createPreparedStatement</strong>
2 (Connection conn) throws SQLException;
When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the
exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also
implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.
49) Explain about BatchPreparedStatementSetter?
If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides
two methods
1 setValues(PreparedStatement ps, int i) throws SQLException;
2 int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times
setValues() will be called.
50) Explain about RowCallbackHandler and why it is used?
In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire
burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a
method processRow() which needs to be implemented so that it is applicable for each and everyrow.
1. What is Spring Framework?
Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and
“Aspect Oriented Programming”.
Spring framework can be used in normal java applications also to achieve loose coupling between different components by
implementing dependency injection and we can perform cross cutting tasks such as logging and authentication using spring
support for aspect oriented programming.
I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC.
Since it’s an open source framework with a lot of online resources and active community members, working with Spring
framework is easy and fun at same time.
2. What are some of the important features and advantages of Spring Framework?
Spring Framework is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.
Some of the features of spring framework are:
 Lightweight and very little overhead of using framework for our development.
 Dependency Injection or Inversion of Control to write components that are independent of each other, spring container
takes care of wiring them together to achieve our work.
 Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
 Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as
well as JSON response.
 Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little
configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are:
 Reducing direct dependencies between different components of the application, usually Spring IoC container is
responsible for initializing resources or beans and inject them as dependencies.
 Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with
actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing
purposes.
 Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot
because it helps us in removing all the boiler-plate code that comes with JDBC programming.
 Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we
don’t need Spring transaction management features, we don’t need to add that dependency in our project.
 Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies,
for example there is a Spring project for Android to help us write better code for native android applications. This makes
spring framework a complete package and we don’t need to look after different framework for different requirements.
3. What do you understand by Dependency Injecti on?
Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely
coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution
from compile-time to runtime.
Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable
components and easy unit testing.
Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency Injection to automate the process
of dependency injection. But in most of the cases we are looking for more than just dependency injection and that’s why Spring
is the top choice for this.
4. How do we implement DI in Spring Framework?
We can use Spring XML based as well as Annotation based configuration to implement DI in spring applications. For better
understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The
post also contains sample project zip file, that you can download and play around to learn more.
5. What are the benefi ts of using Spring Tool Suite?
We can install plugins into Eclipse to get all the features of Spring Tool Suite. However STS comes with Eclipse with some other
important stuffs such as Maven support, Templates for creating different types of Spring projects and tc server for better
performance with Spring applications.
I like STS because it highlights the Spring components and if you are using AOP pointcuts and advices, then it clearly shows
which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when
developing Spring based applications.
6. Name some of the important Spring Modules?
Some of the important Spring Framework modules are:
 Spring Context – for dependency injection.
 Spring AOP – for aspect oriented programming.
 Spring DAO – for database operations using DAO pattern
 Spring JDBC – for JDBC and DataSource support.
 Spring ORM – for ORM tools support such as Hibernate
 Spring Web Module – for creating web applications.
 Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
7. What do you understand by Aspect Oriented Programming?
Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and
application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented
Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects
and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented
programming. For example, we can have a separate class for logging but again the classes will have to call these methods for
logging the data. Read more about Spring AOP support atSpring AOP Example.
8. What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal
class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as
Aspect using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed
when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring
interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that is matched with join points to determine whether advice needs to be executed
or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ
pointcut expression language for determining the join points where advice methods will be applied.
Join Point: A join point is the specific point in the application such as method execution, exception handling, changing object
variable values etc. In Spring AOP a join points is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied
to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method
from where argument type is determined.
These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to
them.
9. What is the diff erence between Spring AOP and AspectJ AOP?
AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some
cases. Main differences between Spring AOP and AspectJ are:
 Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
 Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
 Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all
kinds of pointcuts.
 One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.
10. What is Spring IoC Container?
Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose
coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other
assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans andorg.springframework.context packages and
provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
 AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
 ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
 FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be
loaded from anywhere in the file system.
 AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
11. What is a Spring Bean?
Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use SpringApplicationContext to get
the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.
12. What is the importance of Spring bean confi gurati on fi le?
We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the
instance of Spring ApplicationContext, it reads the spring bean xml file and initialize all of them. Once the context is initialized,
we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to
support annotations based configurations.
13. What are diff erent ways to confi gure a class as Spring Bean?
There are three different ways to configure Spring Bean.
A. XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a
Spring Bean. For example:
1 <bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
B. Java Based Configuration: If you are using only annotations, you can configure a Spring bean using@Bean annotation.
This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
1 @Configuration
2 @ComponentScan(value="com.journaldev.spring.main")
3 public class MyConfiguration {
4  
5     @Bean
6     public MyService getService(){
7         return new MyService();
8     }
9 }
C. To get this bean from spring context, we need to use following code snippet:
1 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
2         MyConfiguration.class);
3 MyService service = ctx.getBean(MyService.class);
D. Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations
with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan
for these classes. For example:
1 <context:component-scan base-package="com.journaldev.spring" />

What are diff erent scopes of Spring Bean?


There are five scopes defined for Spring Beans.
A. singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans.
While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data
inconsistency issues because it’s not thread-safe.
B. prototype: A new instance will be created every time the bean is requested.
C. request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean
will be created for each HTTP request.
D. session: A new bean will be created for each HTTP session by the container.
E. global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the
scopes provided by the framework.
To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based
configurations.
What is Spring Bean life cycle?
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When context is destroyed, it also
destroys all the initialized beans. This works well in most of the cases but sometimes we want to initialize other resources or do
some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-
destroy methods in spring beans.
We can do this by two ways – by implementing InitializingBean and DisposableBean interfaces or using init-
method and destroy-method attribute in spring bean configurations. For more details, please read Spring Bean Life Cycle
Methods.
How to get ServletContext and ServletConfi g object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
A. Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete
example of these aware interfaces, please read Spring Aware Interfaces
B. Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet
container specific environment only though.
1 @Autowired
2 ServletContext servletContext;
What is Bean wiring and @Autowired annotati on?
The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
Usually it’s best practice to do the explicit wiring of all the bean dependencies, but spring framework also supports autowiring.
We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need
to enable annotation based configuration in spring bean configuration file. This can be done by context:annotation-
config element.
For more details about @Autowired annotation, please read Spring Autowire Example.
What are diff erent types of Spring Bean autowiring?
There are four types of autowiring in Spring framework.
A. autowire byName
B. autowire byType
C. autowire by constructor
D. autowiring by @Autowired and @Qualifier annotations
Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire by constructor or byType. For
more details about these options, please read Spring Bean Autowiring.
Does Spring Bean provide thread safety?
The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a
class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not
thread-safe.
However we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of
performance. It’s a design decision and based on the project requirements.
What is a Controller in Spring MVC?
Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured
resources to handle it. In Spring MVC,org.springframework.web.servlet.DispatcherServlet is the front controller class that
initializes the context based on the spring beans configurations.
A Controller class is responsible to handle different kind of client requests based on the request mappings. We can create a
controller class by using @Controller annotation. Usually it’s used with@RequestMapping annotation to define handler
methods for specific URI mapping.
What’s the diff erence between @Component, @Controller, @Repository & @Service annotati ons in Spring?
@Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean,
when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search
data. We can apply this annotation with DAO pattern implementation classes.
@Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are
annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily
distinguish the purpose of the annotated classes.
What is DispatcherServlet and ContextLoaderListener?
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and
initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean
annotated with @Component, @Controller, @Repository or @Serviceannotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions
are to tie up the lifecycle of ApplicationContext to the lifecycle of theServletContext and to automate the creation
of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
What is ViewResolver in Spring?
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean
configuration file. For example:
1 <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
2 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
3     <beans:property name="prefix" value="/WEB-INF/views/" />
4     <beans:property name="suffix" value=".jsp" />
5 </beans:bean>
InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages
directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will
use view page located at /WEB-INF/views/home.jsp.
What is a Multi partResolver and when its used?
MultipartResolver interface is used for uploading files – CommonsMultipartResolver andStandardServletMultipartResolver are
two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured
but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in
spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped
HttpServletRequest. Then it’s used in the controller class to get the file and process it. For a complete example, please
read Spring MVC File Upload Example.
How to handle excepti ons in Spring MVC Framework?
Spring MVC Framework provides following ways to help us achieving robust exception handling.
A. Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these
methods with @ExceptionHandler annotation.
B. Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice
annotation that we can use with any class to define our global exception handler.
C. HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring
Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The
reason behind this additional way to define global exception handler is that Spring framework also provides default
implementation classes that we can define in our spring bean configuration file to get spring framework exception
handling benefits.
For a complete example, please read Spring Exception Handling Example.
How to create Applicati onContext in a Java Program?
There are following ways to create spring context in a standalone java program.
A. AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for
Configuration, then we can use this to initialize the container and get the bean objects.
B. ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use
this class to load the file and get the container object.
C. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration
file can be loaded from anywhere in the file system.
Can we have multi ple Spring confi gurati on fi les?
For Spring MVC applications, we can define multiple spring context configuration files throughcontextConfigLocation. This
location string can consist of multiple locations separated by any number of commas and spaces. For example;
1 <servlet>
2     <servlet-name>appServlet</servlet-name>
3     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
4     <init-param>
5         <param-name>contextConfigLocation</param-name>
6         <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-va
7     </init-param>
8     <load-on-startup>1</load-on-startup>
9 </servlet>
We can also define multiple root level spring configurations and load it through context-param. For example;
1 <context-param>
2     <param-name>contextConfigLocation</param-name>
3     <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value>
4 </context-param>
Another option is to use import element in the context configuration file to import other configurations, for example:
1 <beans:import resource="spring-jdbc.xml"/>
What is ContextLoaderListener?
ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to
all other contexts. It’s configured in web.xml file as:
1 <context-param>
2     <param-name>contextConfigLocation</param-name>
3     <param-value>/WEB-INF/spring/root-context.xml</param-value>
4 </context-param>
5  
6 <listener>
7     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
8 </listener>
What are the minimum confi gurati ons needed to create Spring MVC applicati on?
For creating a simple Spring MVC application, we would need to do following tasks.
 Add spring-context and spring-webmvc dependencies in the project.
 Configure DispatcherServlet in the web.xml file to handle requests through spring container.
 Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to
configure view resolver for view pages.
 Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC Hello World application.

How would you relate Spring MVC Framework to MVC architecture?


As the name suggests Spring MVC is built on top of Model-View-Controller architecture.DispatcherServlet is the Front
Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller
handler methods.
Model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of
form data to java beans. We can set model beans as attributes to be used in the view pages.
View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view
page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the
view and returning the final response to the client.
How to achieve localizati on in Spring MVC applicati ons?
Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application
localized are:
A. Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
B. Defining messageSource bean in the spring bean configuration file of
typeResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
C. For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure
LocaleChangeInterceptor interceptor. Example configuration can be like below:
1 <beans:bean id="messageSource"
2     class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
3     <beans:property name="basename" value="classpath:messages" />
4     <beans:property name="defaultEncoding" value="UTF-8" />
5 </beans:bean>
6  
7 <beans:bean id="localeResolver"
8     class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
9     <beans:property name="defaultLocale" value="en" />
10     <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property>
11     <beans:property name="cookieMaxAge" value="3600"></beans:property>
12 </beans:bean>
13  
14 <interceptors>
15     <beans:bean
16         class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
17         <beans:property name="paramName" value="locale" />
18     </beans:bean>
19 </interceptors>
D. Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and
renders the page in corresponding locale and return as response.
For a complete example, please read Spring Localization Example.
How can we use Spring to create Restf ul Web Service returning JSON response?
We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson
JSON API that we can use to send JSON response in restful web service.
We would need to do following steps to configure our Spring MVC application to send JSON response:
A. Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:
1 <!-- Jackson -->
2 <dependency>
3     <groupId>com.fasterxml.jackson.core</groupId>
4     <artifactId>jackson-databind</artifactId>
5     <version>${jackson.databind-version}</version>
6 </dependency>
B. Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters
property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:
1 <!-- Configure to plugin JSON as request and response in method handler -->
2 <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
3     <beans:property name="messageConverters">
4         <beans:list>
5             <beans:ref bean="jsonMessageConverter"/>
6         </beans:list>
7     </beans:property>
8 </beans:bean>
9   
10 <!-- Configure bean to convert JSON to POJO and vice versa -->
11 <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessa
12 </beans:bean>
C. In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:
1 @RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)
2 public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {
3     logger.info("Start getEmployee. ID="+empId);
4       
5     return empData.get(empId);
6 }
D. You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate
class.
For a complete example, please read Spring Restful Webservice Example.
What are some of the important Spring annotati ons you have used?
Some of the Spring annotations that I have used in my project are:
 @Controller – for controller classes in Spring MVC project.
 @RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so
you should go through Spring MVC RequestMapping Annotation Examples
 @ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
 @PathVariable – for mapping dynamic values from the URI to handler method arguments.
 @Autowired – for autowiring dependencies in spring beans.
 @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
 @Service – for service classes.
 @Scope – for configuring scope of the spring bean.
 @Configuration, @ComponentScan and @Bean – for java based configurations.
 AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around,@Pointcut etc.
Can we send an Object as the response of Controller handler method?
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
How to upload fi le in Spring MVC Applicati on?
Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use
and requires only configuration changes to get it working. Obviously we would need to write controller handler method to
handle the incoming file and process it. For a complete example, please refer Spring File Upload Example.
How to validate form data in Spring Web MVC Framework?
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create
our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required
validations.
For custom validator implementation, we need to configure it in the controller class. For a complete example, please
read Spring MVC Form Validation Example.
What is Spring MVC Interceptor and how to use it?
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client
request at three places – preHandle, postHandle and afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract
class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client
requests or we can configure it for specific URI mapping too. For a detailed example, please refer Spring MVC Interceptor
Example.
What is Spring JdbcTemplate class and how to use it?
Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid
bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.
For JdbcTemplate example, please refer Spring JDBC Example.
How to use Tomcat JNDI DataSource in Spring Web Applicati on?
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then
inject it to spring beans as dependencies. Then we can use it withJdbcTemplate to perform database operations.
Sample configuration would be:
1 <beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
2     <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
3 </beans:bean>
For complete example, please refer Spring Tomcat JNDI Example.
How would you achieve Transacti on Management in Spring?
Spring framework provides transaction management support through Declarative Transaction Management as well as
programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and
works in most of the cases.
We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure
transaction manager for the DataSource in the spring bean configuration file.
1 <bean id="transactionManager"
2     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
3     <property name="dataSource" ref="dataSource" />
4 </bean>
What is Spring DAO?
Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For
example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport andJpaDaoSupport for respective technologies.
Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.
How to integrate Spring and Hibernate Frameworks?
We can use Spring ORM module to integrate Spring and Hibernate frameworks, if you are using Hibernate 3+ where
SessionFactory provides current session, then you should avoid usingHibernateTemplate or HibernateDaoSupport classes and
better to use DAO pattern with dependency injection for the integration.
Also Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than
going for hibernate boiler-plate code for transaction management.
For better understanding you should go through following tutorials:
 Spring Hibernate Integration Example
 Spring MVC Hibernate Integration Example
What is Spring Security?
Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of
most of the common security vulnerabilities such as CSRF attack.
It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such
as @EnableWebSecurity. You should go through following posts to learn how to use Spring Security framework.
 Spring Security in Servlet Web Application
 Spring MVC and Spring Security Integration Example
How to inject a java.uti l.Properti es into a Spring Bean?
We need to define propertyConfigurer bean that will load the properties from the given property file. Then we can use Spring
EL support to inject properties into other bean dependencies. For example;
1 <bean id="propertyConfigurer"
2   class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
3     <property name="location" value="/WEB-INF/application.properties" />
4 </bean>
5  
6 <bean class="com.journaldev.spring.EmployeeDaoImpl">
7     <property name="maxReadResults" value="${results.read.max}"/>
8 </bean>
If you are using annotation to configure the spring bean, then you can inject property like below.
1 @Value("${maxReadResults}")
2 private int maxReadResults;
Name some of the design patt erns used in Spring Framework?
Spring Framework is using a lot of design patterns, some of the common ones are:
A. Singleton Pattern: Creating beans with default scope.
B. Factory Pattern: Bean Factory classes
C. Prototype Pattern: Bean scopes
D. Adapter Pattern: Spring Web and Spring MVC
E. Proxy Pattern: Spring Aspect Oriented Programming support
F. Template Method Pattern: JdbcTemplate, HibernateTemplate etc
G. Front Controller: Spring MVC DispatcherServlet
H. Data Access Object: Spring DAO support
I. Dependency Injection and Aspect Oriented Programming
What are some of the best practi ces for Spring Framework?
Some of the best practices for Spring Framework are:
A. Avoid version numbers in schema reference, to make sure we have the latest configs.
B. Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
C. For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with
listener.
D. Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
E. For application level properties, best approach is to create a property file and read it in the spring bean configuration file.
F. For smaller applications, annotations are useful but for larger applications annotations can become a pain. If we have all
the configuration in xml files, maintaining it will be easier.
G. Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO
beans use @Repository.
H. Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that gets usually added
when you create projects through Spring Tool Suite templates.
I. If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods.
Consider custom annotations that are easier to use and avoid any issues.
J. Use dependency injection when there is actual benefit, just for the sake of loose-coupling don’t use it because it’s harder
to maintain.

1. What is IOC (or Dependency Injection)? 


The basic concept of the Inversion of Control pattern (also known as dependency injection) 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.

i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the
system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object
obtains references to collaborating objects.
2. What are the different types of IOC (dependency injection) ? 
There are three types of dependency injection:
 Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
 Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
 Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection 
3. What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
 Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and
how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a
setter method with little or no extra configuration.
 Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC
containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects
into the object under test.
 Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive
because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting
piece of code. Also some containers promote the design to interfaces not to implementations design concept by
encouraging managed objects to implement a well-defined service interface of your own.
 IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of
managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.
4.  What is 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.
5. What are the advantages of Spring framework?
The advantages of Spring are as follows:
 Spring has layered architecture. Use what you need and leave you don't need now.
 Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous
integration and testability.
 Dependency Injection and Inversion of Control Simplifies JDBC
 Open source and no vendor lock-in.
6. What are features of Spring ?
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.
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.
Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from
system services.
Container:
Spring contains and manages the life cycle and configuration of application objects.
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.
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.
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
  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.
7 . What is web module?
This module is built on the application context module, providing a context that is appropriate for web-based applications. This
module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and
programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.
8. What are the types of Dependency Injection Spring supports?
Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static
factory method to instantiate your bean.
Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
9. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans
within itself and then instantiates the bean whenever asked for by clients.
 BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden
of configuration from bean itself and the beans client.
 BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
10. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to
move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean
factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
 A means for resolving text messages, including support for internationalization.
 A generic way to load file resources.
 Events to beans that are registered as listeners.
11. What is the difference between Bean Factory and Application Context ?  
On the surface, an application context is same as a bean factory. But application context offers much more..
 Application contexts provide a means for resolving text messages, including support for i18n of those messages.
 Application contexts provide a generic way to load file resources, such as images.
 Application contexts can publish events to beans that are registered as listeners.
 Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a
bean factory, can be handled declaratively in an application context.
 ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An
application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource
instances.
 MessageSource support: The application context implements MessageSource, an interface used to obtain localized
messages, with the actual implementation being pluggable
12. What are the common implementations of the Application Context ?
   The three commonly used implementation of 'Application Context' are
 ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context
definitions as classpath resources. The application context is loaded from the application's classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
 FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is
loaded from the file system by using the code . 
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
 XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
13. How is a typical spring implementation look like ?
   For a typical Spring Application we need the following files:
 An interface that defines the functions.
 An Implementation that contains properties, its setter and getter methods, functions etc.,
 Spring AOP (Aspect Oriented Programming)
 A XML file called Spring configuration file.
 Client program that uses the function.
14.  What is the typical Bean life cycle in Spring Bean Factory Container ?
   Bean life cycle in Spring Bean Factory Container is as follows:
 The spring container finds the bean’s definition from the XML file and instantiates the bean.
 Using the dependency injection, spring populates all of the properties as specified in the bean definition
 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be
called.
 If an init-method is specified for the bean, it will be called.
 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be
called.
15. 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.
16. 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
17. 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 asDelegatingVariableResolver
18. How to integrate  Java Server Faces (JSF) with Spring? 
   JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in
the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to
these beans and all of their properties.We can integrate JSF and Spring in two ways:
 DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
   "http://www.springframework.org/dtd/spring-beans.dtd">
<faces-config>
   <application>
      <variable-resolver>
         org.springframework.web.jsf.DelegatingVariableResolver
      </variable-resolver>
   </application>
</faces-config>

The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and
then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed
beans.
 FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at
times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to
WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
19. 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.
20. What is Significance of JSF- Spring integration ?
Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such
as a bean that encapsulates the business logic to be performed when a submit button is pressed.
21. 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 and grab your Spring-managed beans explicitly using a getWebApplicationContext()
method.
22. What are ORM’s Spring supports ? 
   Spring supports the following ORM’s :
 Hibernate
 iBatis
 JPA (Java Persistence API)
 TopLink
 JDO (Java Data Objects)
 OJB
23. What are the ways to access Hibernate using Spring ?
   There are two approaches to Spring’s Hibernate integration:
 Inversion of Control with a HibernateTemplate and Callback
 Extending HibernateDaoSupport and Applying an AOP Interceptor
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
   Spring and Hibernate can integrate using Spring’s 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
25. What are Bean scopes in Spring Framework ?
   The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware
ApplicationContext). The scopes supported are listed below:
Description
Scope
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
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.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a
web-aware Spring ApplicationContext.
global Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when
session used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

26. What is 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.
27. How the AOP used in Spring?
   AOP is used in the Spring Framework:To provide declarative enterprise services, especially as a replacement for EJB declarative
services. The most important such service is declarative transaction management, which builds on the Spring Framework's
transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP.
28. What do you mean by Aspect ? 
   A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting
concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular
classes annotated with the @Aspect annotation (@AspectJ style).
29. What do you mean by JointPoint? 
A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join
point always represents a method execution.
30. What do you mean by Advice?
Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many
AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.
31. What are the types of Advice? 
Types of advice:
 Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow
proceeding to the join point (unless it throws an exception).
 After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns
without throwing an exception.
 After throwing advice: Advice to be executed if a method exits by throwing an exception.
 After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional
return).
 Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice.
Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing
whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or
throwing an exception
32. What are the types of the transaction management Spring supports ?
   Spring Framework supports:
 Programmatic transaction management.
 Declarative transaction management.
33. 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.
 Integrates very well with Spring's various data access abstractions.
34.  Why most users of the Spring Framework choose declarative transaction management ?
   Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on
application code, and hence is most consistent with the ideals of a non-invasive lightweight container.
35. 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.
36.  What are object/relational mapping integration module?
Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring
provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction
management supports each of these ORM frameworks as well as JDBC.
37. 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. 
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.
38. 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.

39. 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.
40. What is SQLExceptionTranslator ? 
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own
data-access-strategy-agnostic org.springframework.dao.DataAccessException.
41. What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC. 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. 
JdbcTemplate template = new JdbcTemplate(myDataSource);
42. What is PreparedStatementCreator ?
   PreparedStatementCreator:
 Is one of the most common used interfaces for writing data to database.
 Has one method – createPreparedStatement(Connection)
 Responsible for creating a PreparedStatement.
 Does not need to handle SQLExceptions.
43. What is SQLProvider ?
   SQLProvider:
 Has one method – getSql()
 Typically implemented by PreparedStatementCreator implementers.
 Useful for debugging.
44. What is RowCallbackHandler ?
   The RowCallbackHandler interface extracts values from each row of a ResultSet.
 Has one method – processRow(ResultSet)
 Called for each row in ResultSet.
 Typically stateful.
45. What are the differences between EJB and Spring ?
   Spring and EJB feature comparison.
EJB Spring
Feature
Transaction  Must use a JTA transaction  Supports multiple transaction environments
management manager. through its PlatformTransactionManager interface,
 Supports transactions that including JTA, Hibernate, JDO, and JDBC.
span remote method calls.  Does not natively support distributed transactions
—it must be used with a JTA transaction manager.
Declarative  Can define transactions Can define transactions declaratively through the
transaction declaratively through the Spring configuration file or through class metadata.
support deployment descriptor. Can define which methods to apply transaction
 Can define transaction behavior explicitly or by using regular expressions.
behavior per method or Can declaratively define rollback behavior per
per class by using the method and per exception type.
wildcard character *.
 Cannot declaratively define
rollback behavior—this
must be done
programmatically.
Persistence Supports programmatic bean- Provides a framework for integrating with several
managed persistence and persistence technologies, including JDBC, Hibernate, JDO,
declarative container managed and iBATIS.
persistence.
Declarative  Supports declarative  No security implementation out-of-the box.
security security through users and  Acegi, an open source security framework built on
roles. The management top of Spring, provides declarative security through
and implementation of the Spring configuration file or class metadata.
users and roles is container
specific.
 Declarative security is
configured in the
deployment descriptor.
Distributed Provides container-managed Provides proxying for remote calls via RMI, JAX-RPC, and
computing remote method calls. web services.
46 . Do I need any other SOAP framework to run Spring Web Services?
You don't need any other SOAP framework to use Spring Web services, though it can use
some of the features of Axis 1 and 2.
47 . I get NAMESPACE_ERR exceptions when using Spring-WS. What can I do about it? 
If you get the following Exception: 
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
               
Most often, this exception is related to an older version of Xalan being used. Make sure to upgrade to 2.7.0.
48 .Does Spring-WS run under Java 1.3? 
Spring Web Services requires Java 1.4 or higher.
49. Does Spring-WS work under Java 1.4? 
Spring Web Services works under Java 1.4, but it requires some effort to make it work. Java 1.4 is bundled with the older XML parser
Crimson, which does not handle namespaces correctly. Additionally, it is bundled with an older version of Xalan, which also has
problems. Unfortunately, placing newer versions of these on the class path does not override them. . 
The only solution that works is to add newer versions of Xerces and Xalan in the lib/endorsed directory of your JDK, as explained in
those FAQs (i.e.$JAVA_HOME/lib/endorsed). The following libraries are known to work with Java 1.4.2:
Version
Library
Xerces 2.8.1
Xalan 2.7.0
XML-APIs 1.3.04
SAAJ 1.2
If you want to use WS-Security, note that the XwsSecurityInterceptor requires Java 5, because an underlying library (XWSS) requires
it. Instead, you can use the Wss4jSecurityInterceptor.
50 .Does Spring-WS work under Java 1.6? 
Java 1.6 ships with SAAJ 1.3, JAXB 2.0, and JAXP 1.4 (a custom version of Xerces and Xalan). Overriding these libraries by putting
different version on the classpath will result in various classloading issues, or exceptions in
org.apache.xml.serializer.ToXMLSAXHandler. The only option for using more recent versions is to put the newer version in the
endorsed directory (see above).
51 . Why do the Spring-WS unit tests fail under Mac OS X? 
For some reason, Apple decided to include a Java 1.4 compatibility jar with their JDK 1.5. This jar includes the XML parsers which
were included in Java 1.4. No other JDK distribution does this, so it is unclear what the purpose of this compatibility jar is. 
The jar can be found at /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/.compatibility/14compatibility.jar.
You can safely remove or rename it, and the tests will run again.
52 . What is SAAJ? 
SAAJ is the SOAP with Attachments API for Java. Like most Java EE libraries, it consists of a set of interfaces (saaj-api.jar), and
implementations (saaj-impl.jar). When running in a Application Server, the implementation is typically provided by the application
server. Previously, SAAJ has been part of JAXM, but it has been released as a seperate API as part of the , and also as part of J2EE 1.4.
SAAJ is generally known as the packagejavax.xml.soap. 
Spring-WS uses this standard SAAJ library to create representations of SOAP messages. Alternatively, it can use
53 . What version of SAAJ does my application server support?
SAAJ Version
Application Server
BEA WebLogic 8 1.1
BEA WebLogic 9 1.1/1.2*
BEA WebLogic 10 1.3**
IBM WebSphere 6 1.2
SUN Glassfish 1 1.3
JBoss 4.2 1.3***
54 .I get a NoSuchMethodError when using SAAJ. What can I do about it? 
If you get the following stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'org.springframework.ws.soap.saaj.SaajSoapMessageFactory' defined in ServletContext resource [/WEB-INF/springws-servlet.xml]:
Invocation of init method failed;
nested exception is java.lang.NoSuchMethodError:
javax.xml.soap.MessageFactory.newInstance(Ljava/lang/String;)Ljavax/xml/soap/MessageFactory;
Caused by:
java.lang.NoSuchMethodError:
javax.xml.soap.MessageFactory.newInstance(Ljava/lang/String;)Ljavax/xml/soap/MessageFactory;
               
Like most J2EE libraries, SAAJ consists of two parts: the API that consists of interfaces (saaj-api.jar) and the implementation (saaj-
impl.jar). The stack trace is due to the fact that you are using a new version of the API (SAAJ 1.3), while your application server
provides an earlier version of the implementation (SAAJ 1.2 or even 1.1). Spring-WS supports all three versions of SAAJ (1.1 through
1.3), but things break when it sees the 1.3 API, while there is no 1.3 implementation. 
The solution therefore is quite simple: to remove the newer 1.3 version of the API, from the class path, and replace it with the
version supported by your application server.
55 . I get an UnsupportedOperationException "This class does not support SAAJ 1.1" when I use SAAJ under WebLogic 9. What can
I do about it? 
WebLogic 9 has a known bug in the SAAJ 1.2 implementation: it implement all the 1.2 interfaces, but throws
UnsupportedOperationExceptions when you call them. Confusingly, the exception message is This class does not support SAAJ 1.1,
even though it supports SAAJ 1.1 just fine; it just doesn't support SAAJ 1.2. See alsot 
Spring-WS has a workaround for this, we basically use SAAJ 1.1 only when dealing with WebLogic 9. Unfortunately, other
frameworks which depend on SAAJ, such as XWSS, do not have this workaround. These frameworks happily call SAAJ 1.2 methods,
which throw this exception. 
The solution is to not use BEA's version of SAAJ, but to use another implementation, like the one from Axis 1, or SUN. In you
application context, use the following: 
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
    <property name="messageFactory">
        <bean class="com.sun.xml.messaging.saaj.soap.MessageFactoryImpl"/>
    </property>
</bean>
                  
56 . I get an UnsupportedOperationException "This class does not support SAAJ 1.1" when I use SAAJ under WebLogic 10. What
can I do about it? 
Weblogic 10 ships with two SAAJ implementations. By default the buggy 9.x implementation is used (which lives in the package
weblogic.webservice.core.soap), but there is a new implementation, which supports SAAJ 1.3 (which lives in the package
weblogic.xml.saaj). By looking at the DEBUG logging when Spring Web Services starts up, you can see which SAAJ implementation is
used. 
To use this new version, you have to create a message factory bean like so: 
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
    <property name="messageFactory">
        <bean class="weblogic.xml.saaj.MessageFactoryImpl"/>
    </property>
</bean>
                   
57 . I get an IndexOutOfBoundsException when I use SAAJ under JBoss. What can I do about it? 
The SAAJ implementation provided by JBoss has some issues. The solution is therefore not to use the JBoss implementation, but to
use another implementation. For instance, you can use SUN's reference implementation like so: 
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
    <property name="messageFactory">
        <bean class="com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl"/>
    </property>
</bean>
                  
58 . Does Spring-WS run on IBM WebSphere? 
WebSphere bundles some libraries which are out-of-date, and need to be upgraded with more recent versions. Specifically, this
includes XML-apis, Xerces, Xalan, and WSDL4J. 
There are a couple of ways to upgrade these libraries, all using parent-last or application-first classloading.
 Package the libraries as part of the WAR (in WEB-INF/lib), and run the web application with the parent-last (application-first)
classloading.
 Package the libraries as part of the EAR, add class-path entries to the manifest of the web application, and run the entire
application with the parent-last classloading.
 Create a new classloader in the WebSphere console, and associate the libraries with. Set this classloader to parent-last.
The last approach has the advantage of restricting the parent-last classloading to the conflicting libraries only, and not to the entire
application.
 59. Why does Spring-WS only support contract-first? 
 Note that Spring-WS only requires you to write the XSD; the WSDL can be generated from that.
60 . How do I retrieve the WSDL from a Service?
The &WSDL query parameter does not work. 
The &WSDL query parameter is a way to get a WSDL of a class. In SWS, a service is generally not implemented as a single class, but
as a collection of endpoints. 
There are two ways to expose a WSDL:
 Simply add the WSDL to the root of the WAR, and the file is served normally. This has the disadvantage that the "location"
attribute in the WSDL is static, i.e. it does not necessarily reflect the host name of the server. You can transform locations by
using a WsdlDefinitionHandlerAdapter.
 Use theMessageDispatcherServlet, which is done is the samples. Every WsdlDefinition listed in the *-servlet.xml will be
exposed under the bean name. So if you define a WsdlDefinition namedecho, it will be exposed as echo.wsdl
(i.e.http://localhost:8080/echo/echo.wsdl).
61 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, Spring’s MVC framework uses IoC to provide for a clean separation of controller logic from
business objects. It also allows you to declaratively bind request parameters to your business objects. It also can take advantage of
any of Spring’s other services, such as I18N messaging and validation.
62 What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s
configuration and dependencies from the actual application code.
63 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.
64 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.
65 .What does a simple spring application contain?
These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the
application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to
configure the classes, known as theSpring configuration file. 
66 What is XMLBeanFactory?
BeanFactory has many implementations in Spring. But one of the most useful one
isorg.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 toXmlBeanFactory.
        BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.
        MyBean myBean = (MyBean) factory.getBean("myBean")

67 . What are important ApplicationContext implementations in spring framework?


 ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in the class path,
treating context definition files as class path resources.
 FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.
 XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web
application.
68 . Explain Bean lifecycle in Spring framework?
 The spring container finds the bean’s definition from the XML file and instantiates the bean.
 Using the dependency injection, spring populates all of the properties as specified in the bean definition.
 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be
called.
 If an init-method is specified for the bean, it will be called.
 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization()methods will be
called.
69 What is bean wiring?
Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the
container what beans are needed and how the container should use dependency injection to tie them together.
70  How do add a bean in spring application?
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
        <beans>
                <bean id="foo" class="com.act.Foo"/>
                <bean id="bar" class="com.act.Bar"/>
        </beans>
71.  What are singleton beans and how can you create prototype beans?
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then
bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in
spring framework are by default singleton beans.
        <beans>
           <bean id="bar" class="com.act.Foo" singleton=”false”/>
        </beans>
72 .  What are the important beans lifecycle methods?
There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container.
The second method is the teardown method which is called when the bean is unloaded from the container.
73 . How can you override beans default lifecycle methods?
The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods.
Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.
        <beans>
          <bean id="bar" class="com.act.Foo" init-method=”fooSetup” destroy=”fooTeardown”/>
        </beans>
74 .  What are Inner Beans?
When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback
of this bean is that it cannot be reused anywhere else.
75. What are the different types of bean injections?
There are two types of bean injections.
 By setter
 By constructor
76. What is Auto wiring?
You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together.
All you have to do is just set the autowire attribute of bean tag to an autowire type.
        <beans>
          <bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>
        </beans>
77 . What are different types of Autowire types?
There are four different types by which autowiring can be done.
o byName
o byType
o constructor
o autodetect
78. What are the different types of events related to Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of
org.springframework.context.Application-Event. They are
 ContextClosedEvent – This is fired when the context is closed.
 ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
 RequestHandledEvent – This is fired when the web context handles any request.
79. What is an Aspect?
An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An
example of an aspect is logging. Logging is something that is required throughout an application. However, because applications
tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense.
However, you can create a logging aspect and apply it throughout your application using AOP.
80 . What is a Jointpoint?
A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being
called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted
into the normal flow of your application to add new behavior.
81 What is an Advice?
Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is
inserted into an application at joinpoints.
82  What is a Pointcut?
A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is
supported by the AOP framework. These Pointcuts allow you to specify where theadvice can be applied.
83  What is an Introduction in AOP?
An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing
class without having to change the structure of the class, but give them the new behavior and state.
84  What is a Target?
A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own
custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is
being applied.
85 . What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the
proxy object are the same.
86 .What is meant by Weaving?
The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven intothe
target object at the specified joinpoints.
87  What are the different points where weaving can be applied?
 Compile Time
 Classload Time
 Runtime
88 . What are the different advice types in spring?
 Around : Intercepts the calls to the target method
 Before : This is called before the target method is invoked
 After : This is called after the target method is returned
 Throws : This is called when the target method throws and exception
 Around : org.aopalliance.intercept.MethodInterceptor
 Before : org.springframework.aop.BeforeAdvice
 After : org.springframework.aop.AfterReturningAdvice
 Throws : org.springframework.aop.ThrowsAdvice
89 What are the different types of AutoProxying?
 BeanNameAutoProxyCreator
 DefaultAdvisorAutoProxyCreator
 Metadata autoproxying

90 What kind of exceptions those spring DAO classes throw?


The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which
are subclasses of DataAccessException.
91 What is DataAccessException?
DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of
exceptions.
92  How can you configure a bean to get DataSource from JNDI?
        <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
             <property name="jndiName">
               <value>java:comp/env/jdbc/myDatasource</value>
            </property>
        </bean>
93  How can you create a DataSource connection pool?
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
           <property name="driver">
               <value>${db.driver}</value>
           </property>
           <property name="url">
              <value>${db.url}</value>
           </property>
           <property name="username">
             <value>${db.username}</value>
           </property>
           <property name="password">
            <value>${db.password}</value>
           </property>
        </bean>
94  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.
95  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 template = new JdbcTemplate(myDataSource);
A simple DAO class looks like this.
        public class StudentDaoJdbc implements StudentDao {
          private JdbcTemplate jdbcTemplate;
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
           this.jdbcTemplate = jdbcTemplate;
        }
        more..
        }
The configuration is shown below.
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
           <property name="dataSource">
               <ref bean="dataSource"/>
           </property>
        </bean>
        <bean id="studentDao" class="StudentDaoJdbc">
           <property name="jdbcTemplate">
               <ref bean="jdbcTemplate"/>
           </property>
        </bean>
        <bean id="courseDao" class="CourseDaoJdbc">
           <property name="jdbcTemplate">
               <ref bean="jdbcTemplate"/>
           </property>
        </bean>
96  How do you write data to backend in spring using JdbcTemplate?
The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these
interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is
BatchPreparedStatementSetter.
97  Explain about PreparedStatementCreator?
PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method
createPreparedStatement().
        PreparedStatement createPreparedStatement(Connection conn)
        throws SQLException;
When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the
exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also
implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.
98 Explain about BatchPreparedStatementSetter?
If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides
two methods
        setValues(PreparedStatement ps, int i) throws SQLException;
        
        int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times
setValues() will be called.
99. Explain about RowCallbackHandler and why it is used?
In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire
burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a
method processRow() which needs to be implemented so that it is applicable for each and everyrow.
        void processRow(java.sql.ResultSet rs);
100 What is JDBC abstraction and DAO module?
Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close
database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought
in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a
Spring application.

You might also like