the sppgring framework: overview and...

17
© 2009 Marty Hall The Spring Framework: Overview and Setup Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/spring.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2009 Marty Hall For live Java training, please see training courses at http //co rses coreser lets com/ Ser lets JSP Str ts http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF, Ajax, GWT, Java 5, Java 6, Spring, Hibernate, JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact [email protected] for details.

Upload: others

Post on 11-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

© 2009 Marty Hall

The Spring Framework: p gOverview and Setup

Originals of Slides and Source Code for Examples:http://courses.coreservlets.com/Course-Materials/spring.html

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2009 Marty Hall

For live Java training, please see training courses at http //co rses coreser lets com/ Ser lets JSP Str tshttp://courses.coreservlets.com/. Servlets, JSP, Struts, JSF, Ajax, GWT, Java 5, Java 6, Spring, Hibernate, JPA,

and customized combinations of topics. p

Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your

organization. Contact [email protected] for details.

Page 2: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Agenda

• What is Spring?– And why use it?

• Main Spring modulesD d i j i– Dependency injection

– AOP

• Configuring apps to use Spring• Configuring apps to use Spring– And Eclipse plugin support

• Simple exampleSimple example

5

© 2009 Marty Hall

Overview of Spring

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Page 3: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

What is Spring?

• Spring is a framework with many modules– To simplify many different Java EE tasks

• Core module: dependency injectionL d fi XML fil h ifi hi h b– Lets you define an XML file that specifies which beans are created and what their properties are

• Simplifies OOP by promoting loose coupling between p y p g p gclasses. Also called “Inversion of Control” (IoC)

• Small example shown in this lecture; details in next lecture

• Second most important module: AOPSecond most important module: AOP– “Aspect Oriented Programming” refers to the ability to

add side effects to a class’ method calls without modifying the class’ source code

– Lets you separate business logic from system services7

Why Spring?

• Disenchantment with EJB– Too complicated– Objects were technology-specific: tied to EJB

Hard to test in isolation– Hard to test in isolation

• Basic Spring philosophy– Avoid tight coupling among classesAvoid tight coupling among classes

• Approaches to support this philosophy– Use POJOs (Plain Old Java Objects)( j )– Add enterprise services declaratively– Use Spring to obtain object instances and to manage their

lif l D ’t k S i d d t llifecyle. Don’t make Spring-dependent classes.• However, annotations partially violate this principle

8

Page 4: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Spring Modules

From Spring in Action, 2nd Edition by Craig Walls9

Use of Spring in Industry

– Claims to compile data from most major jobs sites• Data through 12/2008• Data through 12/2008

10

Page 5: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

© 2009 Marty Hall

Installation and Setup

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Downloading

• http://www.springsource.org/download– Choose latest released version

• 2.5.6 as of 12/2008

– Choose “Community Download”y• This is free and open source• There is also Enterprise version that comes with paid support

– Choose version with dependenciesChoose version with dependencies• Includes required and optional JAR files, documentation, and

samples– You only have to use the JAR files you want, so there is no harm in

downloading the full version

• spring-framework-2.5.6-with-dependencies.zip as of 12/08

– Alternative: download spring-blank.zip• Eclipse project with two required JAR files, blank

applicationContext.xml, and Eclipse Spring IDE nature• From coreservlets.com; see link on title page of this tutorial.

12

Page 6: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Installation

• Unzip into directory of your choiceI ill f t thi l t i i t ll– I will refer to this later as spring-install

• To add Spring capabilities to projects– Simple Java project

• Add two JAR files to project class path– spring-install/dist/spring.jar– spring-install/lib/jakarta-commons/commons-logging.jar

• Create empty bean definition file to use as a starting point• Create empty bean definition file to use as a starting point– Usually placed in top-level of class path: src/applicationContext.xml

• Simple example given in this lecture– Dynamic Web ProjectDynamic Web Project

• Add two JAR files to WEB-INF/lib– spring-install/dist/spring.jar– spring-install/lib/jakarta-commons/commons-logging.jar

• Place starting-point bean definition file in WEB-INF• Declare listener that loads the bean definition file at app startup• Simple example given in next lecture

13

Documentation

• Online docsR f d i– Reference documentation

• http://static.springframework.org/spring/docs/2.5.x/reference/– API in JavaDoc

• http://static.springframework.org/spring/docs/2.5.x/api/– Tutorials and setup guides

• http://opensource.atlassian.com/confluence/spring/dashboard.actionp p p g– Documentation for Spring Eclipse plugin

• http://springide.org/project/wiki/TOC

• Books• Books– Spring Recipes by Gary Mak (APress)

• Covers Spring 2.5S i i A i b C i W ll (M i )– Spring in Action by Craig Walls (Manning)

• Covers Spring 2.0

14

Page 7: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

