SKILLWISE – SPRING
FRAMEWORK
2
Contents
ļ‚§ What is Spring Framework?
ļ‚§ History of Spring Framework
ļ‚§ Spring Overview
ļ‚§ Spring Architecture
ļ‚§ IOC and Dependency Injection
ļ‚§ Bean Factory, Beans and Bean Definition
ļ‚§ Lifecycle events of a Bean
ļ‚§ Bean Post Processor
ļ‚§ Advantages of Spring
ļ‚§ Spring and EJB
3
What is Spring Framework?
ļ‚§ Spring is an open source framework
ļ‚§ Spring is a Lightweight Application framework
ļ‚§ Where Struts, WebWork and others can be considered
Web frameworks, Spring addresses all tiers of an
application
ļ‚§ Spring provides the plumbing so that you don’t have to
do the unwanted redundant job
ļ‚§ Essence of Spring is providing enterprise services to
simple POJO
4
History of Spring Framework
ļ‚§ Started 2002/2003 by Rod Johnson and Juergen Holler
ļ‚§ Started as a framework developed around Rod
Johnson’s book Expert One-on-One J2EE Design and
Development
ļ‚§ Spring 1.0 Released March 2004
ļ‚§ 2004/2005 onwards: Spring is emerging as a leading
full-stack Java/J2EE application framework
ļ‚§ Recent version: 3.0
5
Spring Architecture - Overview
Note: Spring distribution comes as one big jar file and alternatively as a series of smaller jars
broken out along the above lines (so you can include only what you need)
6
Spring Architecture - Overview
ļ‚§ Spring Core: Most import component of the Spring Framework which provides the
Dependency Injection features. The BeanFactory provides a factory pattern which
separates the dependencies like initialization, creation and access of the objects from
the actual program logic
ļ‚§ Spring Context: Builds on the beans package to add support for message sources
and the ability for application objects to obtain resources using a consistent API
ļ‚§ Spring AOP: One of the key components of Spring. Used to provide declarative
enterprise services
ļ‚§ Spring ORM: Related to the database access using OR mapping
ļ‚§ Spring DAO: Used for standardizing the data access work using the technologies
like JDBC, Hibernate or JDO
ļ‚§ Spring Web: Spring’s web application development stack (includes Spring MVC)
ļ‚§ Spring Web MVC: Provides the MVC implementations for the web applications
7
But really, What is Spring?
ļ‚§ At it’s core, Spring provides:
• An Inversion of Control Container
o Also known as Dependency Injection
• An AOP Framework
o Spring provides a proxy-based AOP framework
• A Service Abstraction Layer
o Consistent integration with various standard and 3rd party APIs
ļ‚§ These together enables to write powerful, scalable
applications using POJOs
ļ‚§ Spring at it’s core is a framework for wiring up your
entire application
ļ‚§ Bean Factories are the heart of Spring
8
IOC and Dependency Injection
ļ‚§ Spring Container pushes dependency to the application
at runtime
ļ‚§ Against pull dependencies from environment
ļ‚§ Different types of injection
ļ‚§ Setter injection
<property name=ā€œemployeeDaoā€>
<ref local=ā€œemployeeDaoā€>
</property>
ļ‚§ Constructor injection
<constructor-arg>
<ref local=ā€œemployeeDaoā€>
<constructor-arg>
ļ‚§ Method injection
ļ‚§ How to decide between setter and constructor
injection?
Dependency Injection (IoC)
ļ‚§ The ā€œHollywood Principleā€: Don’t call me, I’ll call you
ļ‚§ Eliminates lookup code from within your application
ļ‚§ Allows for pluggablity and hot swapping
ļ‚§ Promotes good OO design
ļ‚§ Enables reuse of existing code
ļ‚§ Makes your application extremely testable
10
Bean Factory
ļ‚§ A BeanFactory is typically configured in an XML file
with the root element: <beans>
ļ‚§ The XML contains one or more <bean> elements
ļ‚§ id (or name) attribute to identify the bean
ļ‚§ class attribute to specify the fully qualified class
ļ‚§ By default, beans are treated as singletons
ļ‚§ Can also be prototypes
<beans>
<bean id=ā€œwidgetServiceā€
class=ā€œcom.zabada.base.WidgetServiceā€>
<property name=ā€œpoolSizeā€>
<!—-property value here-->
</property>
</bean>
</beans>
The bean’s ID
The bean’s fully-
qualified
classname
Maps to a setPoolSize() call
Property Values for BeanFactories
ļ‚§ Strings and Numbers
ļ‚§ Arrays and Collections
<property name=ā€œsizeā€><value>42</value></property>
<property name=ā€œnameā€><value>Jim</value></property>
<property name=ā€œhobbiesā€>
<list>
<value>Basket Weaving</value>
<value>Break Dancing</value>
</list>
</property>
Property Values for BeanFactories (continued)
The real magic comes in when you can set a property on a
bean that refers to another bean in the configuration:
This is the basic concept of Inversion of Control
<bean name=ā€œwidgetServiceā€ class=ā€œcom.zabada.base.WidgetServiceImplā€>
<property name=ā€œwidgetDAOā€>
<ref bean=ā€œmyWidgetDAOā€/>
</property>
</bean>
calls
setWidgetDAO(myWidgetDAO)
where myWidgetDAO is another
bean defined in the configuration
A Very Special BeanFactory:
ApplicationContext
ļ‚§ An ApplicationContext is a BeanFactory with more
ā€œframeworkā€ features such as:
– i18n messages
– Event notifications
ļ‚§ This is what you will probably use most often in your Spring
applications
14
Bean Factory and Configurations (Contd..,)
ļ‚§ Bean factory works as the container
ļ‚§ BeanFactory is an Interface
ļ‚§ ApplicationContext is also a beanfactory. It is a sub
class of BeanFactory interface
ļ‚§ How to start the container?
ApplicationContext context = new ClassPathApplicationContext(
new FileSystemXmlApplicationContext(
15
Bean information
ļ‚§ How to get the bean?
context.getBean(beanName)
ļ‚§ An individual bean definition contains the information
needed for the container to know how to create a bean, the
lifecycle methods and information about bean's
dependencies
ļ‚§ Usage of ref local and ref bean while accessing the
bean in multiple context files
16
Ref Local vs Ref Bean vs Ref Parent
ļ‚§ <ref local=ā€œemployeeDaoā€ />
ļ‚§ <ref bean=ā€œemployeeDaoā€ />
ļ‚§ <ref parent=ā€œemployeeDaoā€ />
17
Spring Injection - Example
public class Inject {
private String name;
private int age;
private String company;
private String email;
private String address;
public void setAddress(String address) {
this.address = address;
}
public void setCompany(String company) {
this.company = company;
}
public void setEmail(String email) {
this.email = email;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Name: %sn" +
"Age: %dn" +
"Address: %sn" +
"Company: %sn" +
"E-mail: %s",
this.name, this.age, this.address, this.company, this.email);
}
}
18
Spring Injection - Example
import org.springframework.beans.factory.xml.XmlBeanFactory
import org.springframework.core.io.ClassPathResource;
public class Main {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPath
Resource("context.xml"));
Inject demo = (Inject) beanFactory.getBean("mybean");
System.out.println(demo);
}
}
19
Spring Injection - Example
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mybean"
class="Inject"
p:name=ā€œKumar"
p:age="28"
p:address=ā€œTrivandrum"
p:company=ā€œUST"
p:email=ā€œkumar@ust-global.com"/>
</beans>
20
Spring Injection - Example
Name: Kumar
Age: 28
Address: Trivandrum
Company: UST
E-mail: kumar@ust-global.com
21
Other features of Bean configuration
ļ‚§ Auto wiring
ļ‚§ Automatically wires the beans
ļ‚§ Bean Post processor
ļ‚§ Special Listeners
ļ‚§ Post processing logic after a bean is initialized
Public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName)
Object postProcessAfterInitialization(Object bean, String beanName)
}
ļ‚§ Property Place holder
ļ‚§ Place the property information in context.xml
22
Code Snippet for Bean Post Processor
public class DatabaseRow {
private String rowId;
private int noOfColumns;
private List<String> values;
public String getRowId() {
return rowId;
}
public void setRowId(String rowId) {
this.rowId = rowId;
}
public int getNoOfColumns() {
return noOfColumns;
}
public void setNoOfColumns(int noOfColumns) {
this.noOfColumns = noOfColumns;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}
23
Code Snippet for Bean Post Processor
public class DBRowBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("Before Initialization");
System.out.println("Bean object: " + bean);
System.out.println("Bean name: " + beanName);
DatabaseRow dbRow = null;
if (bean instanceof DatabaseRow) {
dbRow = (DatabaseRow)bean;
dbRow.setRowId("ROWID-001");
dbRow.setNoOfColumns(3);
return dbRow;
}
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("After Initialization");
System.out.println("Bean object: " + bean);
System.out.println("Bean name: " + beanName);
DatabaseRow dbRow = null;
if (bean instanceof DatabaseRow) {
dbRow = (DatabaseRow)bean;
dbRow.setValues(Arrays.asList("Antony", "10", "93232"));
return dbRow;
}
return null;
}
}
24
Code Snippet for Bean PreProcessor
static void beanPostProcessorTest()
{
Resource resource = new FileSystemResource("./src/resources/bean-lifecycle.xml");
ConfigurableBeanFactory xmlBeanFactory = new XmlBeanFactory(resource);
DBRowBeanPostProcessor processor = new DBRowBeanPostProcessor();
xmlBeanFactory.addBeanPostProcessor(processor);
DatabaseRow databaseRow =
(DatabaseRow)xmlBeanFactory.getBean("databaseRow");
System.out.println("Row Id: " + databaseRow.getRowId());
System.out.println("Columns: " + databaseRow.getNoOfColumns());
System.out.println("Values : " + databaseRow.getValues().toString());
}
25
How to initialize Spring in web.xml?
ļ‚§ Register the ContextLoader Servlet
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
ļ‚§ Specify the path of the Context configuration Location
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
26
Advantages of Spring Framework
ļ‚§ Non-invasive framework
ļ‚§ Promotes code reuse
ļ‚§ Facilitates Object Oriented programming
ļ‚§ Promotes pluggability
ļ‚§ Easy to test
ļ‚§ Spring provides a consistent way to glue your whole
application together
Quick Recap
ļ‚§ Open Source and Light weight application framework
ļ‚§ Bean Factory and Beans
ļ‚§ IOC or Dependency Injection
ļ‚§ Program to Interfaces
ļ‚§ Also, Spring comes with .Net flavour (Spring.net)
Spring and EJB
Discussion !!!
References
ļ‚§ Professional Java Development with Spring Framework –
Rod Johnson
ļ‚§ http://static.springsource.org
ļ‚§ http://www.springbyexample.org
30
Questions?
Skillwise-Spring framework 1

