005 Spring63
005 Spring63
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
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.
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.
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.
<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">
</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.
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>
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: 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,
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,
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
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:
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.
(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.
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
(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.
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: 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.
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
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.
<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.
► 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:
► 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.
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" />
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.