IDE Support for Spring

• Spring IDE– Free, open source, Eclipse only. Used in these tutorials.

• http://springide.org/

• Skyway BuilderSkyway Builder– Commercial Eclipse plugin for Spring and Hibernate

• http://www.skywayperspectives.org/

Others for Eclipse• Others for Eclipse– Search Eclipse Plugin Central. Several new ones listed.

• http://www.eclipseplugincentral.com/

• Other IDEs– MyEclipse

• Has their own Spring support http://myeclipseide com/• Has their own Spring support. http://myeclipseide.com/

– Intellij IDEA• Has their own Spring support. http://www.jetbrains.com/idea/

15

Spring IDE: Eclipse Plugin for SpringEclipse Plugin for Spring

• IdeaO i l l i dd f l– Optional plugin adds many useful Spring-aware features to Eclipse.

– Highly recommended for Eclipse users.

• Installation– Help Software UpdatesHelp Software Updates

Available Software Add Site– Enter

http://springide org/updatesitehttp://springide.org/updatesite– Select both the springide.org site

and the automatically-created site for AspectJ supportfor AspectJ support

– Click Install16

Page 8: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Making a New Spring Project

1. Make new Java projectN P j J J P j– New Project Java Java Project

2. Add Spring IDE Eclipse support– R-click project, Spring Tools Add Spring ProjectR click project, Spring Tools Add Spring Project

Nature• For regular Java projects (not Dynamic Web Projects) you

can combine the above two steps by doing p y gNew Project Spring Spring Project.

• You can still use Spring even if you don’t have Spring IDE. Adding the project nature just makes Eclipse smarter about editing and graphically displaying certain filesabout editing and graphically displaying certain files.

3. Add spring.jar and commons-logging.jar– Details on next slide

4. Put an empty bean definition file in src– Details on upcoming slide

17

Adding JAR Files to Project

• Required JAR filesi j (f “di ” f ld )– spring.jar (from “dist” folder)

• If disk space is critical, you can choose among many smaller JAR files. But simplest to just use spring.jar.

l i j (f “lib/j k t ”)– commons-logging.jar (from “lib/jakarta-commons”)• Putting JAR files in class path

– Make a new project directory (e.g., “lib”)Make a new project directory (e.g., lib )– Copy spring-install/dist/spring.jar and

spring-install/lib/jakarta-commons/commons-logging.jar to the lib folderto the lib folder.

– R-click on project, Properties Libraries Add JARs• Then point at lib/spring.jar and lib/commons-logging.jar

For Dynamic Web Projects• For Dynamic Web Projects– Instead of above steps, copy JARs to WEB-INF/lib

18

Page 9: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Making a Bean Definition File

• Idea– XML file defines objects (beans) and gives them names.

Java code will load file and refer to objects by name.– File is most commonly loaded relative to the class path– File is most commonly loaded relative to the class path,

so is typically placed in src folder– File can have any name

• Common choices are beans.xmland applicationContext.xml

• Creating with Spring IDECreating with Spring IDE– R-click on src folder New

Other Spring S i B D fi itiSpring Bean Definition

– Choose a name and hit “Finish”19

Sample Bean Definition File

• Starting point file<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beansxsi:schemaLocation= http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Your entries will go here -->

</beans>

• Spring IDE is not required– This file can be created and edited manually

• Grab one from the samples that come with Spring– Make sure it does not refer to fancy features you are not using yeta e su e t does ot e e to a cy eatu es you a e ot us g yet

– Delete everything between <beans …> and </beans>

• Or, take the empty one from spring-blank20

Page 10: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

The spring-blank Project

• Preconfigured Eclipse project– Standard Java project with Spring Project Nature

• But works with or without Spring IDE plugin

– spring jar and commons-logging jar in lib folder– spring.jar and commons-logging.jar in lib folder• And with those two JARs added to build path

– Empty applicationContext.xml file in src folder

• Usage– R-click project, Copy

R li k i P j t E l P t i– R-click in Project Explorer, Paste, give new name

• Download from coreservlets.comhttp://www coreservlets com/Spring Tutorial/– http://www.coreservlets.com/Spring-Tutorial/

– Import into Eclipse with File Import General Existing Projects into Workspace21

© 2009 Marty Hall

Simple Spring Example

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Page 11: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Goal: Loose Coupling

• Geometric analysis– You have a program that computes areas for various

collections of shapes. You want to avoid code that depends on any particular type of shape, since thedepends on any particular type of shape, since the varieties of shapes keep changing.

• Strategy– Define interface or abstract class

• No dependencies on Spring

– Make concrete implementations of the interface– Make concrete implementations of the interface• No dependencies on Spring

– Declare specific concrete object in bean definition file– Load bean definition file and get instance (driver class)

• No dependency on specific concrete type23

