1 oracle consulting – java professional community – 29 augustus 2005 spring – power to the...

72
1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle Consulting – Java Professional Community, maandag 29 augustus 2005

Upload: gyles-bradley

Post on 30-Dec-2015

216 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

1Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring – Power to the POJOIntroductie tot het Spring Framework

Lucas Jellema

Oracle Consulting – Java Professional Community,

maandag 29 augustus 2005

Page 2: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

2Oracle Consulting – Java Professional Community – 29 augustus 2005

Agenda

Introductie Spring – History, Background Hoe kom je aan nieuwe objecten

BeanFactory en Inversion of Control + Dependency Injection

Hoe laat je bestaande objecten naar je pijpen dansen? Aspect Oriented Programming (AOP)

Business Tier & Architectuur Test Driven Development Spring Persistence & Spring DAO Spring Remoting Losse eindjes, conclusies, discussie Workshop

Page 3: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

3Oracle Consulting – Java Professional Community – 29 augustus 2005

Where we’ve come from

EJB as we know it… Resembles the original JavaBeans specification in name only. Heavyweight:

• Requires application server

• Difficult to unit-test

• Intrusive (must implement EJB interfaces)

Complex• Home/Remote/Local/LocalHome interfaces

• Deployment descriptors

Non-intuitive

Page 4: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

4Oracle Consulting – Java Professional Community – 29 augustus 2005

The future of EJB…

Spilling the beans… EJB 3.0 will embrace simplicity Based on POJO/POJI (? Well, maybe) Employ dependency injection instead of LDAP Declarative services (transactions, security) will be

aspects Entity beans will be POJOs, persisted via Hibernate-

like framework

Page 5: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

5Oracle Consulting – Java Professional Community – 29 augustus 2005

The future is NOW!

Spring is a lightweight container framework Build applications based on POJO/POJI. Wire beans together using dependency injection. Declaratively apply transactions and security using

aspect. Integrates cleanly with Hibernate for persistence.

EJB 3.0=Spring + Hibernate + Metadata

Page 6: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

6Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring History

J2EE Design and Development – by Rod Johnson, 2002 Introducing the i21 framework

First release of Spring: Spring 2004 Spring 1.2.4: August 2005 Open Source

Interface21 – small company with most core committers

Contributions from Oracle and otherparties

Spawned many sub-projects

Page 7: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

7Oracle Consulting – Java Professional Community – 29 augustus 2005

Power to the POJO

Con

sist

ent S

ervi

ce A

bstra

ctio

ns

(Tem

plat

e Pat

tern

)

AOP

IoC (Dependency Injection)

Page 8: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

8Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring’s modules

Page 9: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

9Oracle Consulting – Java Professional Community – 29 augustus 2005

What’s more…

Remoting support via RMI, JAX-RPC, and Hessian/Burlap

Metadata (ala, JSR-175 or Commons Attributes) Persistence via TopLink, Hibernate, JDO, or iBatis

support E-mail support EJB support JMX Support (Spring 1.1) JMS support Spring Rich Client Platform (Spring 1.1) Spring .Net

Page 10: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

10Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring is HOT!

Page 11: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

11Oracle Consulting – Java Professional Community – 29 augustus 2005

Many books available

J2EE without EJB The starting point

Spring Live Pro Spring Spring in Action Professional Spring Development

By The Team

Page 12: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

12Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring Home: http://www.springframework.org

Page 13: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

13Oracle Consulting – Java Professional Community – 29 augustus 2005

Core SpringInversion of Control & Dependency Injection

Page 14: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

14Oracle Consulting – Java Professional Community – 29 augustus 2005

Coupling

Highly coupled code is… Hard to test Hard to maintain Exhibits “whack-a-mole” style bugs

• Here one pops up, when you solve it, another one appears

Uncoupled code is… Code that doesn’t do anything

Coupling is somewhat necessary… …but should be controlled

Page 15: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

15Oracle Consulting – Java Professional Community – 29 augustus 2005

Dependency Injection

The “Hollywood Principle”: Don’t call me, I’ll call you.

Collaborators aren’t asked for…they’re received. Also known as “Dependency Injection”, thanks to

Martin Fowler.

Page 16: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

16Oracle Consulting – Java Professional Community – 29 augustus 2005

Benefits of IoC

Objects are more cohesive because they are no longer responsible for obtaining their own collaborators.

