An introduction to the Spring Framework
-
Upload
weiliatslideshare -
Category
Technology
-
view
1.883 -
download
2
description
Transcript of An introduction to the Spring Framework
An Introduction to the Spring Framework - Wei Li, 11/17/2004
An Introduction to Spring FrameworkWei Li
Spring Framework Background
An open source project founded by Rod Johnson in February 2003
Based on the infrastructure code for Rod's book "Expert One-on-One J2EE Design and Development"
Stemmed from his several successful real world applications dated back to early 2000
Took experience and lessons of many other projects
Good documentation (reference manual, books, white papers, presentations
Current release version 1.1.2 (released on 11/14/2004)
Being ported to .NET, thereby providing "one stone, two birds" solution
Overview of Spring Framework
One of the best lightweight Java IOC containers
Many other high quality modules (sub-framework built upon its IOC)
One-stop shop for many infrastructure needs
Spring writes lots of plumbing code for you: the code which is not concerned with the real business operation
Let developers focus on what really needs to be done and make it easier to do
Overall, Spring makes J2EE easier to use - the mission of Spring Framework
Overview of Spring Framework
Does not reinvent the wheel, and provides good integration with existing solutions, while avoiding competition with these solutions
Layered architectural design so that it is easy to use any part of the framework
Less intrusive - your code does not reply on Spring API
POJO based IOC container - simple but powerful
Develop and configure application in a consistent way
Promotes good OO programming practices
Promotes testability
What Does Spring Framework Offer
Source: Spring's Official Reference Documentation
Build a Full Fledged Application Using Spring
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 1/17
Source: Spring's Official Reference Documentation
Using Spring with Others
Source: Spring's Official Reference Documentation
Overview of Inversion of Control
Source: http://www.jroller.com/resources/J2JBlog/IoC_in_Action.jpg
What is IOC - What Do People Say?
Hollywood Principle: Do not call me, I call you
Martin Fowler: Dependency Injection
Unknown: Give without asking
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 2/17
Yours truly: Push not pull
What Does IOC Do?
Create new objects
Configure/solve dependency among objects and assembly them
Allow objects to be retrieved by id/name
Manage objects' lifecycle
Allow external configuration
Source: http://www.pyrasun.com/mike/mt/archives/2004/11/06/15.46.14/index.html
What Does IOC Do?
Silly Example - Hello, IndyJUG; Hello, World
Class B and C depend on D
Class A depends on B and C
D must be implemented as singleton
Main class only uses A and does not care about B, C and D
Code: net.weili.spring.ioc.whyioc
What Does IOC Do?
Old way - the end class has to take care of everything!
What Does IOC Do?
IOC way - the end class only concerns about A, nothing else
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 3/17
What Does IOC Do?
Inversion of Control!
What Does IOC Do?
Now the questions:
1. What is the end class really concerned about?
2. Where is the coupling?
3. Which one is easier to code and maintain?
4. Which one is easier to test?
5. Does IOC help you?
Why Do We Use IOC?
Reduces the amount of code in your application
Does the plumbing work for you
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 4/17
Makes your application more testable
No more reading and processing configuration file
No more creating and hooking them together
No more lookup...
Reference: HiveMind
So What - Do I Have to Use IOC?
No. There is nothing that you have to do with IOC. However, using IOC will:
Move dependency/coupling from code into configuration file
Move the object management into IOC container
Have the IOC container do the plumbing work for you
Your code will be clean
Be productive - less code, less chance to make mistake
Have fun - this is important
Your application is more maintainable and testable
Types of Inversion of Control
Source: Spring's Official Reference Documentation
Available Java IOC Containers
Spring IOC
HiveMind (Howard Lewis Ship, also in the fame of Tapestry)
PicoContainer (Martin Fowler and the ThoughtWorks folks)
Avalon (Apache project. Is it dying?)
Dependency Injection in Action
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 5/17
Source: http://www.jroller.com/resources/J2JBlog/di_in_action.jpg
Break 1: Software Development Bad Ideas
Order the T-Shirts for the development team
Announcement the availability date
Code
Write the manual
Hire a product manager
Spec the software (writing the spec after the code helps to ensure that the software meets the spec.)
Ship it!
Test (The customers are a big help here)
Identify bugs as potential enhancements or features
Announce the upgraded program
Source: unknown
Spring's IOC
The core of the whole Spring framework
Foundation of other Spring framework's components - achieve internal consistence
POJO based, interface oriented
Setter and constructor dependency injection
Good support for external configuration: beans can be defined in XML or properties files
Spring's IOC - Java Bean
Spring IOC works with plain Java beans
POJO: constructors, getters and setters - could not be simpler
Does not rely on vendor API or application server
Very powerful: Spring configures/manages POJO; Hibernate maps POJO to relational database and Velocity presents POJO
The simple solution is usually the right solution
Spring's IOC - Bean Definition
Define beans
Define the relations among beans
Define the rules of how beans work
XML or properties file format
IOC's BeanFactory will parse it and make objects ready to be used
Spring's IOC - Bean Definition
Spring bean definition - simple but consistent
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 6/17
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans>
<bean id="..." class="..."> ... </bean>
<bean id="..." class="..."> ... </bean>
...
</beans>
Spring's IOC - Bean Definition
Spring bean definition contains:
id/name (required)
class (required)
singleton or prototype (default: singleton)
properties
constructor arguments
Initialization method
Destruction method
Others...
Spring's IOC - Bean Definition
Bean Definition in XML format (most commonly used)
Define beans
Set bean properties: simple data type
Set bean properties: Properties, List, Set, Map
Configure dependency: set reference to other bean
Configure dependency: through constructor injection
Demo
Code: net.weili.spring.ioc.beandefinition
Spring's IOC - Bean Definition
Use external properties files
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>jdbc.properties</value> </list> </property></bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"><value>${jdbc.driverClassName}</value></property> <property name="url"><value>${jdbc.url}</value></property> <property name="username"><value>${jdbc.username}</value></property> <property name="password"><value>${jdbc.password}</value></property></bean>
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 7/17
Consolidate application's configuration files if you want
Bean Factory
The core of core
Does the required IOC work
Spring offers: XmlBeanFactory and ListableBeanFactoryImpl
Bean Factory - How Does It Work?
Let us see what has happened behind the scene
Loading XML bean definitions from class path resource [whyioc.xml]Loading bean definitions
Creating shared instance of singleton bean 'd_id'Creating instance of bean 'd_id' with merged definition
Creating instance of bean 'a_id' with merged definitionFound property 'b' of type Found property 'c' of typeResolving reference from property 'b' in bean 'a_id' to bean 'b_id'
Creating instance of bean 'b_id'Found property 'd' of typeResolving reference from property 'd' in bean 'b_id' to bean 'd_id'Returning cached instance of singleton bean 'd_id'Invoked write method [public void B.setD(D)]
Resolving reference from property 'c' in bean 'a_id' to bean 'c_id'Creating instance of bean 'c_id' with merged definitionFound property 'd' of type Resolving reference from property 'd' in bean 'c_id' to bean 'd_id'Returning cached instance of singleton bean 'd_id'
Invoked write method [public void C.setD(D)]Invoked write method [public void A.setB(B)]Invoked write method [public void A.setC(C)]
Bean's Life Cycle
Bean is created
Autowiring executes
Dependency check performed
Set bean properties
setBeanFactory() called
afterPropertiesSet() called
init-method invoked
Bean is ready to be used
destroy() called
destroy-method invoked (when shutting down or reloading application?)
Source: Spring Live
Code: net.weili.spring.ioc.beanlifecycle
Spring's IOC - ApplicationContext
Extends Bean Factory
Adds more features:
Message lookup - supporting for i18n
Access to resource
Event publication/notification mechanism
Allow loading of multiple contexts
Spring's IOC - ApplicationContext
Three implementations out of box
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 8/17
FileSystemXmlApplicationContext
ClassPathXmlApplicationContext
XmlWebApplicationContext
Spring's IOC - How to Use It?
Bean definitions are usually loaded by startup code in main method or init method or from a servlet
listener
InputStream is = new FileInputStream("beans_definition.xml");XmlBeanFactory factory = new XmlBeanFactory(is);
ClassPathResource res = new ClassPathResource("beans_definition.xml");XmlBeanFactory factory = new XmlBeanFactory(res);
String[] configFiles = new String[] {"beans_definition.xml"};BeanFactory factory = new ClassPathXmlApplicationContext(configFiles);
Spring's IOC - Other Advanced Features
Auto wiring
BeanPropertyEditor
Dependency checking
Others...
Break 2: Software Development Good Ideas
All killer, no filler
Release early, release often
Minor releases are still major releases
We are not our users
Under promise, over deliver
Good enough can be good enough
Development never stops
Source: http://www.rogueamoeba.com/utm/posts/
Spring's Support for JDBC and OR Mapping
Something Spring shines
Offers a good JDBC wrapper
Integrates well with existing OR mapping tools
Spring + Hibernate = Dream Team (= EJB3?)
Spring's Support for JDBC and OR Mapping
Case study: a trivial task
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 9/17
JDBC Demo - Raw JDBC API
Fine but here is the pain:
Verbose error handling to create and release resources (connections...)
Uninformative SQLException
Code: net.weili.posts.jdbc
Spring's JDBC Support
Provide APIs that move tedious and error-prone error handling from application code
Thus, free you from writing "try", "catch" and "finally" blocks - focus what you need to do
Takes away the vendor-specific exception handling error code by providing a meaningful exception hierarchy
Data access exceptions hierarchy is based on unchecked exception since they are usually not recoverable
Overall you write much less code and your code is more maintainable and testable
Spring's JDBC Abstraction 1 - JDBC Template
Uses callbacks to move control and error handling, etc from application code
Spring uses the similar callback approach for managing other resources
Spring classes that perform this callbacks are called templates
Spring JDBC templates support different scenarios including batch updates
JDBC Demo - Spring JDBC Template
Demo - Spring JDBC Template
Code: net.weili.posts.spring.jdbc1
Spring's JDBC Abstraction 2 - Spring JDBC SqlQuery/SqlUpdate Objects
Built on the core JDBC callback functionality
Inspired by JDO API
Model database operations such as query, update as java object
Proxy stored procedure as java class
JDBC demo - Spring JDBC SqlQuery/SqlUpdate Objects
Demo - Spring JDBC SqlQuery/SqlUpdate
Code: net.weili.posts.spring.jdbc2
JDBC and Spring JDBC Wrapper Comparison
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 10/17
Raw JDBC Spring JDBC Wrapper
Connection Need to explicitly open and close connections Framework manages connections
Exception Must catch SQLException and interpret vendor-specific error codeFramework translate exceptions to a common hierarchy based
on configurable translation mappings
Testing Hard to do unit test if code uses JNDI lookup for connection poolCan be tested standalone since a DataSource is easily
configurable for a variety of environments
TransactionProgrammatic transaction management possible but makes code
less reusable. CMT is available for EJBs
Both programmatic and declarative transaction management
possible.
Source: Thomas Risberg's Presentation on Spring's DAO and JDBC support
What Does Spring JDBC Wrapper Do for You?
Task Spring JDBC Wrapper Developer
Connection Management X
SQL X
Statement Management X
ResultSet Management X
Task Spring JDBC Wrapper Developer
Row Data Retrieval X
Parameter Declaration X
Parameter Setting X
Transaction Management X
Source: Thomas Risberg's Presentation on Spring's DAO and JDBC support
Spring's OR Mapping Support
Remember: Spring promises not to reinvent the wheel?
There is no OR mapping API provided by Spring
Spring supports and integrates well with existing tools in the arena
Hibernate Demo - without Spring
Demo - Hibernate without Spring
Code: net.weili.posts.hibernate
Spring's OR Mapping Support - Hibernate
Spring's integration with Hibernate offers:
Session management: efficient, easy and safe handling of Hibernate session
Resource management: Spring Context handles configuration
Transaction management
Exception wrapping
Ease of testing: Spring IOC allows swap the implementation and location of Hibernate session factories, etc.
Source: Introducing the Spring Framework
Hibernate Demo - with Spring
Demo - Hibernate with Spring
Code: net.weili.posts.spring.hibernate
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 11/17
iBatis Demo - without Spring
Demo - iBatis without Spring
Code: net.weili.posts.ibatis
Spring's OR Mapping Support - iBatis
Spring's integration with iBatis offers:
Basically the similar benefits as mentioned in the Hibernate section
iBatis Demo - with Spring
Demo - iBatis with Spring
Code: net.weili.posts.spring.ibatis
Spring's OR Mapping Support - JDO
It is there
Spring's OR Mapping Support - OJB
It is there
Break 3: The Joel Test - 12 Steps to Better Code
Do you use source control?
Can you make a build in one step?
Do you make daily builds?
Do you have a bug database?
Do you fix bugs before writing new code?
Do you have an up-to-date schedule?
Do you have a spec?
Do programmers have quiet working conditions?
Do you use the best tools money can buy?
Do you have testers?
Do new candidates write code during their interview?
Do you do hallway usability testing?
Source: http://www.joelonsoftware.com/articles/fog0000000043.html
Spring's MVC Framework
Powerful and solid MVC implementation
Flexible and configurable: built on interface
Clean separation between controllers, beans (models), and views
View agnostic - you can use JSP, Velocity, XSLT and others
Can be configured via Spring IOC and thus makes it easy to test
Source: Introducing the Spring Framework
Spring's MVC Framework
Demo - an example modified from this paper:
Simplify Your Web App Development Using the Spring MVC Framework
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 12/17
Spring's Other Gems
Scheduling
Velocity
Others...
Nice small utilities
Spring's Other Gems
Demo - Spring's Email and Velocity Support
Code: net.weili.spring.gems
Be Nice - Let's Work With Others
It is easy to use Spring with other existing frameworks
IOC
Code to interface
Example: Integration with Struts
web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/dataAccessContext-local.xml /WEB-INF/applicationContext.xml </param-value></context-param>
...
<!-- - Loads the root application context of this web app at startup, - by default from "/WEB-INF/applicationContext.xml". - Note that it is preferable to use ContextLoaderListener in a servlet container - that follows the Servlet 2.4 initialization order (most Servlet 2.3 containers do). - - Use WebApplicationContextUtils.getWebApplicationContext(servletContext) - to access it anywhere in the web application, outside of the framework. - - The root context is the parent of all servlet-specific contexts. - This means that its beans are automatically available in these child contexts, - both for getBean(name) calls and (external) bean references.--><servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet>
Source: Spring JPetStore
Example: Integration with Struts
dataAccessContext-local.xml
<!-- ========================= DAO DEFINITIONS: IBATIS IMPLEMENTATIONS ========================= -->
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 13/17
<bean id="accountDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao"> <property name="dataSource"><ref local="dataSource"/></property> <property name="sqlMap"><ref local="sqlMap"/></property></bean>
<bean id="categoryDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapCategoryDao"> <property name="dataSource"><ref local="dataSource"/></property> <property name="sqlMap"><ref local="sqlMap"/></property></bean>
Source: Spring JPetStore
Example: Integration with Struts
applicationContext.xml
<bean id="petStore" parent="baseTransactionProxy"> <property name="target"> <bean class="org.springframework.samples.jpetstore.domain.logic.PetStoreImpl"> <property name="accountDao"><ref bean="accountDao"/></property> <property name="categoryDao"><ref bean="categoryDao"/></property> <property name="productDao"><ref bean="productDao"/></property> <property name="itemDao"><ref bean="itemDao"/></property> <property name="orderDao"><ref bean="orderDao"/></property> </bean> </property></bean>
Source: Spring JPetStore
Example: Integration with Struts
PetStoreImpl.java
public class PetStoreImpl implements PetStoreFacade, OrderService {
private AccountDao accountDao;
...
public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; }
...
public Account getAccount(String username) { return this.accountDao.getAccount(username); }
...
public List getUsernameList() { return this.accountDao.getUsernameList(); }
...}
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 14/17
Source: Spring JPetStore
Example: Integration with Struts
BaseAction.java
public abstract class BaseAction extends Action {
private PetStoreFacade petStore;
public void setServlet(ActionServlet actionServlet) { super.setServlet(actionServlet); ServletContext servletContext = actionServlet.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); this.petStore = (PetStoreFacade) wac.getBean("petStore"); }
protected PetStoreFacade getPetStore() { return petStore; }
}
Source: Spring JPetStore
Example: Integration with Struts
EditAccountAction.java
public class EditAccountAction extends SecureBaseAction {
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ... getPetStore().updateAccount(account); acctForm.setAccount(getPetStore().getAccount(account.getUsername())); ... }
}
Source: Spring JPetStore
Easy Unit Test
Dependency/coupling is moved from code to configuration file
Code to interface - make swap of implementation easy and mock test easy
Topics Not Covered
Spring AOP
Transaction Management
Remoting
Spring Roadmap - What Is Next?
JMS support
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 15/17
Support for dynamic reconfiguration of bean factories
The ability to expose web services
IDE and other tool support
Source: Introduction to Spring Framework
Resources
Tools
Official Examples
Books
Online Documentation
Presentations
Resources - Tools
Eclipse Spring IDE - ease working bean factory configuration files
Spring Console - visually edit Spring configuration files
SpringViz - Configuration Visualization for Spring. See a sample here
BeanDoc - tool for getting a better view of a Spring application context.
Resources - Examples
Spring JPetStore: Struts or Spring MVC + Spring iBatis
Petlinks: Spring MVC + Spring Hibernate or OJB or JDBC
Countries: Spring MVC + Spring JDBC
Demo? - Depending on time and interests
Resources - Books
Expert One-on-One J2EE Design and Development by Rod Johnson
Expert One-on-One J2EE Development without EJB by Rod Johnson and Juergen
Professional Java Development with the Spring Framework by Rod Johnson, Juergen Hoeller, Alef Arendsen, Thomas Risberg, Dmitriy Kopylenko
Better, Faster, Lighter Java by Bruce A. Tate, Justin Gehtland
Spring in Action by Craig Walls and Ryan Breidenbach
Spring Live by Matt Raible
Pro Spring by Rob Harrop, Jan Machacek
Resources - Online White Papers and Documentation
See a relatively complete list of white papers here
The following should be singled out:
Introducing the Spring Framework - by Rod Johnson
Inversion of Control Containers - by Mike Spille
Official Spring Reference Documentation - by Spring Team
Resources - Presentations
See a incomplete list here
Caution
Reading, playing and trying Spring framework can be addictive!
Questions
Questions?
Wrap Up: Matz's 10 Tips to Be a Good Programmer
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 16/17
Learn more than one programming language, preferably one with a different style
Read good books, for example, "Pragmatic Programmers", "Refactoring"
Read the source code
Don't focus too much on tools. Tools change; algorithms and basic fundamentals don't
Don't focus too much on machines.
Be lazy. Machines should serve the human. Often, programmers serve machines unconsciously. Let machines serve you. Do everything you can to make yourself lazy.
Test early, test often. Write test suites before you code, if possible.
Be nice to others. Consider the interface first; man to man, man to machine, and machine to machine. Again, remember, human factor is important.
Be creative.
Enjoy programming and life. I believe that is one of the purposes of life.
Thank You
Thank You and Happy Thanksgiving!
3/5/2011 An Introduction to the Spring Framewo…
C:/home/M/…/spring_intro.html 17/17