Skillwise-Spring framework 1

  • 1.
  • 2.
    2 Contents ļ‚§ What isSpring Framework? ļ‚§ History of Spring Framework ļ‚§ Spring Overview ļ‚§ Spring Architecture ļ‚§ IOC and Dependency Injection ļ‚§ Bean Factory, Beans and Bean Definition ļ‚§ Lifecycle events of a Bean ļ‚§ Bean Post Processor ļ‚§ Advantages of Spring ļ‚§ Spring and EJB
  • 3.
    3 What is SpringFramework? ļ‚§ Spring is an open source framework ļ‚§ Spring is a Lightweight Application framework ļ‚§ Where Struts, WebWork and others can be considered Web frameworks, Spring addresses all tiers of an application ļ‚§ Spring provides the plumbing so that you don’t have to do the unwanted redundant job ļ‚§ Essence of Spring is providing enterprise services to simple POJO
  • 4.
    4 History of SpringFramework ļ‚§ Started 2002/2003 by Rod Johnson and Juergen Holler ļ‚§ Started as a framework developed around Rod Johnson’s book Expert One-on-One J2EE Design and Development ļ‚§ Spring 1.0 Released March 2004 ļ‚§ 2004/2005 onwards: Spring is emerging as a leading full-stack Java/J2EE application framework ļ‚§ Recent version: 3.0
  • 5.
    5 Spring Architecture -Overview Note: Spring distribution comes as one big jar file and alternatively as a series of smaller jars broken out along the above lines (so you can include only what you need)
  • 6.
    6 Spring Architecture -Overview ļ‚§ Spring Core: Most import component of the Spring Framework which provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from the actual program logic ļ‚§ Spring Context: Builds on the beans package to add support for message sources and the ability for application objects to obtain resources using a consistent API ļ‚§ Spring AOP: One of the key components of Spring. Used to provide declarative enterprise services ļ‚§ Spring ORM: Related to the database access using OR mapping ļ‚§ Spring DAO: Used for standardizing the data access work using the technologies like JDBC, Hibernate or JDO ļ‚§ Spring Web: Spring’s web application development stack (includes Spring MVC) ļ‚§ Spring Web MVC: Provides the MVC implementations for the web applications
  • 7.
    7 But really, Whatis Spring? ļ‚§ At it’s core, Spring provides: • An Inversion of Control Container o Also known as Dependency Injection • An AOP Framework o Spring provides a proxy-based AOP framework • A Service Abstraction Layer o Consistent integration with various standard and 3rd party APIs ļ‚§ These together enables to write powerful, scalable applications using POJOs ļ‚§ Spring at it’s core is a framework for wiring up your entire application ļ‚§ Bean Factories are the heart of Spring
  • 8.
    8 IOC and DependencyInjection ļ‚§ Spring Container pushes dependency to the application at runtime ļ‚§ Against pull dependencies from environment ļ‚§ Different types of injection ļ‚§ Setter injection <property name=ā€œemployeeDaoā€> <ref local=ā€œemployeeDaoā€> </property> ļ‚§ Constructor injection <constructor-arg> <ref local=ā€œemployeeDaoā€> <constructor-arg> ļ‚§ Method injection ļ‚§ How to decide between setter and constructor injection?
  • 9.
    Dependency Injection (IoC) ļ‚§The ā€œHollywood Principleā€: Don’t call me, I’ll call you ļ‚§ Eliminates lookup code from within your application ļ‚§ Allows for pluggablity and hot swapping ļ‚§ Promotes good OO design ļ‚§ Enables reuse of existing code ļ‚§ Makes your application extremely testable
  • 10.
    10 Bean Factory ļ‚§ ABeanFactory is typically configured in an XML file with the root element: <beans> ļ‚§ The XML contains one or more <bean> elements ļ‚§ id (or name) attribute to identify the bean ļ‚§ class attribute to specify the fully qualified class ļ‚§ By default, beans are treated as singletons ļ‚§ Can also be prototypes <beans> <bean id=ā€œwidgetServiceā€ class=ā€œcom.zabada.base.WidgetServiceā€> <property name=ā€œpoolSizeā€> <!—-property value here--> </property> </bean> </beans> The bean’s ID The bean’s fully- qualified classname Maps to a setPoolSize() call
  • 11.
    Property Values forBeanFactories ļ‚§ Strings and Numbers ļ‚§ Arrays and Collections <property name=ā€œsizeā€><value>42</value></property> <property name=ā€œnameā€><value>Jim</value></property> <property name=ā€œhobbiesā€> <list> <value>Basket Weaving</value> <value>Break Dancing</value> </list> </property>
  • 12.
    Property Values forBeanFactories (continued) The real magic comes in when you can set a property on a bean that refers to another bean in the configuration: This is the basic concept of Inversion of Control <bean name=ā€œwidgetServiceā€ class=ā€œcom.zabada.base.WidgetServiceImplā€> <property name=ā€œwidgetDAOā€> <ref bean=ā€œmyWidgetDAOā€/> </property> </bean> calls setWidgetDAO(myWidgetDAO) where myWidgetDAO is another bean defined in the configuration
  • 13.
    A Very SpecialBeanFactory: ApplicationContext ļ‚§ An ApplicationContext is a BeanFactory with more ā€œframeworkā€ features such as: – i18n messages – Event notifications ļ‚§ This is what you will probably use most often in your Spring applications
  • 14.
    14 Bean Factory andConfigurations (Contd..,) ļ‚§ Bean factory works as the container ļ‚§ BeanFactory is an Interface ļ‚§ ApplicationContext is also a beanfactory. It is a sub class of BeanFactory interface ļ‚§ How to start the container? ApplicationContext context = new ClassPathApplicationContext( new FileSystemXmlApplicationContext(
  • 15.
    15 Bean information ļ‚§ Howto get the bean? context.getBean(beanName) ļ‚§ An individual bean definition contains the information needed for the container to know how to create a bean, the lifecycle methods and information about bean's dependencies ļ‚§ Usage of ref local and ref bean while accessing the bean in multiple context files
  • 16.
    16 Ref Local vsRef Bean vs Ref Parent ļ‚§ <ref local=ā€œemployeeDaoā€ /> ļ‚§ <ref bean=ā€œemployeeDaoā€ /> ļ‚§ <ref parent=ā€œemployeeDaoā€ />
  • 17.
    17 Spring Injection -Example public class Inject { private String name; private int age; private String company; private String email; private String address; public void setAddress(String address) { this.address = address; } public void setCompany(String company) { this.company = company; } public void setEmail(String email) { this.email = email; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } @Override public String toString() { return String.format("Name: %sn" + "Age: %dn" + "Address: %sn" + "Company: %sn" + "E-mail: %s", this.name, this.age, this.address, this.company, this.email); } }
  • 18.
    18 Spring Injection -Example import org.springframework.beans.factory.xml.XmlBeanFactory import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPath Resource("context.xml")); Inject demo = (Inject) beanFactory.getBean("mybean"); System.out.println(demo); } }
  • 19.
    19 Spring Injection -Example <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="mybean" class="Inject" p:name=ā€œKumar" p:age="28" p:address=ā€œTrivandrum" p:company=ā€œUST" p:email=ā€œkumar@ust-global.com"/> </beans>
  • 20.
    20 Spring Injection -Example Name: Kumar Age: 28 Address: Trivandrum Company: UST E-mail: kumar@ust-global.com
  • 21.
    21 Other features ofBean configuration ļ‚§ Auto wiring ļ‚§ Automatically wires the beans ļ‚§ Bean Post processor ļ‚§ Special Listeners ļ‚§ Post processing logic after a bean is initialized Public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object bean, String beanName) Object postProcessAfterInitialization(Object bean, String beanName) } ļ‚§ Property Place holder ļ‚§ Place the property information in context.xml
  • 22.
    22 Code Snippet forBean Post Processor public class DatabaseRow { private String rowId; private int noOfColumns; private List<String> values; public String getRowId() { return rowId; } public void setRowId(String rowId) { this.rowId = rowId; } public int getNoOfColumns() { return noOfColumns; } public void setNoOfColumns(int noOfColumns) { this.noOfColumns = noOfColumns; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } }
  • 23.
    23 Code Snippet forBean Post Processor public class DBRowBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Before Initialization"); System.out.println("Bean object: " + bean); System.out.println("Bean name: " + beanName); DatabaseRow dbRow = null; if (bean instanceof DatabaseRow) { dbRow = (DatabaseRow)bean; dbRow.setRowId("ROWID-001"); dbRow.setNoOfColumns(3); return dbRow; } return null; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("After Initialization"); System.out.println("Bean object: " + bean); System.out.println("Bean name: " + beanName); DatabaseRow dbRow = null; if (bean instanceof DatabaseRow) { dbRow = (DatabaseRow)bean; dbRow.setValues(Arrays.asList("Antony", "10", "93232")); return dbRow; } return null; } }
  • 24.
    24 Code Snippet forBean PreProcessor static void beanPostProcessorTest() { Resource resource = new FileSystemResource("./src/resources/bean-lifecycle.xml"); ConfigurableBeanFactory xmlBeanFactory = new XmlBeanFactory(resource); DBRowBeanPostProcessor processor = new DBRowBeanPostProcessor(); xmlBeanFactory.addBeanPostProcessor(processor); DatabaseRow databaseRow = (DatabaseRow)xmlBeanFactory.getBean("databaseRow"); System.out.println("Row Id: " + databaseRow.getRowId()); System.out.println("Columns: " + databaseRow.getNoOfColumns()); System.out.println("Values : " + databaseRow.getValues().toString()); }
  • 25.
    25 How to initializeSpring in web.xml? ļ‚§ Register the ContextLoader Servlet <servlet> <servlet-name>context</servlet-name> <servlet-class> org.springframework.web.context.ContextLoaderServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> ļ‚§ Specify the path of the Context configuration Location <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param>
  • 26.
    26 Advantages of SpringFramework ļ‚§ Non-invasive framework ļ‚§ Promotes code reuse ļ‚§ Facilitates Object Oriented programming ļ‚§ Promotes pluggability ļ‚§ Easy to test ļ‚§ Spring provides a consistent way to glue your whole application together
  • 27.
    Quick Recap ļ‚§ OpenSource and Light weight application framework ļ‚§ Bean Factory and Beans ļ‚§ IOC or Dependency Injection ļ‚§ Program to Interfaces ļ‚§ Also, Spring comes with .Net flavour (Spring.net)
  • 28.
  • 29.
    References ļ‚§ Professional JavaDevelopment with Spring Framework – Rod Johnson ļ‚§ http://static.springsource.org ļ‚§ http://www.springbyexample.org
  • 30.