When used with interfaces, code is very loosely coupled.

Page 17: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

17Oracle Consulting – Java Professional Community – 29 augustus 2005

Elements of a Spring app

Beans Not EJBs. Actually, not necessarily JavaBeans. Just

POJOs

Bean wiring Typically an XML file.

A bootstrap class A class with a main() method. A servlet.

The bootstrap class uses a BeanFactory (or IoC Container) to retrieve POJOs That have been ‘wired’ and ‘dependency injected’

Page 18: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

18Oracle Consulting – Java Professional Community – 29 augustus 2005

IoC Container in ActionApplication Class needs POJOs

Application

IoC ContainerxmlPOJO 1

pojo 1

pojo 2

pojo 3

getBean(“POJO1”)

POJO 2

POJO 3

Page 19: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

19Oracle Consulting – Java Professional Community – 29 augustus 2005

IoC Container in ActionApplication Class needs POJOs

HrmClient

xml

HrmServiceImpl

hrmService

employeeDao

dataSourceDBDirect

getBean(“hrmService”)

EmployeeJdbcDAO

DriverManagerDataSource

IoC Container

Hrm

Service

DataS

ource

Em

pDA

O

Page 20: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

20Oracle Consulting – Java Professional Community – 29 augustus 2005

Wiring beans in XML

Root elements is <beans> Contains one or more <bean> elements

id (or name) attribute to identify bean class attribute to specify class

<beans> <bean id=“foo” class=“com.habuma.foobar.Foo”> <!-- Properties defined here --> </bean></beans>

The bean’s ID

The bean’s fully-qualified classname

Page 21: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

21Oracle Consulting – Java Professional Community – 29 augustus 2005

Wiring a property

Use <property> element name attribute specifies name of property

<beans> <bean id=“foo” class=“com.habuma.foobar.Foo”>

<property name=“bar”> <!-- Property value goes here --> </property>

</bean></beans>

Maps to a setBar() call

Page 22: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

22Oracle Consulting – Java Professional Community – 29 augustus 2005

Property values

Strings and numbers:

Null

Lists and arrays:

<property name=“bar”><value>42</value></property>

<property name=“bar”><value>Hello</value></property>

<property name=“bar”> <list> <value>ABC</value> <value>123</value> </list></property>

<property name=“bar”><null/></property>

Page 23: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

23Oracle Consulting – Java Professional Community – 29 augustus 2005

Property values

Sets:

Maps:

<property name=“bar”> <set> <value>ABC</value> <value>123</value> </set></property>

<property name=“bar”> <map> <entry key=“key1”><value>ABC</value></entry> <entry key=“key2”><value>123</value></entry> </set></property>

Page 24: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

24Oracle Consulting – Java Professional Community – 29 augustus 2005

Property values

Property sets:

Other beans:

<property name=“bar”> <props> <prop key=“prop1”>ABC</prop> <prop key=“prop2”>123</prop> </set></property>

<property name=“bar”> <ref bean=“bar”/></property>

Page 25: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

25Oracle Consulting – Java Professional Community – 29 augustus 2005

Auto-wiring

You can auto-wire… “byName”: Property names are matched to bean

names “byType”: Property names are matched to bean types “constructor”: Pico-like constructor wiring. Like

“byType” except using constructor. “autodetect”: Uses reflection to decide whether to

use “byType” or “constructor”

Page 26: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

26Oracle Consulting – Java Professional Community – 29 augustus 2005

Auto-wiring

<bean id=“foo” class=“com.habuma.foobar.Foo” autowire=“byName”/>

<bean id=“foo” class=“com.habuma.foobar.Foo” autowire=“byName”> <property name=“bar”><value>bar</value></property></bean>

<beans default-autowire=“byType”> <!-- Bean definitions go here --></beans>

Page 27: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

27Oracle Consulting – Java Professional Community – 29 augustus 2005

BeanFactory vs. ApplicationContext

A BeanFactory is the Spring container. Loads beans and wires beans together. Dispenses beans as requested. XmlBeanFactory is the most commonly used.

An ApplicationContext is a BeanFactory, but adds “framework” features such as: I18N messages Event notification

Page 28: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

28Oracle Consulting – Java Professional Community – 29 augustus 2005

IoC Examples

Page 29: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

29Oracle Consulting – Java Professional Community – 29 augustus 2005

