november 21st 2009 shaun abram

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

Upload: marinel

Post on 25-Feb-2016

36 views

Category:

Documents


2 download

DESCRIPTION

An Introduction to Spring. November 21st 2009 Shaun Abram. 1. Agenda. Introduction & Background IoC and Dependency Injection Code Example Spring details Spring MVC. 2. Agenda. Introduction & Background IoC and Dependency Injection Code Example Spring details Spring MVC. 3. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: November 21st 2009 Shaun Abram

1

November 21st 2009

Shaun Abram

An Introduction to Spring

Page 2: November 21st 2009 Shaun Abram

2

Agenda

1. Introduction & Background

2. IoC and Dependency Injection

3. Code Example

4. Spring details

5. Spring MVC

Page 3: November 21st 2009 Shaun Abram

3

Agenda

1. Introduction & Background

2. IoC and Dependency Injection

3. Code Example

4. Spring details

5. Spring MVC

Page 4: November 21st 2009 Shaun Abram

4

Introductions

Shaun Abram

• Sun Certified Enterprise Architect

• 10+ years of Java/JEE development

• Tech Lead at Wells Fargo

• http://www.shaunabram.com

You?

Page 5: November 21st 2009 Shaun Abram

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 SurveyIntroduction to Spring Framework 2.5 by Rod Johnson

Page 6: November 21st 2009 Shaun Abram

6

A Brief History…

…of JavaBeans, Enterprise JavaBeans and Spring.

1. 1996: Sun released JavaBeans spec 2. 1998: Sun published EJB 1.0 spec3. 2002: “Expert One-on-One J2EE Design and

Development” published4. 2003: Spring open source project created5. 2009: Spring 2.5 latest production release

Spring 3.0 coming soon…

Page 7: November 21st 2009 Shaun Abram

7

Agenda

1. Introduction & Background

2. IoC and Dependency Injection

3. Code Example

4. Spring details

5. Spring MVC

Page 8: November 21st 2009 Shaun Abram

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

Page 9: November 21st 2009 Shaun Abram

9

Dependency Injection at its simplest

Hard coded dependency

class Test {Object dependency;public Test() {

dependency = new Object();}

}

Dependency Injection enabled

//Constructor Injectionclass Test {

Object dependency;public Test(Object dep) {

this.dependency = dep;}

}

//Setter Injectionclass Test {

Object dependency;public setDependency(Object dep) {

this.dependency = dep;}

}

Page 10: November 21st 2009 Shaun Abram

10

Agenda

1. Introduction & Background

2. IoC and Dependency Injection

3. Code Example

4. Spring details

5. Spring MVC

Page 11: November 21st 2009 Shaun Abram

11

Example: Account Service

Typical Web Architecture:JSP

Controller

Service

DAO (Data Access Object)

Database

Code to interfaces!

Page 12: November 21st 2009 Shaun Abram

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

Page 13: November 21st 2009 Shaun Abram

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

Page 14: November 21st 2009 Shaun Abram

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 possibilitiesUnderlying problem is Coupling…

Page 15: November 21st 2009 Shaun Abram

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

Page 16: November 21st 2009 Shaun Abram

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;}

}

Page 17: November 21st 2009 Shaun Abram

17