Making Spring Project

• From scratchFil N P j S i S i P j– File New Project Spring Spring Project

• Or, if no Spring IDE, File New Java Java Project

– Named project spring-intro– R-clicked on project, made new folder called lib

• Copied spring-install/dist/spring.jar and spring-install/lib/jakarta-commons/commons-logging.jar to lib

• R-clicked on project, Properties Libraries Add JARs– Then pointed at lib/spring.jar and lib/commons-logging.jar

– R-clicked src folder and New Other Spring Spring Bean Definition

• If no Spring IDE, copied sample applicationContext.xml file

• By copying existing projecty py g g p j– Copied spring-blank– Renamed copy to spring-intro

24

Page 12: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Interface

package coreservlets;

public interface Shape {public double getArea();

}}

• NotesNotes– No imports of Spring packages

• No ties in any way to Spring

C d h l h ( i h i d h d lik– Code that only uses the area (or inherited methods like toString) should refer only to Shape

• But interfaces cannot be used everywhere: code that uses ymore specific info (e.g., the radius of a Circle that implements Shape) will need to use concrete type

25

Concrete Class: Rectangle

public class Rectangle implements Shape {private double length, width; The driver class will use only getAreaprivate double length, width;

public Rectangle() {}

The driver class will use only getAreaand methods inherited from Object, sowill refer to Shape, not Rectangle.

public Rectangle(double length, double width) {setLength(length);

The bean definition in the upcoming applicationContext.xml file will not specify any constructor arguments. So, the zero-arg constructor will be used.

setLength(length);setWidth(width);

}

26

Page 13: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Rectangle (Continued)

public double getLength() {return(length);

}

public void setLength(double length) {this.length = length;t s. e gt e gt ;

}

public double getWidth() {return(width);

The bean definition in the upcoming applicationContext.xml file will refer to the length and width “properties”. That really means to call setLength and setWidth.return(width);

}

public void setWidth(double width) {this width width

g

this.width = width;}

public double getArea() {ireturn(length * width);

}}

27

Concrete Class: Circle

public class Circle implements Shape {private double radius = 1.0;

public Circle() {}

public Circle(double radius) {pub c C c e(doub e ad us) {setRadius(radius);

}

public double getRadius() {

The bean definition in the upcoming applicationContext.xml file will supply a number as a constructor argument. So, this constructor will be used.public double getRadius() {

return(radius);}

public void setRadius(double radius) {public void setRadius(double radius) {this.radius = radius;

}

ipublic double getArea() {return(Math.PI * radius * radius);

}}28

Page 14: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Bean Definition File: applicationContext xmlapplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="shape1" class="coreservlets.Rectangle"><property name="length" value="10"/><property name="width" value="20"/>

</bean>

Call new Rectangle(), then setLength(10) and setWidth(20). Associate the instance with the name “shape1”.</bean>

<bean id="shape2" class="coreservlets.Circle"><constructor-arg value="10"/>

</bean>

p

Call new Circle(10). Associate the instance with the name “shape2”.

</beans>

29

Driver Class

package coreservlets;

import org.springframework.context.*;import org.springframework.context.support.*;

public class ShapeTest {public static void main(String[] args) {ApplicationContext context =new ClassPathXmlApplicationContext

File is in “src”, which is top level of class path.

new ClassPathXmlApplicationContext("/applicationContext.xml");

Shape shape1 = (Shape)context.getBean("shape1");printInfo(shape1);Shape shape2 = (Shape)context.getBean("shape2");printInfo(shape2);

}Names as given in applicationContext.xml.

30

Page 15: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

Driver Class (Continued)

private static void printInfo(Shape shape) {private static void printInfo(Shape shape) {System.out.printf("Area of %s is %.2f%n",

shape.getClass().getSimpleName(),shape.getArea());

}}

Since type is declared as Shape, use only methods defined in the interface (getArea) or inherited from Object (getClass).

31

Output

Rectangle with area of 200.00Ci l ith f 314 16Circle with area of 314.16

32

Page 16: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

© 2009 Marty Hall

Wrap-up

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Summary

• Why Spring?– Spring promotes loose coupling among classes, isolating

one class from changes in another.

• Using Spring in your apps• Using Spring in your apps– Add spring.jar and commons-logging.jar to class path– Put a bean definition file in your class pathy p

• Approach– Define interface or abstract class– Make concrete implementations of the interface– Declare specific concrete object in bean definition file

• <bean id="someName" class="package Class"> </bean>• <bean id="someName" class="package.Class">…</bean>– Use property or constructor-arg

– Load bean definition file and get instance34

Page 17: The Sppgring Framework: Overview and Setupcourses.moreservlets.com/Course-Materials/pdf/spring/... · 2009-02-12 · Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring,

© 2009 Marty Hall

Questions?

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.