Example of a IoC based programming

Page 30: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

32Oracle Consulting – Java Professional Community – 29 augustus 2005

Core SpringAspect Oriented Programming

AOP – a programming technique that promotes separation of concerns within a software system

Recurring – often infrastructural – concerns can easily be duplicatedin many objects Security Transaction

Management Logging Profiling

AOP suggestsseparation Concerns are applied

at compile or run-time

Page 31: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

33Oracle Consulting – Java Professional Community – 29 augustus 2005

AOP in a nutshell

Aspect: A modularization of a cross-cutting concern. Implemented in Spring as Advisors or interceptors

Joinpoint: Point during the execution of execution. Advice: Action taken at a particular joinpoint. Pointcut: A set of joinpoints specifying where advice should be

applied. Advisor: Fully represents an aspect, including both advice and a

pointcut. Introduction: Adding methods or fields to an advised class. Weaving: Assembling aspects into advised objects.

Page 32: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

34Oracle Consulting – Java Professional Community – 29 augustus 2005

Without AOP

Page 33: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

35Oracle Consulting – Java Professional Community – 29 augustus 2005

With AOP

Page 34: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

36Oracle Consulting – Java Professional Community – 29 augustus 2005

Implementing AOP

Compile time – modify the source code during compilation Requires a customized Java Compiler For example AspectJ; Spring does not do compile time AOP

Run time – byte injection Change the class when loaded, generating a subclass that

contains the aspects Uses CGLib library

Run time – using the JDK 1.3 Dynamic Proxy Instead of getting an object instance, the application receives a

proxy object The proxy implements the same interface

• And maybe something else as well

• Besides, it can intercept and wrap method calls

Page 35: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

37Oracle Consulting – Java Professional Community – 29 augustus 2005

IoC Container hides AOP implementation from POJO consumer

Application

IoC Container

xml Pojo1Impltarget=pojo1Impl

pojo1 = proxyTargetinterceptorNames=> AspectA, AspectB

getBean(“POJO1”)

POJO 1(interface)

implements

Proxy

implements

target

Aspect Ainvoke()

Aspect Bbefore()

AspectA

AspectB

Page 36: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

38Oracle Consulting – Java Professional Community – 29 augustus 2005

Different types of Advice

Before advice Calls to advised methods are intercepted before the method is called.

After returning advice Calls to advised methods are intercepted after a successful return.

After throws advice Calls to advised methods are intercepted after an exception is thrown.

Around advice/interception Calls to advised methods are intercepted. Call must be explicitly made to target

method. Introduction advice

Allows a class (or rather its proxy) to implement additional interfaces Calls to methods are intercepted…even when the target bean doesn’t have the

method!• Actually, just a special case of around advice

Page 37: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

39Oracle Consulting – Java Professional Community – 29 augustus 2005

Creating Advise

Create a class that implements one or more of the Spring AOP interfaces MethodInterceptor BeforeAdvice AfterReturningAdvice ThrowsAdvice

Implement the interface method before (Method method, Object[] args) afterReturning(Object returnValue, Method method,

Object[] args) invoke(MethodInvocation invocation)

Page 38: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

40Oracle Consulting – Java Professional Community – 29 augustus 2005

Defining Pointcuts in Spring(specify where to apply which Advice)

Programmatically No BeanFactory required Can be used independently of the rest of Spring

Declaratively In the bean container configuration file

(applicationContext.xml)

Page 39: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

41Oracle Consulting – Java Professional Community – 29 augustus 2005

Applications of AOP by Spring itselfalways in conjunction with IoC/DI

Remoting Support Proxy references a remote object

Transaction Management Service method is wrapped in around advice that

opens and closes the transaction Security JMX

Proxy implements the MBean interfaces for its target object

Mock Testing Tested objects are injected with Mock objects that are

dynamically created (made up)

Page 40: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

45Oracle Consulting – Java Professional Community – 29 augustus 2005

Future of AOP – according to Rod Johnson

Programming Aspects and composing an Application from Aspects will become widely accepted Various orthogonal concerns can be dealt with in

parallel Maintaining a single – cross application concern – is

done by maintaining a single aspect Tool and Runtime support for AOP will further increase

Development of IBM WebSphere & WSAD is heavily done in an AOP fashion

Page 41: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

46Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring’s recommended Application Guidelines and Architecture

