1 November 21st 2009 Shaun Abram An Introduction to Spring.

Slides:



Advertisements
Similar presentations
Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
Advertisements

Apache Struts Technology
Spring, Hibernate and Web Services 13 th September 2014.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
Struts Basics SSE USTC Qing Ding. Agenda What is and Why Struts? Struts architecture – Controller: Focus of this presentation – Model – View Struts tag.
© 2005, Cornell University. Rapid Application Development using the Kuali Architecture (Struts, Spring and OJB) A Case Study Bryan Hutchinson
Application Architectures Vijayan Sugumaran Department of DIS Oakland University.
1 Java Server Pages Can web pages be created specially for each user? What part does Java play?
Apache Struts Technology A MVC Framework for Java Web Applications.
Session-01. Layers Struts 2 Framework The struts 2 framework is used to develop MVC-based web application. Struts 1.0 was released in June The.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
The Spring Framework: A brief introduction to Inversion of Control James Brundege
Intro to Spring CJUG - January What is Spring? “The Spring framework provides central transaction control of various objects.” This means that any.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Dependency Injection and Model-View-Controller. Overview Inversion of Control Model-View-Controller.
Java Frameworks Indy Java Users Group January 29, 2003.
Programming Languages and Paradigms Object-Oriented Programming.
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Introduction to the Spring Framework By: Nigusse A. Duguma Kansas State university Department of Computer Science Nov 20, 2007.
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
The Spring Framework Training Get to know Spring Framework Rohit Prabhakar
Copyright © 2012 Accenture All Rights Reserved.Copyright © 2012 Accenture All Rights Reserved. Accenture, its logo, and High Performance Delivered are.
JDeveloper 10g and JavaServer Faces: High-Performance UIs on the Web Avrom Roy-Faderman Senior Programmer May, 2006.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An.
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
Text 16 de mayo de 2009 Spring Framework Part I. Dependency Injection Buenos Aires, May 2009.
JSF Introduction Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without written permission.
Opus College - overview. OpusCollege - background First project: ICT Capacity Building Mozambican Higher Education Institutions Partners: RUG Groningen,
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
Case Study + MVC Lec Error Pages By means of the page directive, a JSP can be given the responsibility of an Error page An Error JSP will be called.
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework,
Introduction to Web Dimitar Nenchev Ivan Nakov
Java Web Development with NetBeans IDE -- Kai Qian Chapter 5 JavaServer Faces (JSF) Technology.
A Presentation By V AIBHAV S AHARAN Web-enHanced Information Management COMS E6125.
JSF Framework Java Server Faces Presented by Songkran Totiya (6/10/2014)
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Apache Struts. J2EE Web Application using MVC design pattern Why MVC? Separate components = easier maintenance – Model component holds object data – View.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Spring and DWR Frameworks for Rich Web Enterprise Application Thomas Wiradikusuma Presentation to the 20 th.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
1 Spring Framework April, 2012 Lam Ho Lam To. © 2010 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 2 1.Spring Overview 2.Framework.
Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
1 Copyright © 2004, Oracle. All rights reserved. Oracle Application Development Framework.
Component Patterns – Architecture and Applications with EJB copyright © 2001, MATHEMA AG Component Patterns Architecture and Applications with EJB Markus.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
2006/2007 Licence Apache 2.0 Castle.Igloo. Castle Igloo Basics Pre-require Concept Scopes PageFlow Configuration Controller View Exemple Castle.Igloo.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Overview of the Spring Framework Introducing.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Mach-II Primer Ben Edwards An Introduction to Mach-II: An event-based, implicit invocation web-application framework.
APACHE STRUTS ASHISH SINGH TOMAR ast2124. OUTLINE Introduction The Model-View-Controller Design Pattern Struts’ implementation of the MVC Pattern Additional.
Apache Struts Technology A MVC Framework for Java Web Applications.
CS320 Web and Internet Programming Web Application and MVC Chengyu Sun California State University, Los Angeles.
Introduction to Inversion Of Control (IOC). IOC Definition (based on Wikipedia)  Consider the way in which an object obtains references to its dependencies.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Inversion of Control Chengyu Sun California State University, Los Angeles.
J2EE Lecture 6: Spring – IoC and Dependency Injection
CS520 Web Programming Spring – Inversion of Control
J2EE Lecture 7: Spring – Spring MVC
Unit 6-Chapter 2 Struts.
Intro to Spring CJUG - January 2013.
The Model Layer What is Model?
Tuesday Brown Bag Inversion of Control with Howard Abrams
Developing and testing enterprise Java applications
Presentation transcript:

