An introduction to the Spring Framework


Published on

This is an introduction to the Spring framework

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

An introduction to the Spring Framework

  1. 1. 3/5/2011 An Introduction to the Spring Framewo…An Introduction to the Spring Framework - Wei Li, 11/17/2004An Introduction to Spring FrameworkWei LiSpring Framework Background An open source project founded by Rod Johnson in February 2003 Based on the infrastructure code for Rods 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" solutionOverview 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 FrameworkOverview 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 testabilityWhat Does Spring Framework OfferSource: Springs Official Reference DocumentationBuild a Full Fledged Application Using SpringC:/home/M/…/spring_intro.html 1/17
  2. 2. 3/5/2011 An Introduction to the Spring Framewo…Source: Springs Official Reference DocumentationUsing Spring with OthersSource: Springs Official Reference DocumentationOverview of Inversion of Control Source: is IOC - What Do People Say? Hollywood Principle: Do not call me, I call you Martin Fowler: Dependency Injection Unknown: Give without askingC:/home/M/…/spring_intro.html 2/17
  3. 3. 3/5/2011 An Introduction to the Spring Framewo… Yours truly: Push not pullWhat 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 configurationSource: 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 DCode: net.weili.spring.ioc.whyiocWhat 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 elseC:/home/M/…/spring_intro.html 3/17
  4. 4. 3/5/2011 An Introduction to the Spring Framewo…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 youC:/home/M/…/spring_intro.html 4/17
  5. 5. 3/5/2011 An Introduction to the Spring Framewo… Makes your application more testable No more reading and processing configuration file No more creating and hooking them together No more lookup...Reference: HiveMindSo 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 testableTypes of Inversion of ControlSource: Springs Official Reference DocumentationAvailable 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 ActionC:/home/M/…/spring_intro.html 5/17
  6. 6. 3/5/2011 An Introduction to the Spring Framewo…Source: 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: unknownSprings IOC The core of the whole Spring framework Foundation of other Spring frameworks 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 filesSprings 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 solutionSprings IOC - Bean Definition Define beans Define the relations among beans Define the rules of how beans work XML or properties file format IOCs BeanFactory will parse it and make objects ready to be usedSprings IOC - Bean DefinitionSpring bean definition - simple but consistentC:/home/M/…/spring_intro.html 6/17
  7. 7. 3/5/2011 An Introduction to the Spring Framewo…<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ""><beans> <bean id="..." class="..."> ... </bean> <bean id="..." class="..."> ... </bean> ...</beans>Springs IOC - Bean DefinitionSpring bean definition contains: id/name (required) class (required) singleton or prototype (default: singleton) properties constructor arguments Initialization method Destruction method Others...Springs IOC - Bean DefinitionBean 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 injectionDemoCode: net.weili.spring.ioc.beandefinitionSprings IOC - Bean DefinitionUse external properties files<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value></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>C:/home/M/…/spring_intro.html 7/17
  8. 8. 3/5/2011 An Introduction to the Spring Framewo…Consolidate applications configuration files if you wantBean Factory The core of core Does the required IOC work Spring offers: XmlBeanFactory and ListableBeanFactoryImplBean Factory - How Does It Work?Let us see what has happened behind the sceneLoading XML bean definitions from class path resource [whyioc.xml]Loading bean definitionsCreating shared instance of singleton bean d_idCreating instance of bean d_id with merged definitionCreating instance of bean a_id with merged definitionFound property b of typeFound property c of typeResolving reference from property b in bean a_id to bean b_idCreating instance of bean b_idFound property d of typeResolving reference from property d in bean b_id to bean d_idReturning cached instance of singleton bean d_idInvoked write method [public void B.setD(D)]Resolving reference from property c in bean a_id to bean c_idCreating instance of bean c_id with merged definitionFound property d of typeResolving reference from property d in bean c_id to bean d_idReturning cached instance of singleton bean d_idInvoked write method [public void C.setD(D)]Invoked write method [public void A.setB(B)]Invoked write method [public void A.setC(C)]Beans 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 LiveCode: net.weili.spring.ioc.beanlifecycleSprings IOC - ApplicationContext Extends Bean Factory Adds more features: Message lookup - supporting for i18n Access to resource Event publication/notification mechanism Allow loading of multiple contextsSprings IOC - ApplicationContextThree implementations out of boxC:/home/M/…/spring_intro.html 8/17
  9. 9. 3/5/2011 An Introduction to the Spring Framewo… FileSystemXmlApplicationContext ClassPathXmlApplicationContext XmlWebApplicationContextSprings IOC - How to Use It?Bean definitions are usually loaded by startup code in main method or init method or from a servletlistenerInputStream 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);Springs 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: 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?)Springs Support for JDBC and OR MappingCase study: a trivial taskC:/home/M/…/spring_intro.html 9/17
  10. 10. 3/5/2011 An Introduction to the Spring Framewo…JDBC Demo - Raw JDBC APIFine but here is the pain: Verbose error handling to create and release resources (connections...) Uninformative SQLExceptionCode: net.weili.posts.jdbcSprings 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 testableSprings 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 updatesJDBC Demo - Spring JDBC TemplateDemo - Spring JDBC TemplateCode: net.weili.posts.spring.jdbc1Springs 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 classJDBC demo - Spring JDBC SqlQuery/SqlUpdate ObjectsDemo - Spring JDBC SqlQuery/SqlUpdateCode: net.weili.posts.spring.jdbc2JDBC and Spring JDBC Wrapper ComparisonC:/home/M/…/spring_intro.html 10/17
  11. 11. 3/5/2011 An Introduction to the Spring Framewo… Raw JDBC Spring JDBC Wrapper Connection Need to explicitly open and close connections Framework manages connections Framework translate exceptions to a common hierarchy based Exception Must catch SQLException and interpret vendor-specific error code on configurable translation mappings Can be tested standalone since a DataSource is easily Testing Hard to do unit test if code uses JNDI lookup for connection pool configurable for a variety of environments Programmatic transaction management possible but makes code Both programmatic and declarative transaction management Transaction less reusable. CMT is available for EJBs possible.Source: Thomas Risbergs Presentation on Springs DAO and JDBC supportWhat Does Spring JDBC Wrapper Do for You? Task Spring JDBC Wrapper Developer Task Spring JDBC Wrapper Developer Connection Management X Row Data Retrieval X SQL X Parameter Declaration X Statement Management X Parameter Setting X ResultSet Management X Transaction Management XSource: Thomas Risbergs Presentation on Springs DAO and JDBC supportSprings 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 arenaHibernate Demo - without SpringDemo - Hibernate without SpringCode: net.weili.posts.hibernateSprings OR Mapping Support - HibernateSprings 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 FrameworkHibernate Demo - with SpringDemo - Hibernate with SpringCode: net.weili.posts.spring.hibernateC:/home/M/…/spring_intro.html 11/17
  12. 12. 3/5/2011 An Introduction to the Spring Framewo…iBatis Demo - without SpringDemo - iBatis without SpringCode: net.weili.posts.ibatisSprings OR Mapping Support - iBatisSprings integration with iBatis offers: Basically the similar benefits as mentioned in the Hibernate sectioniBatis Demo - with SpringDemo - iBatis with SpringCode: net.weili.posts.spring.ibatisSprings OR Mapping Support - JDOIt is thereSprings OR Mapping Support - OJBIt is thereBreak 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: 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 testSource: Introducing the Spring FrameworkSprings MVC FrameworkDemo - an example modified from this paper:Simplify Your Web App Development Using the Spring MVC FrameworkC:/home/M/…/spring_intro.html 12/17
  13. 13. 3/5/2011 An Introduction to the Spring Framewo…Springs Other Gems Email Scheduling Velocity Others... Nice small utilitiesSprings Other GemsDemo - Springs Email and Velocity SupportCode: net.weili.spring.gemsBe Nice - Lets Work With OthersIt is easy to use Spring with other existing frameworks IOC Code to interfaceExample: Integration with Strutsweb.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 JPetStoreExample: Integration with StrutsdataAccessContext-local.xml<!-- ========================= DAO DEFINITIONS: IBATIS IMPLEMENTATIONS =========================C:/home/M/…/spring_intro.html 13/17
  14. 14. 3/5/2011 An Introduction to the Spring Framewo…<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 JPetStoreExample: Integration with StrutsapplicationContext.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 JPetStoreExample: Integration with StrutsPetStoreImpl.javapublic 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(); } ...}C:/home/M/…/spring_intro.html 14/17
  15. 15. 3/5/2011 An Introduction to the Spring Framewo…Source: Spring JPetStoreExample: Integration with StrutsBaseAction.javapublic abstract class BaseAction extends Action { private PetStoreFacade petStore; public void setServlet(ActionServlet actionServlet) { super.setServlet(actionServlet); ServletContext servletContext = actionServlet.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(s this.petStore = (PetStoreFacade) wac.getBean("petStore"); } protected PetStoreFacade getPetStore() { return petStore; }}Source: Spring JPetStoreExample: Integration with StrutsEditAccountAction.javapublic 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 JPetStoreEasy Unit Test Dependency/coupling is moved from code to configuration file Code to interface - make swap of implementation easy and mock test easyTopics Not Covered Spring AOP Transaction Management RemotingSpring Roadmap - What Is Next? JMS supportC:/home/M/…/spring_intro.html 15/17
  16. 16. 3/5/2011 An Introduction to the Spring Framewo… Support for dynamic reconfiguration of bean factories The ability to expose web services IDE and other tool supportSource: Introduction to Spring FrameworkResources Tools Official Examples Books Online Documentation PresentationsResources - 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 JDBCDemo? - Depending on time and interestsResources - 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 MachacekResources - Online White Papers and DocumentationSee a relatively complete list of white papers hereThe 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 TeamResources - PresentationsSee a incomplete list hereCautionReading, playing and trying Spring framework can be addictive!QuestionsQuestions?Wrap Up: Matzs 10 Tips to Be a Good ProgrammerC:/home/M/…/spring_intro.html 16/17
  17. 17. 3/5/2011 An Introduction to the Spring Framewo… Learn more than one programming language, preferably one with a different style Read good books, for example, "Pragmatic Programmers", "Refactoring" Read the source code Dont focus too much on tools. Tools change; algorithms and basic fundamentals dont Dont 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 YouThank You and Happy Thanksgiving!C:/home/M/…/spring_intro.html 17/17