Program against interfaces For example Service Interface, DAO Interfaces Typically no interfaces for Domain Classes

No configuration “plumbing” in your classes Have configuration details injected

Domain Classes are used through all tiers No Struts ActionForms to wrap domain classes Controllers use Business Service methods to create or

manipulate Domain Objects

Practice “Test driven development”

Page 42: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

47Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring’s recommended architecture

RDBMS

Presentation Tier

Business Tier

Data Tier

Business Services LayerInterfaces and Container Managed

Implementations

DAO Interface LayerInterfaces, independent of

implementing DAO Technology

DAO Implementation layerRetrieves, saves entities using ORM tool or JDBC

PersistentDomainObjects

O/R Mapping LayerJDB

C

Remote Service ExportersUsing SOAP, RMI, JAX-RPC etc.Web Tier Actions

(Controllers)

View ComponentsGenerate HTML or PDF

JDB

C

Page 43: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

48Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and Test Driven Development

Agile Software Engineering methods, such as XP First design and develop a test based on

interfaces Before implementing the interfaces Before starting to resolve a bug

Automated Unit Testing for every class in the application At every stage of development, the test can be rerun!

Unit Testing usually based on JUnit Great integration in Eclipse and JDeveloper 10.1.3

(10.1.2 is somewhat sparse)

Page 44: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

49Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and Test Driven Development

Challenges include Container Dependencies (HttpServlet object) Dependencies on external objects (not a unit test)

• Especially objects that are hard to configure, e.g. DAO Impl

Dependencies on objects that have not yet been implemented

Page 45: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

50Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring support for Test Driven Development

When all objects (Service and DAO Impl) are Spring Beans They get dependency injected by the container

During a test, instead of injecting them with real objects We can inject them with Mock Objects, that will return

the values we specify when called The real objects do not need to exist

• even when they do exist, using mock objects ensures we are performing a true UNIT test

Page 46: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

51Oracle Consulting – Java Professional Community – 29 augustus 2005

Unit Testing HrmServiceImpl using Mock objects

Unit Test

Business Tier

Data Tier

HrmServiceImpl

EmployeeDAO Interfaces, independent of

implementing DAO Technology

EmployeeDAOImpl(does not yet exist)

PersistentDomainObjects

HrmServiceTest(JUnit TestCase)

MockEmployeeDAOImpl

Page 47: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

52Oracle Consulting – Java Professional Community – 29 augustus 2005

Testen en MockObjects

public class TestEmployeeDao

extends AbstractDependencyInjectionSpringContextTests

{

private EmployeeDao employeeDAO;

public void setEmployeeDAO(EmployeeDao employeeDAO)

{

this.employeeDAO = employeeDAO;

}

protected String[] getConfigLocations() {

return new String[]

{"nl/amis/demo/dao/jdbc/applicationContext-jdbc.xml"};

}

public void testFindEmployeeById ()

{

Employee emp = employeeDAO.getEmployeeById(7839);

assertEquals("KING", emp.getName());

assertEquals("PRESIDENT", emp.getJob());

// ...

}

}

<bean id="employee7839" class="nl.amis.demo.domain.Employee">

<property name="name" value="KING" /> <property name="employeeNumber" value="7839" /> <property name="job" value="PRESIDENT" /></bean>

<bean id="employeeMockDAO" class="nl.amis.demo.dao.EmployeeMockDao">

<property name="emp"> <ref local="employee7839" /> </property></bean>

Page 48: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

53Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring JDBC and Spring DAO

Properly implementing those Mock DAO objects

Page 49: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

54Oracle Consulting – Java Professional Community – 29 augustus 2005

Doelen van Spring JDBC

Database acties SQL (Select en Manipulatie) Procedural (stored procedure calls)

Flexibel Externe configuratie van data source Geen Checked Exceptions Out of container testen Database onafhankelijk

Gecontroleerd Exception handling Connection leaking/connection pooling

Productief Geen herhaling van code (tcftc) Vereenvoudigen van Transaction Management

Page 50: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

55Oracle Consulting – Java Professional Community – 29 augustus 2005

Architectuur

Service

DAO

DomainObject

DomainObject

DomainObject

JNDI

Page 51: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

56Oracle Consulting – Java Professional Community – 29 augustus 2005

Example