1 November 21st 2009 Shaun Abram An Introduction to Spring

2 Agenda 1.Introduction & Background 2.IoC and Dependency Injection 3.Code Example 4.Spring details 5.Spring MVC

3 Agenda 1.Introduction & Background 2.IoC and Dependency Injection 3.Code Example 4.Spring details 5.Spring MVC

4 Introductions Shaun Abram Sun Certified Enterprise Architect 10+ years of Java/JEE development Tech Lead at Wells Fargo You?

5 Spring – Why you should care Rapidly becoming the de facto standard in enterprise Java Hugely popular: -50% of Java shops use Spring -73% use or planning to use Spring -9 out of the top 10 global banks use Spring extensively -Used by LinkedIn, Orbitz, Wired, Sky, Accenture, Edmunds.com -Open source projects: Grails Spring makes JEE development easier Sources: Evans Data Survey Introduction to Spring Framework 2.5 by Rod Johnson

6 A Brief History… …of JavaBeans, Enterprise JavaBeans and Spring : Sun released JavaBeans spec : Sun published EJB 1.0 spec : “Expert One-on-One J2EE Design and Development” published : Spring open source project created : Spring 2.5 latest production release Spring 3.0 coming soon…

7 Agenda 1.Introduction & Background 2.IoC and Dependency Injection 3.Code Example 4.Spring details 5.Spring MVC

8 Inversion of Control No longer create/find objects IoC Container calls your software Passing it everything it need aka ‘The Hollywood Principle’ Dependency Injection IoC and DI

