Spring Short Note
Spring Short Note
Let us see what Spring Framework is, and why we need to work with this Spring…
Spring is a Java based open source, light weight, loosely coupled, aspect oriented and
dependency based app’s/J2EE Based app’s and to develop the all kind of java app’s.
Opensouce S/W means it is not only free s/w .it source code will exposed/visible to the
programmer along with installations.
Spring is a java based light weight and open source framework created by Rod
Johnson in 2003.( Most of the Spring app’s can executed without heavyweight
webserver/app’s server… )
Spring is a complete and a modular framework, i mean spring framework can be used
for all layer implementations for a real time application or spring can be used for the
development of particular layer of a real time application unlike struts [ only for front
end related ] and hibernate [ only for database related ], but with spring we can
develop all layers.
Spring framework is said to be a non-invasive means it doesn’t force a programmer to
extend or implement their class from any predefined class or interface given by Spring
API, in struts we used to extend Action Class right that’s why struts is said to be invasive
In case of struts framework, it will forces the programmer that, the programmer class
must extend from the base class provided by struts API
Spring is light weight framework because of its POJO model
Spring Framework made J2EE application development little easier, by introducing POJO
model
While executing the Spring App’s much memory and CPU resources are not required.
Spring technology is easy to learn and use
o If the Degree of Dependency is less b/w two components then we can say the
component are loosely coupled component
o If the Degree of Dependency is more b/w two components then we can say the
component are tightly coupled component
Simplicity
Testability
Loose Coupling
Simplicity
Testability
Actually for writing the spring application, server [Container] is not mandatory, but
for struts applications we need a server, and for EJB too. If we want to test the application it
may need lot of changes in the source and each time we must restart the server to view the
changes, which is little tedious and time taking but we can overcome this in Spring, for testing
spring application server is not mandatory spring has it own container to run the applications.
Spring can be used to develop any kind of java application, means we can develop starting from
console application to enterprise level application
Loose Coupling
While working with spring we can use either individual module or multiple modules to
gather.
we can integrate spring with Other Java Technologies In app’s deployment like Servlet,
JSP, Struts, and Hibernate etc…
Every spring module provides abstraction layer on providing multiple core technologies
and makes programmer free from core technologies based programing while developing
the apps.
It is always recommended to develop large scale apps by enabling the middle ware
services like security, transaction management etc…
While transferring huge amount of data or values between two layers of application
instead of sending between two layer multiple number of time its is recommended to
combine all these multiple values into single object and sends that object to destination
layer
due to this round trips between layers will be received and sending and receiving values
will become easy in struts application, form page view layer use multiple values as form
data for action class
all these values will combined into form bean class object and will be made visible in
model layer action class in two forms of single object due to this we can say form bean
class is action data transfer object or value object class
Dependency lookup:
o Resource explicitly searches and gathers dependent value from others
o In dependency lookup resource , pulls the values from others
or
o If resource of the application spending time to search and get dependent values
from other resources of application then it is called dependency lookup
o Example :
If the student get his dependent value material from instruction by asking
for it then is called dependency lookup
The way servlet / ejb component gets jdbc data source object form
registry through jndi lookup operation is called dependency lookup
o In dependency lookup resource perform “pull” operation on other resource or
on underlying s/w to get the dependent values
o Disadvantage: resource has to spend time to search and get dependent values
o Advantage: resource can get only required dependent values.
Dependency injection:
o if underlying s/w (or) framework server (or) special resource of application assign
dependent values to resource, the moment resource is ready then it is called
dependency injection or inversion of controller (IOC)
o Example :
The way student gets his course material the moment to register for
course is called dependency injection
If jdbc data source object is assigned to servlet object by servlet container
the moment servlet object is created is called dependency injection
o In dependency injection underlying s/w or container/ framework server or
special resource perform “push” operation on the resource of application to
assign dependent values the moment resource is ready
o Advantage: resource need not spend time to get dependent value and it can use
dependent value at the moment resource is ready
o Disadvantage: both necessary and unnecessary values will be injected
o In struts the way action servlet dynamically assign form data to form bean class
properties
o By creating /locating formbean class object is called dependency injection or ioc
Spring Core Module
Spring Context [ J2EE ]
Spring DAO Module [ Spring JDBC ]
Spring ORM module
Spring AOP [ Aspect Oriented Programming ]
Spring WEB-MVC Module
Spring Core is the base module for the all of other module of Spring F/W .
By using core module to understand the SpringBean life cycle management and dependency
Injection
The concrete java class that is configured in Spring configuration file through annotation is
called “SpringBean”. Javabean can act as Spring Bean but every springbean need not be a
javabean.
Spring gives two built –in containers and light weight containers
Dependency Injection:-
Instead of creating the direct object we need to inject the values from dependent class that is
called as Dependency injection
Container:
Container is a software app’s or java class that can be care of the whole lifecycle (Birth to
Death) of given resource.
Spring container is given to perform spring bean lifecycle management and to perform
dependency injection on Spring Bean.
To activate the Bean factory container on our app’s to create object for java class that
implement org.springframework.beans.factory.Beanfactory (Interface )
EX:-
To activate the app’s context container on our app’s to create object for java class that
implement org.springframework.context.applicationcontext( Interface)
We can’t create the Servlet container or JSP container by creating the object for certain
classes.so they are heavy weight container. Because we need to start heavy weight server to
activate this container.
o Spring Interface
o Spring Bean class
o Spring configuration
o Client app’s
SpringBean:-
1. Setter Injections:-
If Spring container calls setXXX() method automatically or dynamically to assign values to the
properties (member variables) of spring bean class. Then it is called Setter method
2. Constructor injections
3. Interface Injection
Partial dependency
Overriding
Number of dependencies
If we have more dependencies for example 15 to 20 are there in our bean class then,
in this case setter injection is not recommended as we need to write almost 20
setters right, bean length will increase.
Changes
Setter injection makes bean class object as mutable. (We can easily change the value
by setter injection)
Constructor injection makes bean class object as immutable. (We cannot change the
value by Constructor injection)
Difference between constructor injection and setter injection as follows:
Constructor Injection :-
1. No Partial Injection
2. Doesn't override the setter property
3. Creates new instance if any modification occurs
4. Better for too many properties
1. Partial Injection
2. Overrides the constructor property if both are defined.
3. Doesn't create new instance if you change the property value
4. Better for few properties.
ApplicationContext context =
newClassPathXmlApplicationContext{"spring_dao.xml","spring_service.xml};
You can use one or more xml file depending on your project requirement. As I am here using
two xml files i.e. one for configuration details for service classes other for dao classes. Here
ClassPathXmlApplicationContext is child of ApplicationContext
Both BeanFactory and Application are used to manage life cycle of beans, ApplicationContext
can do all things that a BeanFactory does along with AOP,Event etc..
BeanFactory ApplicationContext
(org.springframework.beans) (org.springframework.context)
Very limited access i.e.; low level It is very convenient to load resources from various
resources resources like ClassPath, FileSystem, etc.
No such support Provides generic way to load resources such as Image file
Detailed explanation for each scope can be found here in Spring bean scopes. Below is the
summary
Singleton - (Default ) Single bean object instance per spring IoC container
prototype - Opposite to singleton, it produces a new instance each and every time a bean is
requested.
request –
A single instance will be created and available during complete lifecycle of an HTTP request.
Only valid in web-aware Spring ApplicationContext.
or
Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP
request has 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 Application Context.
session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.
or
global session –
A single instance will be created and available during complete lifecycle of ServletContext.
Only valid in web-aware Spring ApplicationContext
or
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid
when used in a portlet context. Only valid in the context of a web-aware Spring
ApplicationContext
<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">
call-->
<bean id="clrBean"class="com.java2novice.bean.ColorBean"scope="prototype"/>
<bean id="ticketBean"class="com.java2novice.bean.TicketManager"scope="singleton"/>
</beans>
Spring DAO:-
DAO
1.SpringDAOmoduleprovidesabstraction layeron plain
JDBCprogrammingandsimplifiesJDBCstylepersistencelogicdevelopmentthrough
JDBCTemplateclass
2.UsingSpringDAOmodulewecan develop
persistencelogicbyimplementingDAOdesignpattern.
PlainJDBCprogramming:
SpringJDBCprogramming(SpringDAO):
1.InjectJDBC Templateclassobject.
2.UseJDBC Templateclass objectto send and executeSQLQueriesin Databasesoftware.
3.Gather and process theresultsinSpringJDBCprogramming programmer just need to
developApplicationsSpecificlogicsbecause theJDBCTemplate classinternallyuses
usesplainJDBCgeneratescommonlogics.
AdvantagesofSpringDAO:
1.Theprocessofconverting one form of execption to another form of exception
iscalledExceptionRethrowing.
2.InSpring, HibernateFrameworkstheunderlying technologiesgeneratedCheckedexceptions
willbeconverted into unChecked exceptionsbyusingExceptionRethrowingconceptasshown in
below
MVC Flow:-
Let us see the flow of spring MVC (3.2). I am not going to describe what is M,V,C hope you
already know that mess right ? so lets start with the flow…
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 top 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.
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.
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.
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 ).
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.
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.
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.
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 autowireby byType .
49. What are the benefits of the Spring Framework’s 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. 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 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
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.
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.
1. java.lang.ClassNotFoundException : This exception indicates that the class was not found on the
classpath. This indicates that we were trying to load the class definition, and the class did not exist on
the classpath.
2. java.lang.NoClassDefFoundError : This exception indicates that the JVM looked in its internal class
definition data structure for the definition of a class and did not find it. This is different than saying that
it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a
class from the classpath, but it failed for some reason – now we’re trying to use the class again (and thus
need to load it, since it failed last time), but we’re not even going to try to load it, because we failed
loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a
ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization
block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a
classpath problem.
Spring Core:-
If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by
that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent
requests and references for that named bean return the cached object.
If we not set any scope to bean then spring container will set to the default scope and default scope of
the bean is always singleton. use ‘singleton’ to set the bean scope to Singleton.
2. Prototype
If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time
a request for that specific bean is made.
Use ‘prototype’ word during spring configuration to set the bean scope to Proto Type.
As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.
3. Request:
This scopes a bean definition to an HTTP Request and its only valid in the context of a web-aware Spring
ApplicationContext.
Use the ‘request’ keyword to set the bean scope to HttpRequest during spring bean configuration.
4. Session:
This scopes a bean definition to an HTTP Session and its only valid in the context of a web-aware Spring
ApplicationContext.
Use the ‘session’ keyword to set the bean scope to Http Session during spring bean configuration.
5. Global Session
This scopes a bean definition to a Global HTTP Session and its only valid in the context of a web-aware
Spring ApplicationContext.
Use the ‘global-session’ keyword to set the bean scope to Global Http Session during spring bean
configuration.
Configuration of these scopes can be done as below:
Define the above mentioned scopes in beans.xml file along with bean declaration.
<!– A bean definition with singleton scope –>
<bean id=”…” class=”…” scope=”singleton”>
<!– collaborators and configuration for this bean go here –>
</bean>
Can also be mention the bean scope using annotation:
@Configuration
public class BeanJavaConfiguration {
@Bean
@Scope(“prototype”)
public Appleapp() {
return new Apple();
}
}
Spring MVC
Spring MVC framework is a robust Model view controller framework which helps us to develop
a loosely coupled web application. It separates different aspects of web applications with the
help of MVC architecture.
Model: Model carries application data. It generally includes POJO in the form of business
objects
View: View is used to render User interface (UI). It will render application data on UI. For
example JSP
Controller: Controller takes care of processing user request and calling back end services.
This Spring MVC tutorial is made for beginners as well as for experienced programmer.
Annotations:-
@Controller :
Spring MVC provides many abstract controllers, which is designed for specific tasks. Here is the
list of anstract controllers that comes with the Spring MVC module:
SimpleFormController
AbstractController
AbstractCommandController
CancellableFormController
AbstractCommandController
MultiActionController
ParameterizableViewController
ServletForwardingController
ServletWrappingController
UrlFilenameViewController
AbstractController
AbstractCommandController
SimpleFormController
CancellableFormController.
Types of ViewReslovers in Spring MVC:-
1. AbstractCachingViewResolver : Abstract view resolver that caches views. Often views need
preparation before they can be used; extending this view resolver provides caching.
2. XmlViewResolver : Implementation of ViewResolver that accepts a configuration file written in
XML with the same DTD as Spring’s XML bean factories. The default configuration file is /WEB-
INF/views.xml.
3. ResourceBundleViewResolver : Implementation of ViewResolver that uses bean definitions in a
ResourceBundle, specified by the bundle base name. Typically you define the bundle in a
properties file, located in the classpath. The default file name is views.properties.
4. UrlBasedViewResolver : Simple implementation of the ViewResolver interface that effects the
direct resolution of logical view names to URLs, without an explicit mapping definition. This is
appropriate if your logical names match the names of your view resources in a straightforward
manner, without the need for arbitrary mappings.
5. InternalResourceViewResolver : Convenient subclass of UrlBasedViewResolver that supports
InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and
TilesView. You can specify the view class for all views generated by this resolver by using
setViewClass(..).
6. VelocityViewResolver/FreeMarkerViewResolver : Convenient subclass of
UrlBasedViewResolver that supports VelocityView (in effect, Velocity templates) or
FreeMarkerView ,respectively, and custom subclasses of them.
7. ContentNegotiatingViewResolver : Implementation of the ViewResolver interface that resolves
a view based on the request file name or Accept header.
https://malliktalksjava.com/2009/07/09/log4j/
http://www.javainterviewpoint.com/spring-mvc-beannameurlhandlermapping-example/
Types of Handler Mapping in Spring MVC:-
Bydefault DispatcherServletuses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMappi
ng.
1. BeanNameUrlHandlerMapping
2. ControllerClassNameHandlerMapping
3. SimpleUrlHandlerMapping
Let’s take BeanNameUrlHandlerMapping in this article. Here we will be mapping each request to a Bean
directly like below
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/helloWorld.htm"
class="com.javainterviewpoint.HelloWorldController" />
<bean name="/hello*.htm"
class="com.javainterviewpoint.HelloWorldController" />
SpringConfig-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/Jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/helloWorld.htm"
class="com.javainterviewpoint.HelloWorldController" />
<bean name="/hello*"
class="com.javainterviewpoint.HelloWorldController" />
<bean name="/welcome.htm"
class="com.javainterviewpoint.WelcomeController"/>
</beans>
Using BeanNameUrlHandlerMapping
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/helloWorld.htm"
class="com.javainterviewpoint.HelloWorldController" />
<bean name="/hello*.htm"
class="com.javainterviewpoint.HelloWorldController" />
Using ControllerClassNameHandlerMapping
Using <value> tag
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/welcome.htm=welcomeController
/welcome*=welcomeController
/hell*=helloWorldController
/helloWorld.htm=helloWorldController
</value>
</property>
</bean>
Using <props> tag
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
<prop key="/welcome*">welcomeController</prop>
<prop key="/helloworld">helloWorldController</prop>
<prop key="/hello*">helloWorldController</prop>
<prop key="/HELLOworld">helloWorldController</prop>
</props>
</property>
</bean>
SpringConfig-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/Jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
<prop key="/welcome*">welcomeController</prop>
<prop key="/helloworld">helloWorldController</prop>
<prop key="/hello*">helloWorldController</prop>
<prop key="/HELLOworld">helloWorldController</prop>
</props>
</property>
</bean>