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.