9 Dependency Injection at its simplest Hard coded dependency class Test { Object dependency; public Test() { dependency = new Object(); } Dependency Injection enabled //Constructor Injection class Test { Object dependency; public Test(Object dep) { this.dependency = dep; } } //Setter Injection class Test { Object dependency; public setDependency(Object dep) { this.dependency = dep; } }

10 Agenda 1.Introduction & Background 2.IoC and Dependency Injection 3.Code Example 4.Spring details 5.Spring MVC

11 Example: Account Service Typical Web Architecture: JSP Controller Service DAO (Data Access Object) Database Code to interfaces!

public interface AccountService { int getAvailableAmount(int accountNum); } public class AccountServiceImpl implements AccountService { AccountDAO accountDAO = null; public AccountServiceImpl() { accountDAO = new SimpleAccountDAO(); } public int getAvailableAmount (int accountNum) { Account account = accountDAO.getAccount(accountNum); int availableAmount = account.getBalance() if (availableAmount < 0) availableAmount = 0; return availableAmount; } 12 Example: AccountService

public interface AccountDAO { Account getAccount(int accountNum); } public class SimpleAccountDAO implements AccountDAO { public Account getAccount (int accountNum) { Account account = null; //logic to retrieve account using accountNum … return account; } 13 Example: AccountDAO

14 Example: Unit testing issues Example JUnit Test Case public class AccountServiceTest extends TestCase { public void testGetAvailableAmount () { AccountService as = new AccountServiceImpl(); int accNum = 1; int availableAmount = as.getAvailableAmount(accNum); assertTrue(availableAmount>=0); } } public class AccountServiceImpl implements AccountService { AccountDAO accountDAO = null; public AccountServiceImpl() { accountDAO = new SimpleAccountDAO (); } public int getAvailableAmount (int accNum) { Account acc = accountDAO.getAccount(accNum); int availableAmount = acc.getBalance(); if (availableAmount < 0) availableAmount = 0; return availableAmount; } } Issues: AccountServiceTest indirectly tests SimpleAccountDAO We are not testing all possibilities Underlying problem is Coupling…

The AccountServiceImpl is coupled to SimpleAccountDAO Although we are coding to an interface: AccountDAO accountDAO = null; We still directly instantiate a specific implementation: accountDAO = new SimpleAccountDAO (); Solution: Instead of AccountService creating an AccountDAO for itself, Set it up for Dependency Injection Then, could use MOCK implementation of AccountDAO 15 Example: Dependency injection enable

16 Example: Dependency injection enable Hard coded dependency public class AccountServiceImpl { AccountDAO accountDAO = null; public AccountServiceImpl() { accountDAO = new SimpleAccountDAO (); } public int getAvailableAmount (int accNum) { … return availableAmount; } Dependency Injection public class AccountServiceImpl { AccountDAO accountDAO = null; public AccountServiceImpl() {} public void setAccountDAO(AccountDAO accDAO) { this.accountDAO = accDAO; } public int getAvailableAmount (int accNum) { … return availableAmount; }

17 Example: Updated Unit Test public void testGetAvailableAmount () { AccountService accountService = new AccountServiceImpl(); AccountDAO accountDAOMock = mock(AccountDAO.class); accountService.setAccountDAO(accountDAOMock); int accNum = 1; //set Mock behavior here! //execute test Integer availableAmount = accountService.getAvailableAmount(accNum); //verify results assertTrue(availableAmount>=0); } New unit test uses Mock objects Removes dependency on any specific AccountDAO impl – test focuses on AccountServiceImpl.getAvailableAmount only We can control what the Mock return allowing us to test all scenarios/branches on AccountServiceImpl.getAvailableAmount NB AccountService code being used without an IoC container

Inversion of Control (IoC): Instead of your code calling a framework, the framework calls your code The Hollywood principle: Don't call us, we'll call you Dependency Injection (DI): A flavor of IoC The framework injects dependent objects With DI, classes are more loosely coupled no longer need to create/locate objects are easier to test still function perfectly well without an IoC framework! 18 IoC/DI summary

19 Agenda 1.Introduction & Background 2.IoC and Dependency Injection 3.Code Example 4.Spring details 5.Spring MVC

20 Spring Details: Beans Bean = Spring managed object Created and managed by the Spring container Treated in a standard way creation initialization configuration Life cycle management Spring beans don’t have to be JavaBeans

21 Spring Details - Container A container will create objects wire them together configure them manage bean lifecycle 2 distinct types: BeanFactory ApplicationContext

22 Spring Config File A Spring IoC container manages one or more beans. Spring config file contains the bean definitions The element is the most basic configuration unit in Spring. e.g. When the Spring container reads this, it will instantiate the accountService bean using the default constructor. Basically, the result is equivalent to accountService = new com.codecamp.AccountServiceImpl();

23 Example: Dependency Injection via Spring 1.Create a Spring config file tells Spring what beans to create and what dependencies to inject 2.‘Start’ the Spring container 3.Retrieve first bean

24 Example: Dependency injection via Spring

25 Spring DI example public class SpringExample { public static void main(String[] args) { AccountService accountService; int accountNum = new Integer(args[0]); //Spring Bootstrap code FileSystemResource appContext = new FileSystemResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(appContext); accountService = (AccountService)factory.getBean("accountService"); int availableBalance = accountService.getAvailableBalance(accountNum); System.out.println("Your available balance is: " + availableBalance); } }

26 Spring Containers in more detail 2 distinct types: BeanFactory ApplicationContext

27 Spring Details - BeanFactory The simplest of the containers Provide basic support for DI An implementation of the Factory design pattern Creates objects (beans) Configures objects Wires objects together Manages bean lifecycle e.g. org.springframework.beans.factory.xml.XmlBeanFactory

28 Spring Details - ApplicationContext Build on the notion of a bean factory public interface ApplicationContext extends ListableBeanFactory Provide application framework service, such as -resolve textual messages from a properties file  including support for Internationalization -event-propagation  publish events to interested event listeners -resource-loading e.g. ClassPathXmlApplicationContext FileSystemXmlApplicationContext XmlWebApplicationContext

29 Spring Details - Containers ApplicationContext vs BeanFactory? If in doubt, use ApplicationContext

30 Bean scopes So far, we have been using bean definitions like this… This essentially does the equivalent of greetingDAO = new package.GreetingDao(); But Spring also gives us the ability to control how many instances of a bean are created. This is referred to as the ‘scope’ of the bean.

31 Singleton scope is the same as

32 Prototype Scope

33 Other Scopes There are 3 other bean scopes in Spring: Request Session Global session These apply to web aware Spring contexts e.g. Spring MVC, portlets

34 Bean Lifecycle and extension points Lifecycle of a typical Java object (POJO) is very simple: Create object: Using ‘new’ (or deserialize) Use object Once dereferenced – eligible for GC GC: Object removed from memory Lifecycle of a Spring bean can be much more elaborate: Instantiate Populate properties Custom initialization for beans Custom destruction for beans

35 Custom Initialization Custom initialization methods If a bean has a default or custom init method declared, the specified initialization method will be called. InitializingBean interface If the bean implements InitializingBean, it’s afterPropertiesSet() method will be called. Discouraged as couples the code to Spring. Instead, use an initialization Not Spring specific – this a JSR-250lifecycle annotation. Used to mark initialization methods that are executed after dependency injection is done but before the object is released for use. Best practice!

36 Custom Destruction Custom destroy methods Any default or custom destroy method declared will be called. e.g. DisposableBean interface If the bean implements DisposableBean, it’s destroy() method will be called. Discouraged as couples the code to Spring. Instead, use an destroy PreDestroy Not Spring specific – this a JSR-250 lifecycle annotation. Used on methods as a callback notification to signal that the instance is in the process of being removed by the container. The method annotated with PreDestroy is typically used to release resources that it has been holding. Best practice

Software is Easier to write - Because you no longer need to worry about object creation and management Easier to test - Because Spring can easily inject ‘Mock’ objects for testing Loosely coupled - Objects no longer need to know how to create other objects Independent of Spring - Use of other frameworks can introduce dependencies - Spring is a non-invasive technology 37 Benefits of Spring IoC Container

38 Agenda 1.Introduction & Background 2.IoC and Dependency Injection 3.Code Example 4.Spring details 5.Spring MVC

39 Spring MVC A web framework providing full MVC implementation MVC = Model–View–Controller -An architectural pattern that separates business, navigation and presentation logic - View = the user interface elements -Model = data -Controller = the business logic Spring MVC is Model 2 i.e. it has a dedicated Front Controller (DispatcherServlet)… Alternative to Struts Follows Spring paradigms, including IoC/DI

40 Spring MVC Why use Spring MVC? Designed to be an improvement to Struts Useful if you are already using Spring Getting up to speed with Spring MVC may be easier than other web frameworks… Other Spring beans can be injected into the web controllers Very testable e.g. test controllers by using mock services All parts of the web application can be tested in isolation Transparently binds request parameters to your business objects also provides validation and error handling Provides a useful JSP Tag Library to make data binding with JSPs even easier

41 Spring MVC

42 Example Spring MVC public class HelloWorldController public ModelAndView helloWorld() { ModelAndView mac = new ModelAndView(); mav.setViewName("helloWorld"); mav.addObject("message", "Hello World!"); return mav; } Spring ‘startup’ code not required because 1) a Listener Servlet called Context Loader will read your Spring config file and load all beans into the container 2) The DispatcherServlet (the Front Controller) passes all requests to the appropriate Controller – no need to manually get access to your first bean (or two)..

43 Spring Web Flow There are 2 kinds of common interaction approaches in web apps 1)Free flow navigation The user controls flow 2)Conversation flow User has come control, but app controls bigger picture e.g. ordering a product on a site login These sequences are called a conversation flow Free flow: Handled by Spring MVC Conversation flow: Handled by Spring Web Flow (a special implementation of a MVC controller)

44 Spring Web Flow Conversation flow can be handled just using Spring MVC e.g. putting links every JSP or Controller But distributing the flow logic throughout the app means: No central place that specifies the overall flow Difficult to get an understanding of the overall flow Difficult to change the flow – requires editing multiple files of multiple types Difficult to reuse common flows without recoding

45 Spring Web Flow Captures logical page flows as self-contained modules Modules are reusable in different situations xml files SWF loosens the coupling between an app's code and its page flow by enabling you to define the flow in a separate self contained flow definition

46 Spring Summary All OO software has dependencies on objects Creating or locating objects can be difficult Managing dependencies (what software needs what objects) also difficult Spring provides Dependency Injection (creates objects, injects them where required) ‏ Result is simplified, testable software There are around 20 Spring modules, including Spring WVC and Web Flow Spring modules can have widely different purposes All rely on the core IoC and DI functionality

47 Recommended Reading Spring in Action - Craig Walls The Spring Framework Reference Documentation – springsource.com Expert one-on-one J2EE Design and Development – Rod Johnson Presentation

48 Questions?

49 Follow up