import java.sql.*;import javax.sql.*;public class EmpDao { public List getAllEmployees() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List emps = new ArrayList(); try { con = getConnection(); pstmt = con.prepareStatement ("select * from emp"); rs = pstmt.executeQuery(); while (rs.next()) { Employee e = new Employee(); e.setId (rs.getLong(1)); e.setName (rs.getString(2)); // ... emps.add(e); } } catch (SQLException e) { // handle exception } finally { try { rs.close(); pstmt.close(); con.close(); } catch (SQLException e1) { // no action needed } } return emps; }}

private Connection getConnection() throws SQLException{ try { Context ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup ("java:comp/env/jdbc/myDatabase"); return ds.getConnection(); } catch (NamingException e) { // handle exception return null; }}

private Connection getConnection() throws SQLException{ try { DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); return DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl“ ,"scott", "tiger"); } catch (SQLException sqle) { // handle exception return null; }}

Page 52: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

57Oracle Consulting – Java Professional Community – 29 augustus 2005

Template Pattern

Operation largely follows a standard algorithm At certain steps, specialization or customization is

required Several implementations

Abstract ‘hook’ methods that sub-class may override Parametrize behaviour and have invoker provide the

details• Such as the SQL Query

Spring JDBC Templates Implement all JDBC wiring Parametrize the query and the result-handling

Page 53: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

58Oracle Consulting – Java Professional Community – 29 augustus 2005

Example of Spring JDBC Template

public interface empDao {

public List getAllEmployees ();

}

public class EmployeeJdbcDao extends JdbcDaoSupport implements EmpDao {

public List getAllEmployees() {

JdbcTemplate jt = getJdbcTemplate();

return jt.queryForList (“select * from emp”);

}

}

<bean id="dataSourceDBDirect"

class="org.springframework.jdbc.datasource.DriverManagerDataSource"

destroy-method="close">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

<property name="url" value="jdbc:oracle:thin:@localhost:1521:BAARSJES1" />

<property name="username" value="scott" />

<property name="password" value="tiger" />

</bean>

<bean id="employeeDAO" class="nl.amis.demo.dao.jdbc.EmployeeJdbcDao" >

<property name="dataSource">

<ref local="dataSourceDBDirect" />

</property>

</bean>

Page 54: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

59Oracle Consulting – Java Professional Community – 29 augustus 2005

jdbc helper classes

JdbcTemplate query, queryForList, queryForInt, queryFor.. ArrayList (per row) of HashMaps (column name as

key)

RowMapper PreparedStatementCreator/Callback MappingSQLQuery ...

Page 55: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

60Oracle Consulting – Java Professional Community – 29 augustus 2005

How can Spring help?

Make life easier:

DAO Support JDBC, Hibernate, Toplink, iBatis, JDO,

javax.persistence (“EJB 3.0”) , ...

Dependency Injection Jdbc helper classes Exception Handling MockObjects Transaction Management

Page 56: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

61Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring Architectuur

Service

DAO

DomainObject

DomainObject

DomainObject DAO

Interface

ApplicationContext-jdbc

XXDAOSupport

JdbcDaoSupportHibernateDaoSupportTopLinkDaoSupport...

Page 57: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

62Oracle Consulting – Java Professional Community – 29 augustus 2005

Exception Handling

RuntimeException ipv checked SQLException DataAccessException

SQLException Translation DataIntegrityViolationException DataRetrievalFailureException CannotGetJdbcConnectionException ...

Page 58: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

63Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and Web ApplicationsStruts and other Controller Frameworks

Struts support Auto-Load WebContext (== BeanFactory) in session Make Action Classes Spring aware and have them

reference the WebContext Proxy Action Classes

and Dependency Inject them• Register Actions

as Spring Beans

Similar support for WebWork Tapestry

Page 59: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

64Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and Web ApplicationsJava Server Faces

Java Server Faces JSF has managed-beans

Very similar to Spring Beans Though no support for AOP And: do you want low level, persistency related

configuration details in the faces-config.xml

JSF-Spring project offers a JSF variable resolver It takes bean references in faces-config.xml and tries

to resolve them in Spring context files

Page 60: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

65Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and Web ApplicationsSpring MVC Controller Framework

Positioned to replace Struts Better, more intuitive, modern architecture Full benefits from IoC and AOP

Works with (these are all Spring Beans) Controllers – that process the request, update and prepare the

Model; they also return a result, a symbolic indication of the ModelView to proceed to

ViewResolvers – that decide which View to let render

ViewBeans – thatwrap View Componentssuch as JSP, Velocity Template, FreeMarker page

Page 61: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

66Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring MVC Controller FrameworkSupport for various View technologies

JSP – using the Spring tag-library (very small, primarily use JSTL)

FreeMarker Velocity Tiles File Download Excel – using Apache POI PDF – using iText XSL-T JasperReports

Page 62: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

67Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring RemoteSupport for distributed applications

Spring’s number one concept concerning remote, distributed objects (take from Martin Fowler): Do NOT distribute!!!

However, in certain circumstances you probably have to Cross organizational boundaries Rich Clients Remote process

accessing back-end server

Page 63: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

68Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring’s Remote Façade Philosphy

Remote access for example supporting remote clients over RMI or

publishing a WebService should be regarded as an alternative presentation

layer no different from an standard Browser oriented HTML

interface On well-defined middle tier service interfaces

that are blissfully unaware that they are exposed and consumed remotely

Remoting infrastructure – for example Data Transfer Objects – should be added on top of the well defined, OO, fully POJO based service

Page 64: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

69Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring support for “remoting”

Spring will Declaratively expose Service interfaces for remote

clients Declaratively expose remote Service interfaces for

local clients

Support for these protocols: RMI Caucho’s Hessian and Burlap Spring’s own HttpInvoker EJB SOAP (based on JAX-RPC, using AXIS or XFire)

Page 65: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

70Oracle Consulting – Java Professional Community – 29 augustus 2005

Exposing Service to remote clients

ClientCode Proxy for Service(generated by BeanFactory)

Service Interface

Service Implementation

Spring Exporter

Page 66: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

71Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring Exporters

Declaratively set up in the configuration file Using a specific protocol Spring Service Exporter

defines an End Point where the Service can be invoked• typically linked to a port

translates incoming remote calls to local calls• unmarshalling parameter values• marshalling return values and exceptions

Spring Exporter often works with Spring Remote Client

Page 67: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

72Oracle Consulting – Java Professional Community – 29 augustus 2005

Details from Server and Client side BeanConfiguration files

Server Side – HttpInvoker Protocol Exporter

Client Side – HttpInvoker Protocol proxy creator

Page 68: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

73Oracle Consulting – Java Professional Community – 29 augustus 2005

Extra Features

JMX – proxy Spring Beans to register them as MBeans

JMS Email JNDI Scheduling (Quartz) Transaction Management

Page 69: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

74Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and the Oracle Java Technology Stack

Spring DAO has TopLink support Since Spring 2005, contributed by Oracle

Spring based POJO business service can be registered with ADF Binding Framework Ideally we can have the registration mechanism honor the

ApplicationContext origin of the Service Object Question: how does ADF currently instantiate its Business

Services?

Spring DAO for ADF BC seems pointless ADF BC is already pretty much wrapped – the API is already

fairly high level The Configurations (bc4j.xcfg) provide a level of decoupling and

dependency injection Spring DAO focuses on POJO – ADF BC does not

Page 70: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

75Oracle Consulting – Java Professional Community – 29 augustus 2005

Spring and the Oracle Java Technology Stack

Spring MVC on ADF BC Business Service could be done though a lot of the natural benefits are lost

UIX could be used with Spring MVC as View technology losing the Struts ADF LifeCyle management

Shortly ADF Faces can be used with Spring MVC as well Spring Remoting can be used to publish and consume

Somewhat overlapping with JDeveloper WebServices support

Spring AOP could be applied to ADF BC objects If we can find the right hook – does not seem easy!

Page 71: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

76Oracle Consulting – Java Professional Community – 29 augustus 2005

Sub Projects and initiatives around Spring

Spring Security Spring IDE (for Eclipse) Spring Rich Client Spring Modules & Spring WebFlow Spring BeanDoc Spring .NET – by Rod Johnson et. al.

Focus on C#

JSF-Spring XDoclet – Spring Bean Configuration generator Aurora MVC Framework More support for Persistency OO/R Frameworks

EJB 3.0…

Page 72: 1 Oracle Consulting – Java Professional Community – 29 augustus 2005 Spring – Power to the POJO Introductie tot het Spring Framework Lucas Jellema Oracle

77Oracle Consulting – Java Professional Community – 29 augustus 2005

Discussion

Ik lust eigenlijk nu ook wel een kop koffie…