Example: Updated Unit Testpublic void testGetAvailableAmount () {

AccountService accountService = new AccountServiceImpl();AccountDAO accountDAOMock = mock(AccountDAO.class);accountService.setAccountDAO(accountDAOMock);

int accNum = 1;

//set Mock behavior here!

//execute testInteger availableAmount = accountService.getAvailableAmount(accNum);//verify resultsassertTrue(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

Page 18: November 21st 2009 Shaun Abram

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

Page 19: November 21st 2009 Shaun Abram

19

Agenda

1. Introduction & Background

2. IoC and Dependency Injection

3. Code Example

4. Spring details

5. Spring MVC

Page 20: November 21st 2009 Shaun Abram

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 

Page 21: November 21st 2009 Shaun Abram

21

Spring Details - Container

A container will• create objects• wire them together• configure them • manage bean lifecycle

2 distinct types:• BeanFactory• ApplicationContext

Page 22: November 21st 2009 Shaun Abram

22

Spring Config File• A Spring IoC container manages one or more beans. • Spring config file contains the bean definitions• The <bean> element is the most basic configuration unit in Spring. e.g.

<bean id="accountService" class="com.codecamp.AccountServiceImpl“/>

 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();

<bean id=“otherService" class=“com.codecamp.OtherServiceImpl">

<constructor-arg value=“otherDao"/> <property name=“otherDao2" ref=“otherDao2"/><property name="greeting" value="Hello From Spring!"/>

</bean>

Page 23: November 21st 2009 Shaun Abram

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 container3. Retrieve first bean

Page 24: November 21st 2009 Shaun Abram

<?xml version="1.0" encoding="UTF-8"?>

<beans>

<bean id="accountService" class="com.codecamp.AccountServiceImpl">

<constructor-arg ref="accountDao"/>

</bean>

<bean id="accountDao" class=“com.codecamp.SimpleAccountDao"/>

</beans>

24

Example: Dependency injection via Spring

Page 25: November 21st 2009 Shaun Abram

25

Spring DI example

public class SpringExample {

public static void main(String[] args) {AccountService accountService;int accountNum = new Integer(args[0]);

//Spring Bootstrap codeFileSystemResource 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);}

}

Page 26: November 21st 2009 Shaun Abram

26

Spring Containers in more detail

2 distinct types:• BeanFactory• ApplicationContext

Page 27: November 21st 2009 Shaun Abram

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

Page 28: November 21st 2009 Shaun Abram

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. ClassPathXmlApplicationContextFileSystemXmlApplicationContextXmlWebApplicationContext

Page 29: November 21st 2009 Shaun Abram

29

Spring Details - Containers

ApplicationContext vs BeanFactory?

If in doubt, use ApplicationContext

Page 30: November 21st 2009 Shaun Abram

30

Bean scopes

So far, we have been using bean definitions like this…<bean id=" greetingDao" class="package.GreetingDao"/>

This essentially does the equivalent ofgreetingDAO = 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.

Page 31: November 21st 2009 Shaun Abram

31

Singleton scope

<bean id="accountDao" class="codecamp.AccountDao" scope=”singleton”/>is the same as <bean id=" accountDao " class=" codecamp. AccountDao "/>

Page 32: November 21st 2009 Shaun Abram

32

Prototype Scope

Page 33: November 21st 2009 Shaun Abram

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

Page 34: November 21st 2009 Shaun Abram

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

Page 35: November 21st 2009 Shaun Abram

35

Custom Initialization

•Custom initialization methodsIf a bean has a default or custom init method declared, the specified initialization method will be called.<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

•InitializingBean interfaceIf the bean implements InitializingBean, it’s afterPropertiesSet() method will be called.Discouraged as couples the code to Spring.Instead, use an initialization method or @PostConstruct

  •@PostConstruct

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!

Page 36: November 21st 2009 Shaun Abram

36

Custom Destruction

•Custom destroy methodsAny default or custom destroy method declared will be called. e.g.<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>

•DisposableBean interfaceIf the bean implements DisposableBean, it’s destroy() method will be called.Discouraged as couples the code to Spring.Instead, use an destroy method or @PreDestroy

 •@ 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

Page 37: November 21st 2009 Shaun Abram

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

Page 38: November 21st 2009 Shaun Abram

38

Agenda

1. Introduction & Background

2. IoC and Dependency Injection

3. Code Example

4. Spring details

5. Spring MVC

Page 39: November 21st 2009 Shaun Abram

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 2i.e. it has a dedicated Front Controller (DispatcherServlet)…

• Alternative to Struts• Follows Spring paradigms, including IoC/DI

Page 40: November 21st 2009 Shaun Abram

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

Page 41: November 21st 2009 Shaun Abram

41

Spring MVC

Page 42: November 21st 2009 Shaun Abram

42

Example Spring MVC Controller

@Controllerpublic class HelloWorldController {

@RequestMapping("/helloWorld")public ModelAndView helloWorld() {

ModelAndView mac = new ModelAndView();mav.setViewName("helloWorld");mav.addObject("message", "Hello World!");return mav;

}}

Spring ‘startup’ code not required because1) a Listener Servlet called Context Loader will read your Spring config file and load all beans into the container2) The DispatcherServlet (the Front Controller) passes all requests to the appropriate Controller – no need to manually get access to your first bean (or two)..

Page 43: November 21st 2009 Shaun Abram

43

Spring Web Flow

There are 2 kinds of common interaction approaches in web apps1) Free flow navigation

The user controls flow2) Conversation flow

User has come control, but app controls bigger picturee.g.• ordering a product on a site• login These sequences are called a conversation flow

Free flow: Handled by Spring MVCConversation flow: Handled by Spring Web Flow

(a special implementation of a MVC controller)

Page 44: November 21st 2009 Shaun Abram

44

Spring Web Flow

Conversation flow can be handled just using Spring MVCe.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

Page 45: November 21st 2009 Shaun Abram

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 flowby enabling you to define the flow in a separate self contained flow

definition

Page 46: November 21st 2009 Shaun Abram

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

Page 47: November 21st 2009 Shaun Abram

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 Slides @ www.shaunabram.com

Page 48: November 21st 2009 Shaun Abram

48

Questions?

Page 49: November 21st 2009 Shaun Abram

49

Follow up

www.shaunabram.com

[email protected]