0% found this document useful (0 votes)
4 views27 pages

Spring Notes

The document provides a comprehensive overview of the Spring Framework, detailing its modular architecture, core components, and various modules such as Core, Data Access, Web, and AOP. It explains key concepts like bean definitions, scopes, lifecycle callbacks, dependency injection, and configuration through XML. Additionally, it covers practical examples of bean creation, initialization, destruction, and the use of collections in Spring.

Uploaded by

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

Spring Notes

The document provides a comprehensive overview of the Spring Framework, detailing its modular architecture, core components, and various modules such as Core, Data Access, Web, and AOP. It explains key concepts like bean definitions, scopes, lifecycle callbacks, dependency injection, and configuration through XML. Additionally, it covers practical examples of bean creation, initialization, destruction, and the use of collections in Spring.

Uploaded by

lihomahowareyou
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Spring Tutorial

[Link]
[Link]

1. Spring framework
Spring is modular, allowing you to pick and choose which modules are applicable
to you, without having to bring in the rest.

Layer Module Description


Core Container Core provides fundamental parts of the
framework, including Ioc and Dependency
Injection
Bean provides BeanFactory
Context builds on solid base provided by Core and
Beans modules. It is a medium to access
any objects defined and configured. The
Application Context interface is the focal
point of the Context module.
SpEL provides expression language for querying
and manipulating and object graph at
runtime
Data Access / JDBC provides JDBC-abstraction layer
Integration
ORM provides integration layer for popular
object-relational mapping API, including
JPA, JDO, Hibernate and iBatis
OXM provides an abstraction layer that supports
Object/XML mapping implementations for
JAXB, Castor, XMLBeans, JiBX and XStream.
JMS producing and consuming messages
Transaction supports programmatic and declarative
transaction management for classes that
implement special interfaces and for all
your POJOs.
Web Web 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.
Web-MVC contains Spring's model-view-controller
(MVC) implementation for web
applications.
Web-Socket provides support for WebSocket-based,
two-way communication between client
and server in web applications.
Web-Portlet provides the MVC implementation to be
used in a portlet environment and mirrors
the functionality of Web-Servlet module.
Miscellaneous AOP provides aspect-oriented programming
implementation allowing you to define
method-interceptors and pointcuts to
cleanly decouple code that implements
functionality that should be separated.
Aspects provides integration with AspectJ which is
again a powerful and mature aspect
oriented programming (AOP) framework
Instrumentation provides class instrumentation support and
class loader implementations to be used in
certain application servers.
Messaging provides support for STOMP as the
WebSocket sub-protocol to use in
applications. It also supports an annotation
programming model for routing and
processing STOMP messages from
WebSocket clients.
Test supports the testing of Spring components
with JUnit or TestNG frameworks.

2. Spring Bean Definition


The bean definition contains the information called configuration
metadata which is needed for the container to know the
followings:

 How to create a bean

 Bean's lifecycle details

 Bean's dependencies

All the above configuration metadata translates into a set of the following
properties that make up each bean definition.

Properties Description

class This attribute is mandatory and specify the


bean class to be used to create the bean.

name This attribute specifies the bean identifier


uniquely. In XML-based configuration
metadata, you use the id and/or name
attributes to specify the bean identifier(s).

scope This attribute specifies the scope of the


objects created from a particular bean
definition and it will be discussed in bean
scopes chapter.

constructor-arg This is used to inject the dependencies and


will be discussed in next chapters.

properties This is used to inject the dependencies and


will be discussed in next chapters.

autowiring mode This is used to inject the dependencies and


will be discussed in next chapters.

lazy-initialization mode A lazy-initialized bean tells the IoC


container to create a bean instance when
it is first requested, rather than at startup.

initialization method A callback to be called just after all


necessary properties on the bean have
been set by the container. It will be
discussed in bean life cycle chapter.

destruction method A callback to be used when the container


containing the bean is destroyed. It will be
discussed in bean life cycle chapter.
3. Bean Scope
The Spring Framework supports following five scopes, three of which are
available only if you use a web-aware ApplicationContext.

Scope Description

singleton This scopes the bean definition to a single instance


per Spring IoC container (default).

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.

4. Bean life-cycle
Initialization callback
Implement InitializingBean interface and initialization work can
be done inside afterPropertiesSet() method as follows:

public class ExampleBean implements InitializingBean {

public void afterPropertiesSet() {

// do some initialization work


}

In the case of XML-based configuration metadata, you can use


the init-method attribute to specify the name of the method that
has a void no-argument signature. For example:

<bean id="exampleBean"

class="[Link]" init-method="init"/>

Following is the class definition:

public class ExampleBean {

public void init() {

// do some initialization work

Destroy callback
Implement DisposableBean interface and finalization work can be
done inside destroy() method as follows:

public class ExampleBean implements DisposableBean {

public void destroy() {

// do some destruction work

In the case of XML-based configuration metadata, you can use


the destroy-method attribute to specify the name of the method
that has a void no-argument signature. For example:

<bean id="exampleBean"

class="[Link]" destroy-method="destroy"/>
Following is the class definition:

public class ExampleBean {

public void destroy() {

// do some destruction work

5. Bean Post Processors

An ApplicationContext automatically detects any beans that are


defined with implementation of the BeanPostProcessor interface
and registers these beans as post-processors, to be then called
appropriately by the container upon bean creation

Here is the content of [Link] file:

package [Link];

import [Link];

import [Link];

public class InitHelloWorld implements BeanPostProcessor {

public Object postProcessBeforeInitialization(Object bean, String


beanName) throws BeansException {

[Link]("BeforeInitialization : " + beanName);

return bean; // you can return any other object as well

}
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {

[Link]("AfterInitialization : " + beanName);

return bean; // you can return any other object as well

Following is the content of the [Link] file. Here you need


to register a shutdown hook registerShutdownHook() method
that is declared on the AbstractApplicationContext class. This will
ensures a graceful shutdown and calls the relevant destroy
methods.

package [Link];

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

AbstractApplicationContext context = new


ClassPathXmlApplicationContext("[Link]");

HelloWorld obj = (HelloWorld) [Link]("helloWorld");

[Link]();

[Link]();

}
}

Following is the configuration file [Link] required for init and


destroy methods:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]

<bean id="helloWorld" class="[Link]"

init-method="init" destroy-method="destroy">

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

</bean>

<bean class="[Link]" />

</beans>

Once you are done with creating source and bean configuration
files, let us run the application. If everything is fine with your
application, this will print the following message:

BeforeInitialization : helloWorld

Bean is going through init.

AfterInitialization : helloWorld

Your Message : Hello World!

Bean will destroy now.


6. Bean Definition Inheritance
When you use XML-based configuration metadata, you indicate a child
bean definition by using the parent attribute, specifying the parent
bean as the value of this attribute.
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]

<bean id="helloWorld" class="[Link]">

<property name="message1" value="Hello World!"/>

<property name="message2" value="Hello Second World!"/>

</bean>

<bean id="helloIndia" class="[Link]"

parent="helloWorld">

<property name="message1" value="Hello India!"/>

<property name="message3" value="Namaste India!"/>

</bean>

</beans>

Here is the content of [Link] file:

package [Link];

public class HelloWorld {


private String message1;

private String message2;

public void setMessage1(String message){

this.message1 = message;

public void setMessage2(String message){

this.message2 = message;

public void getMessage1(){

[Link]("World Message1 : " + message1);

public void getMessage2(){

[Link]("World Message2 : " + message2);

Here is the content of [Link] file:

package [Link];

public class HelloIndia {

private String message1;

private String message2;

private String message3;


public void setMessage1(String message){

this.message1 = message;

public void setMessage2(String message){

this.message2 = message;

public void setMessage3(String message){

this.message3 = message;

public void getMessage1(){

[Link]("India Message1 : " + message1);

public void getMessage2(){

[Link]("India Message2 : " + message2);

public void getMessage3(){

[Link]("India Message3 : " + message3);

Following is the content of the [Link] file:


package [Link];

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new


ClassPathXmlApplicationContext("[Link]");

HelloWorld objA = (HelloWorld) [Link]("helloWorld");

objA.getMessage1();

objA.getMessage2();

HelloIndia objB = (HelloIndia) [Link]("helloIndia");

objB.getMessage1();

objB.getMessage2();

objB.getMessage3();

this will print the following message:

World Message1 : Hello World!

World Message2 : Hello Second World!

India Message1 : Hello India!

India Message2 : Hello Second World!

India Message3 : Namaste India!


If you observed here, we did not pass message2 while creating
"helloIndia" bean, but it got passed because of Bean Definition
Inheritance.

7. Dependency Injection
Class – Triangle, Circle
Application Class – DrawShape
1)
Class Triangle {
Public void Draw() {
[Link](“Draw Triangle”);
}
}
Class DrawShape {
Triangle tri = new Triangle();
Circle cir = new Circle();
[Link]();
[Link]();
}

2) Use a common interface / class for the Objects

Shape

Triangle Circle

Class Triangle and Circle extends Shape


Shape has a method draw()
Also, create a new class for drawing shape ShapeDrawer
Class ShapeDrawer {
Public void drawShape(Shape s) {
[Link]([Link]());
}
}
The revise the application class,

Class DrawShape {
Shape tri = new Triangle();
Shape cir = new Circle();
ShapeDrawer sd = new ShapeDrawer();

[Link](tri);
[Link](cir);

3) Instantiate the bean in [Link]


Class DrawShape {
BeanFactory bf = [Link](“[Link]”)
ShapeDrawer sd = new ShapeDrawer();

[Link](tri);
[Link](cir);

8. Spring 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.

Configuration for the setter-based injection:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]
[Link]

<!-- Definition for textEditor bean -->

<bean id="textEditor" class="[Link]">

<property name="spellChecker" ref="spellChecker"/>

</bean>

<!-- Definition for spellChecker bean -->

<bean id="spellChecker" class="[Link]">

</bean>

</beans>

9. Injecting Inner Bean

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]

<bean id="outerBean" class="...">

<property name="target">

<bean id="innerBean" class="..."/>

</property>

</bean>
</beans>

1) Spring – Injecting Collection


2) Spring offers four types of collection configuration elements which are as
follows:

Elemen Description
t

<list> This helps in wiring ie 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.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]
<!-- Definition for javaCollection -->

<bean id="javaCollection" class="[Link]">

<!-- results in a setAddressList([Link]) call -->

<property name="addressList">

<list>

<value>INDIA</value>

<value>Pakistan</value>

<value>USA</value>

<value>USA</value>

</list>

</property>

<!-- results in a setAddressSet([Link]) call -->

<property name="addressSet">

<set>

<value>INDIA</value>

<value>Pakistan</value>

<value>USA</value>

<value>USA</value>

</set>

</property>

<!-- results in a setAddressMap([Link]) call -->

<property name="addressMap">

<map>
<entry key="1" value="INDIA"/>

<entry key="2" value="Pakistan"/>

<entry key="3" value="USA"/>

<entry key="4" value="USA"/>

</map>

</property>

<!-- results in a setAddressProp([Link]) call -->

<property name="addressProp">

<props>

<prop key="one">INDIA</prop>

<prop key="two">Pakistan</prop>

<prop key="three">USA</prop>

<prop key="four">USA</prop>

</props>

</property>

</bean>

</beans>

10. Spring – Beans Auto-Wiring

11. Setup
 Require spring jar files
 Require common file jar
 Require [Link]

12. Understanding Spring Bean Factory


All the object is in the Spring Container

Spring Factory
An object is created by factory using factory pattern. The Spring Bean Factory will
read the configuration file [Link]

12.1 Write Code Using Bean Factory


Public static void main() {
BeanFactory factory = new XmlBeanFactory(new
FileSystemResource(“[Link]”);
Triangle tri = [Link](“triangle”); // bean id
[Link]();
}
[Link] (put in class path)
<beans>
<bean id=”triangle” class=”[Link]”></bean>
</beans>

12.2 ApplicationContext and Property Initialization


Using applicationContext instead of BeanFactory
Public static void main() {
//BeanFactory factory = new XmlBeanFactory(new
FileSystemResource(“[Link]”);
ApplicationContext context = new
ClassPathXmlApplicationContext(“[Link]”);
Triangle tri = [Link](“triangle”); // bean id
[Link]();
}

Add a type variable in class Triangle


Class Triangle {
Private String type;
Public String getType() {}
Public void setType(String type) {
[Link] = type;
}
Public void Draw() {
[Link](getType() + “ Triangle”);
}
}
Modify [Link] (property injection)
[Link]
<beans>
<bean id=”triangle” class=”[Link]”>
<property name=”type” value=”Equilateral”/>
</bean>
</beans>

12.3 Using Constructor Injection


Class Triangle {
Public Triangle(String type) {
[Link] = type;
}
[Link]
<beans>
<bean id=”triangle” class=”[Link]”>
<constructor-arg type=”[Link]” value=”Equilateral”/>
</bean>
</beans>

12.4 Injecting Object


Create a Point class
Class Point {
Private int x;
Private int y;
// getter and setters
}
Class Triangle {
Private Point pointA;
Private Point pointB;
Private Point pointC;

Public Triangle(String type) {


[Link] = type;
}
Public void draw() {
// print 3 points
}
}

Public static void main() {


ApplicationContext context = new
ClassPathXmlApplicationContext(“[Link]”);
Triangle tri = [Link](“triangle”); // bean id
[Link]();
}

[Link]
<beans>
<bean id=”triangle” class=”[Link]”>
<property name=”pointA” ref=”zeroPoint”/>
<property name=”pointB” ref=”point2”/>
<property name=”pointC” ref=”point3”/>
</bean>
<bean id=”zeroPoint” class=”[Link]”>
<property name=”x” value=”0”/>
<property name=”y” value=”0”/>
</bean>
<bean id=”point2” class=”[Link]”>
<property name=”x” value=”-20”/>
<property name=”y” value=”0”/>
</bean>
<bean id=”point3” class=”[Link]”>
<property name=”x” value=”20”/>
<property name=”y” value=” 0”/>
</bean>
</beans>

12.5 Inner Bean, alias, idref


<bean id=”triangle” class=”[Link]”>
<property name=”pointB” ref=”point2”/>
<bean class=”[Link]”>
<property name=”x” value=”-20”/>
<property name=”y” value=”0”/>
</bean>
</property>
</bean>

<alias name=”triangle” alias=”triangle-alias”/> <!—triangle-alias can be used for


reference in class 

12.6 Initializing Collections


Public class Triangle {
Private List<Point> points;
Public List<Point> getPoints() { return points;}
Public void setPoints(List<Point> points) { [Link] = points;}
}

<bean id=”triangle” class=”[Link]”>


<property name=”points” >
<list>
<ref bean=”zeroPoint”/>
<ref bean=”point2”/>
<ref bean=”point3”/>
</list>
</property>
</bean>

12.7 Bean Autowiring (自動裝配)


If the name of the member variable is equal to the name of bean defined in the
[Link], also define the autowire=“byname”
Public class Triangle {
Private Point pointA;
Private Point pointB;
}
<bean id=”triangle” class=”[Link]” autowire=”byName”>
</bean>

Also, autowire=”byType”, there should be only 1 bean with the type defined in
[Link]

Also, autowire=”constructor”, there should be only 1 bean with the type defined
in [Link]

12.8 Understanding Bean Scopes

Spring Container

Obj
Obj

ApplicationContext

Object

Spring Spring Spring


Bean Bean Bean

Spring XML

When start, initialize the ApplicationContext by reading the Spring XML and then
creates the Spring Beans. Once the Object request the Spring Bean, the
ApplicationContext handover them to Object.

Basic Bean Scopes


 Singleton – Only once per Spring container (default)
 ApplicationContext create the Triangle object, no matter how many
request for the Triangle object, the ApplicationContext return the same
Triangle object.
 Prototype – New bean created with every request or reference.
 ApplicationContext will create new ZeroPoint object with every request
or reference.
Web-aware Context Bean Scopes
 Request – New bean per servlet request
 Session – New bean per session
 Global Session – New bean per global HTTP session (portlet context)

<bean id=”triangle” class=”[Link]” scope=”singleton”>


</bean>

12.9 Using ApplicationContextAware


In order to get the applicationContext in the object e.g. Triangle, implement the
interface ApplicationContextAware
Public class Triangle implements ApplicationContextAware {…}

12.10 Bean Definition Inheritance


<bean id=”parenttriangle” class=”[Link]”>
<property name=”pointA” ref=”PointA”/>
<property name=”points”>
<list>
<ref bean=”pointC”/>
</list>
</property>
</bean>

<bean id=”triangle1” class=”[Link]” parent=”parenttriangle”>


<property name=”pointB” ref=”PointB”/>
</bean>

Override the list


<bean id=”triangle1” class=”[Link]” parent=”parenttriangle”>
<property name=”points”>
<list>
<ref bean=”pointD”/>
</list>
</property>
</bean>

Merge the list


<bean id=”triangle1” class=”[Link]” parent=”parenttriangle”>
<property name=”points”>
<list merge=”true”>
<ref bean=”pointD”/>
</list>
</property>
</bean>

12.11 Lifecycle Callbacks


Before bean initializing and actual destroy, Spring will call the code if the object
implements InitializingBean and DisposableBean interface.

Public class Triangle implements InitializingBean, DisposableBean {


Public void afterPropertiesSet() {…}
Public void destroy() {…}
}

Public static void main() {


ApplicationContext context = new
ClassPathXmlApplicationContext(“[Link]”);
[Link]();
Triangle tri = [Link](“triangle”); // bean id
[Link]();
}

OR config in the [Link]


<bean id=”triangle1” class=”[Link]” init-method=”myInit” destroy-
method=”cleanup”>
</bean>
Public class Triangle {
Public void myInit() {…}
Public void cleanup() {…}
}

OR define globally
<beans default-init-method=”myInit” default-destroy-method=”cleanUp”>

12.12 Writing a BeanPostProcessor


A common class to show the initialization and destruction of beans

<bean class=”[Link]”/>

Class DisplayNameBeanPostProcessor implements BeanPostProcessor {


Public Object postProcessAfterInitialization(Object bean, String beanName) {
// …
}
Public Object postProcessBeforeInitialization(Object bean, String beanName) {
// …
}
}

12.13 Writing a BeanFactoryPostProcessor

You might also like