145
Framework Concepts

Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

Embed Size (px)

Citation preview

Page 1: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

Framework

Concepts

Page 2: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 2 Gpower Software

The enterprise challenge

0 10 20 30 40 50 60 70 80 90 100

High Availability

Cost Effective

Scalability

Time to Market

Secure

Good Performance

Ability to integrate

Multi-channel

Page 3: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 3 Gpower Software

How can you meet the enterprise challenges?

• Use a Flexible Foundation

• Use Open and Extensible Client Interfaces

• Leverage Legacy systems and data

• Adopt Component based solutions

Database

Flexible foundation

Business Application

Business Application

Business Application

Business Application

Page 4: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 4 Gpower Software

Business Application

Business Application

Business Application

CustomizedProducts

Re-usableComponents

Beans

ID engine

calculation

J2EE Server

Application Framework

Assembly on a

Common platform

Component based solutionsAutomotive industryAutomotive industry Software businessSoftware business

Page 5: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 5 Gpower Software

What is a framework?

A framework is a set of prefabricated software building blocks that programmers can use, extend, or customize for specific computing solutions

By Taligent’s definition

A framework is a set of prefabricated software building blocks that programmers can use, extend, or customize for specific computing solutions

By Taligent’s definition

With framework-oriented programming, software development is one step closer towards a factory mode of

operation

J2EE Server

Application Framework

Business Applicatio

n

Business Applicatio

n

Business Applicatio

n

Page 6: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 6 Gpower Software

What should a framework achieve?

An application framework will help to:

Define the guidelines for building components

Define how all the components should fit together

Define the guidelines for managing change

Ensure consistency of code

Focus developers on business logic

An application framework will help to:

Define the guidelines for building components

Define how all the components should fit together

Define the guidelines for managing change

Ensure consistency of code

Focus developers on business logic

Page 7: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 7 Gpower Software

Business Functions

0

Small ScaleApplication development

Large Scale Application Development

With Framewor

k

Time/EffortMan days

Without Framework

X

3X

Framework reduces development time

Integration

Design

Requirement

Coding

Integration

Design

Requirement

Coding

Page 8: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

Hibernate

Page 9: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 10 Gpower Software

• Why object/relational mapping?

• Solving the mismatch with tools

• Basic Hibernate features

• Hibernate Query Options

• Detached Objects

Hibernate Introduction

Page 10: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 11 Gpower Software

• The Structural Mismatch. Java types vs. SQL datatypes

user-defined types (UDT) are in SQL:1999 current products are proprietary

Type inheritance no common inheritance model

Entity relationships.

Hibernate Introduction

Page 11: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 12 Gpower Software

• “Modern” ORM Solutions Transparent Persistence (POJO/JavaBeans) Persistent/transient instances Automatic Dirty Checking Transitive Persistence Lazy Fetching Outer Join Fetching Runtime SQL Generation Three Basic Inheritance Mapping Strategies

Hibernate Introduction

Page 12: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 13 Gpower Software

• Why ORM Structural mapping more robust Less error-prone code Optimized performance all the time Vendor independence

Hibernate Introduction

Page 13: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 14 Gpower Software

• What do RDBs do well?Work with large amounts of data

Searching, sortingWork with sets of data

Joining, aggregatingSharing

Concurrency (Transactions)Many applications

IntegrityConstraintsTransaction isolation

Hibernate Introduction

Page 14: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 15 Gpower Software

• What do RDBs do badly? Modeling

No polymorphismFine grained models are difficult

Business logic Stored procedures really bad

Hibernate Introduction

Page 15: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 16 Gpower Software

• The Goal Take advantage of those things that relational databases do well Without leaving the language of objects / classes

Hibernate Introduction

Page 16: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 17 Gpower Software

• Hibernate Opensource (LGPL) Mature Popular (15,000 downloads/month) Custom API Will be core of JBoss CMP 2.0 engine

Hibernate Introduction

Page 17: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 18 Gpower Software

• Features Persistence for POJOs (JavaBeans) Flexible and intuitive mapping Support for fine-grained object models Powerful, high performance queries Dual-Layer Caching Architecture (HDLCA) Toolset for roundtrip development Support for detached persistent objects

Hibernate Introduction

Page 18: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 19 Gpower Software

Hibernate High Level Architecture

Page 19: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 20 Gpower Software

Hibernate Full Cream Architecture

Page 20: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 21 Gpower Software

Conception• SessionFactory

– A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider

• Session – A single-threaded, short-lived object representing a conversation between the

application and the persistent store. Wraps a JDBC connection. Factory for Transaction.

• Persistent Objects and Collections– Short-lived, single threaded objects containing persistent state and business

function. These might be ordinary JavaBeans/POJOs,

• Transient Objects and Collections– Instances of persistent classes that are not currently associated with a Session.

• Transaction – A single-threaded, short-lived object used by the application to specify atomic

units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases.

Page 21: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 22 Gpower Software

• Example

Hibernate Mapping

Page 22: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 23 Gpower Software

• Persistent Class JavaBean specification (or POJOs) No-arg constructor Accessor methods for properties Collection property is an interface Identifier property

Hibernate Mapping

public class AuctionItem {private Long _id;private Set _bids;private Bid _successfulBidprivate String _description;

public Long getId() {return _id;

}private void setId(Long id) {

_id = id;}public String getDescription() {

return _description;}public void setDescription(String desc) {

_description=desc;}…

}

Page 23: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 24 Gpower Software

• XML Mapping Readable metadata Column/table mappings Surrogate key generation strategy Collection metadata Fetching strategies

Hibernate Mapping

<class name=“AuctionItem” table=“AUCTION_ITEM”>

<id name=“id” column=“ITEM_ID”>

<generator class=“native”/>

</id>

<property name=“description” column=“DESCR”/>

<many-to-one name=“successfulBid”column=“SUCCESSFUL_BID_ID”/>

<set name=“bids”

cascade=“all”

lazy=“true”>

<key column=“ITEM_ID”/>

<one-to-many class=“Bid”/>

</set>

</class>

Page 24: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 25 Gpower Software

Class <class name="ClassName" table="tableName" discriminator-value="discriminator_value" mutable="true|false" schema="owner" proxy="ProxyInterface" dynamic-update="true|false" dynamic-insert="true|false" select-before-update="true|false" polymorphism="implicit|explicit" where="arbitrary sql where condition" persister="PersisterClass" batch-size="N" optimistic-lock="none|version|dirty|all" lazy="true|false"/>

Basic O/R Mapping

Page 25: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 26 Gpower Software

ID <id name="propertyName" type="typename" column="column_name" unsaved-value="any|none|null|id_value" access="field|property|ClassName">

<generator class="generatorClass"/></id>

Generator: Increment, sequence, hilo, seqhilo, uuid.hex, native, assigned,

foreign

Basic O/R Mapping

Page 26: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 27 Gpower Software

Composite-id <composite-id name="propertyName" class="ClassName" unsaved-value="any|none" access="field|property|ClassName">

<key-property name="propertyName" type="typename" column="column_name"/>

<key-many-to-one name="propertyName class="ClassName" column="column_name"/>

......</composite-id>

Basic O/R Mapping

Page 27: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 28 Gpower Software

Property <property name="propertyName" column="column_name" type="typename" update="true|false" insert="true|false" formula="arbitrary SQL expression" access="field|property|ClassName" />

Basic O/R Mapping

Page 28: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 29 Gpower Software

Many to one<many-to-one name="propertyName" column="column_name" class="ClassName" cascade="all|none|save-update|delete" outer-join="true|false|auto" update="true|false" insert="true|false" property-ref="propertyNameFromAssociatedClass" access="field|property|ClassName"

unique="true|false" />

One to one<one-to-one name="propertyName" class="ClassName" cascade="all|none|save-update|delete" constrained="true|false" outer-join="true|false|auto" property-ref="propertyNameFromAssociatedClass" access="field|property|ClassName" />

Basic O/R Mapping

Page 29: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 30 Gpower Software

Collection (<set>, <list>, <map>, <bag>, <array>)

<map name="propertyName" table="table_name" schema="schema_name" lazy="true|false" inverse="true|false" cascade="all|none|save-update|delete|all-delete-orphan" sort="unsorted|natural|comparatorClass" order-by="column_name asc|desc" where="arbitrary sql where condition" outer-join="true|false|auto" batch-size="N" access="field|property|ClassName" >

<key .... /> <index .... /> <element .... /></map>

Basic O/R Mapping

Page 30: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 31 Gpower Software

Many-to-many

<many-to-many column="column_name" class="ClassName" outer-join="true|false|auto" />

Basic O/R Mapping

Page 31: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 32 Gpower Software

Transient Objects

Objects instantiated using the new operator aren’t immediately persistent. Their state is transient, which means they aren’t associated with any database table row, and so their state is lost as soon as they’re dereferenced.

Persist Objects

A persistent instance is any instance with a database identity. Persistent instances are associated with the persistence manager. Persistent instances are always associated with a Session and are transactional

Detached Objects

Instances lose their association with the persistence manager when you close() the Session. We refer to these objects as detached, indicating that their state is no longer guaranteed to be synchronized with database state; they’re no longer under the management of Hibernate.

Object state

Page 32: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 33 Gpower Software

Object Lifecycle

Page 33: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 34 Gpower Software

Typical Usage

Session sess = factory.openSession();Transaction tx = null;try { tx = sess.beginTransaction(); // do some work ... tx.commit();}catch (Exception e) { if (tx!=null) tx.rollback(); throw e;}finally { sess.close();}

Page 34: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 35 Gpower Software

Automatic dirty object checking Retrieve an AuctionItem and change description

Session session = sessionFactory.openSession();Transaction tx = s.beginTransaction();

AuctionItem item = (AuctionItem) session.get(ActionItem.class, itemId);

item.setDescription(newDescription);

tx.commit();session.close();

Hibernate Introduction

Page 35: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 36 Gpower Software

Transitive Persistence Retrieve an AuctionItem and create a new persistent Bid

Bid bid = new Bid();bid.setAmount(bidAmount);

Session session = sf.openSession();Transaction tx = session.beginTransaction();

AuctionItem item = (AuctionItem) session.get(ActionItem.class, itemId);

bid.setItem(item);item.getBids().add(bid);

tx.commit();session.close();

Hibernate Introduction

Page 36: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 37 Gpower Software

Detached objects Retrieve an AuctionItem and change the description: Session session = sf.openSession();Transaction tx = session.beginTransaction();AuctionItem item =

(AuctionItem) session.get(ActionItem.class, itemId);tx.commit();session.close();

item.setDescription(newDescription);

Session session2 = sf.openSession();Transaction tx = session2.beginTransaction();session2.update(item);tx.commit();session2.close();

Hibernate Introduction

Page 37: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 38 Gpower Software

• Hibernate query options Hibernate Query Language (HQL)

“minimal” object-oriented dialect of ANSI SQL Criteria Queries

Extensible framework for expressing query criteria as objectsIncludes “query by example”

Native SQL queriesDirect passthrough with automatic mappingNamed SQL queries in metadata

Hibernate Introduction

Page 38: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 39 Gpower Software

• Hibernate Query LanguageMake SQL be object oriented

Classes and properties instead of tables and columns Polymorphism Associations Much less verbose than SQL

Full support for relational operations Inner/outer/full joins, cartesian products Projection Aggregation (max, avg) and grouping Ordering Subqueries SQL function calls

Hibernate Introduction

Page 39: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 40 Gpower Software

• HQL ExampleSimple

from AuctionItemi.e. get all the AuctionItems:List allAuctions = session.createQuery(“from

AuctionItem”).list();

More realistic exampleselect item

from AuctionItem itemjoin item.bids bid

where item.description like ‘hibernate%’and bid.amount > 100

i.e. get all the AuctionItems with a Bid worth > 100 and description that begins with “hibernate”

Hibernate Introduction

Page 40: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 41 Gpower Software

• Criteria Queries

List auctionItems = session.createCriteria(AuctionItem.class)

.setFetchMode(“bids”, FetchMode.EAGER)

.add( Expression.like(“description”, description) )

.createCriteria(“successfulBid”).add( Expression.gt(“amount”,

minAmount) ).list();

Equivalent HQL:

from AuctionItem itemleft join fetch item.bids

where item.description like :descriptionand item.successfulbid.amount > :minAmount

Hibernate Introduction

Page 41: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 42 Gpower Software

• Example Queries

AuctionItem item = new AuctionItem();item.setDescription(“hib”);Bid bid = new Bid();bid.setAmount(1.0);List auctionItems =

session.createCriteria(AuctionItem.class)

.add( Example.create(item).enableLike(MatchMode.START) ).createCriteria(“bids”)

.add( Example.create(bid) ).list();

Equivalent HQL:

from AuctionItem itemjoin item.bids bid

where item.description like ‘hib%’and bid.amount > 1.0

Hibernate Introduction

Page 42: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 43 Gpower Software

• Fine-grained persistence Fine-grained object models are good

greater code reuse easier to understand More typesafe Better encapsulation

Hibernate defines Entities (lifecycle and relationships) Values (no identity, “embedded” state)

Hibernate Introduction

Page 43: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 44 Gpower Software

• Composing Objects Address of a User Address depends on User

Hibernate Introduction

<class name=“User” table=“USER”> <component name=“address”> <property name=“street”

column=“STREET”/> <property name=“zipCode”

column=“ZIPCODE”/> <property name=“city”

column=“CITY”/> </component></class>

Page 44: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 45 Gpower Software

• Layer Communication The presentation layer is decoupled from the service layer and business

logic:

Hibernate Introduction

Presentation Layer

Service Layer

Domain Objects

Remote? DTO?

Page 45: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 46 Gpower Software

• DTOs are Evil “Useless” extra LOC Not objects (no behavior) Parallel class hierarchies smell Shotgun change smell

Solution: detached object support

Hibernate Introduction

Page 46: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 47 Gpower Software

• Detached Object Support For applications using servlets + session beans You don’t need to select a row when you only want to update it! You don’t need DTOs anymore! You may serialize objects to the web tier, then serialize them back to the

EJB tier in the next request Hibernate lets you selectively reassociate a subgraph! (essential for

performance)

Hibernate Introduction

Page 47: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 48 Gpower Software

Feature Review

Transparent Persistence Bad

Persistent/transient instances Bad

Automatic Dirty Checking Good

Transitive Persistence Bad

Lazy Fetching Good

Outer Join Fetching Average

Runtime SQL Generation Average

Three Basic Inheritance Mapping Strategies

Bad

Hibernate Introduction

CMP VS Hibernate

Page 48: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

Spring Framework

Core

Page 49: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 50 Gpower Software

• A clear separation of application component responsibility.– Presentation layer

• Concentrates on request/response actions• Handles UI rendering from a model. • Contains formatting logic and non-business related validation logic.• Handles exceptions thrown from other layers

– Persistence layer • Used to communicate with a persistence store such as a relational

database.• Provides a query language• Possible O/R mapping capabilities• JDBC, Hibernate, iBATIS, JDO, Entity Beans, etc.

– Domain layer • Contains business objects that are used across above layers.• Contain complex relationships between other domain objects• May be rich in business logic• May have ORM mappings• Domain objects should only have dependencies on other domain

objects

Application Layering

Page 50: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 51 Gpower Software

Application Layering (cont)– Service layer

• Gateway to expose business logic to the outside world• Manages ‘container level services’ such as transactions,

security, data access logic, and manipulates domain objects

• Not well defined in many applications today or tightly coupled in an inappropriate layer.

Page 51: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 52 Gpower Software

Proposed Web App Layering

Page 52: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 53 Gpower Software

• Presentation/Business/Persistence

• Struts+Spring+Hibernate

• Struts + Spring + EJB

• JavaServer Faces + Spring + iBATIS

• Spring + Spring + JDO

• Flex + Spring + Hibernate

• Struts + Spring + JDBC

• You decide…

More Application Layering Combinations

Page 53: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 54 Gpower Software

• Sun’s traditional solution to middle tier business logic

• Specification that did not always work as projected in real applications.

• EJBs are less portable than POJO based architectures.

• Inconsistencies by vendors make EJBs break the “write once, run anywhere” rule.

• Fosters over-engineering in most cases

• Entity Beans – very limiting compared to alternatives such as Hibernate.

• Performance with POJOs are much faster then EJBs.

• EJBs run in a heavy container

• Your code becomes coupled to EJB API.

• We need to redefine what J2EE means…

EJB (<=2.x) in the Service Layer

Page 54: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 55 Gpower Software

• A lightweight framework that addresses each tier in a Web application.– Presentation layer – An MVC framework that is most similar to

Struts but is more powerful and easy to use.– Business layer – Lightweight IoC container and AOP support

(including built in aspects)– Persistence layer – DAO template support for popular ORMs and

JDBC• Simplifies persistence frameworks and JDBC• Complimentary: Not a replacement for a persistence framework

• Helps organize your middle tier and handle typical J2EE plumbing problems.

• Reduces code and speeds up development

• Current Version is 1.1

Spring

Page 55: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 56 Gpower Software

Spring (continued)• Do I have to use all components of Spring?

• Spring is a non-invasive and portable framework that allows you to introduce as much or as little as you want to your application.

• Promotes decoupling and reusability

• POJO Based

• Allows developers to focus more on reused business logic and less on plumbing problems.

• Reduces or alleviates code littering, ad hoc singletons, factories, service locators and multiple configuration files.

• Removes common code issues like leaking connections and more.

• Built in aspects such as transaction management

• Most business objects in Spring apps do not depend on the Spring framework.

Page 56: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 57 Gpower Software

• Enables you to stop polluting code

• No more custom singleton objects– Beans are defined in a centralized configuration file

• No more custom factory object to build and/or locate other objects

• DAO simplification– Consistent CRUD– Data access templates– No more copy-paste try/catch/finally blocks– No more passing Connection objects between methods– No more leaked connections

• POJO Based

• Refactoring experience with Spring

Spring Benefits

Page 57: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 58 Gpower Software

Spring Features

Page 58: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 59 Gpower Software

Spring middle-tier using a third-party web framework

Page 59: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 60 Gpower Software

Remoting usage scenario

Page 60: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 61 Gpower Software

EJBs - Wrapping existing POJOs

Page 61: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 62 Gpower Software

• IoC container – Setter based and constructor based dependency injection– Portable across application servers– Promotes good use of OO practices such as programming to

interfaces.– Beans managed by an IoC container are reusable and decoupled

from business logic

• AOP– Spring uses Dynamic AOP Proxy objects to provide cross-cutting

services– Reusable components– Aopalliance support today– Integrates with the IoC container– AspectJ support in Spring 1.1

Spring IoC + AOP

Page 62: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 63 Gpower Software

• Inversion of Control/Dependency Injection– Beans do not depend on framework– Container injects the dependencies

• Spring lightweight container– Configure and manage beans

IoC/Dependency Injection

Page 63: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 64 Gpower Software

• Dependency injection– Beans define their dependencies through constructor

arguments or properties– The container provides the injection at runtime

• “Don’t talk to strangers”

• Also known as the Hollywood principle – “don’t call me I will call you”

• Decouples object creators and locators from application logic

• Easy to maintain and reuse

• Testing is easier

Inversion of Control

Page 64: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 65 Gpower Software

Inversion of Control

Girl want a boy friend

三种方式:1 青梅竹马; 2 亲友介绍; 3 父母包办

Page 65: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 66 Gpower Software

Inversion of Control

青梅竹马

public class Girl { void kiss(){ Boy boy = new Boy(); }}

Page 66: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 67 Gpower Software

Inversion of Control

亲友介绍

public class Girl { void kiss(){ Boy boy = BoyFactory.createBoy(); }}

Page 67: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 68 Gpower Software

Inversion of Control

父母包办

public class Girl { void kiss(Boy boy){ // kiss boy boy.kiss(); }}

Page 68: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 69 Gpower Software

Inversion of Control

Page 69: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 70 Gpower Software

Inversion of Control (Type 0)

public class Girl implements Servicable {

private Kissable kissable;

public Girl() {

kissable = new Boy();

}

public void kissYourKissable() {

kissable.kiss();

}

}

Page 70: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 71 Gpower Software

Inversion of Control (Type 1)

public class Girl implements Servicable {

Kissable kissable;

public void service(ServiceManager mgr) {

kissable = (Kissable) mgr.lookup(“kissable”);

}

public void kissYourKissable() {

kissable.kiss();

}

}

<container>    <component name=“kissable“ class=“Boy">                     <configuration> … </configuration>    </component>

    <component name=“girl" class=“Girl" /></container>

Page 71: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 72 Gpower Software

Inversion of Control (Type 2)

public class Girl {

private Kissable kissable;

public void setKissable(Kissable kissable) {

this.kissable = kissable;

}

public void kissYourKissable() {

kissable.kiss();

}

}

<beans>    <bean id=“boy" class=“Boy"/>    <bean id=“girl“ class=“Girl">        <property name=“kissable">           <ref bean=“boy"/>        </property>    </bean></beans>

Page 72: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 73 Gpower Software

Inversion of Control (Type 3)

public class Girl {

private Kissable kissable;

public Girl(Kissable kissable) {

this.kissable = kissable;

}

public void kissYourKissable() {

kissable.kiss();

}

}

PicoContainer container = new DefaultPicoContainer();container.registerComponentImplementation(Boy.class);container.registerComponentImplementation(Girl.class);Girl girl = (Girl) container.getComponentInstance(Girl.class);girl.kissYourKissable();

Page 73: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 74 Gpower Software

Spring Bean Definition

• The bean class is the actual implementation of the bean being described by the BeanFactory.

• Bean examples – DAO, DataSource, Transaction Manager, Persistence Managers, Service objects, etc

• Spring config contains implementation classes while your code should program to interfaces.

• Bean behaviors include:– Singleton or prototype– Autowiring– Initialization and destruction methods

• init-method• destroy-method

• Beans can be configured to have property values set. – Can read simple values, collections, maps, references to other beans,

etc.

Page 74: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 75 Gpower Software

Simple Spring Bean Example

• <bean id=“orderBean” class=“example.OrderBean” init-method=“init”><property

name=“minimumAmountToProcess”>10</property><property name=“orderDAO”> <ref bean=“orderDAOBean”/></property>

</bean>

• public class OrderBean implements IOrderBean{…public void setMinimumAmountToProcess(double

d){this. minimumAmountToProcess = d;

}public void setOrderDAO(IOrderDAO odao){

this.orderDAO = odao;}

}

Page 75: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 76 Gpower Software

Spring BeanFactory

• BeanFactory is core to the Spring framework– Lightweight container that loads bean definitions

and manages your beans.– Configured declaratively using an XML file, or files,

that determine how beans can be referenced and wired together.

– Knows how to serve and manage a singleton or prototype defined bean

– Responsible for lifecycle methods.– Injects dependencies into defined beans when

served

Page 76: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 77 Gpower Software

XMLBeanFactory

• Beanfactory Implementation

• Beans Definition<beans> <bean id="exampleBean" class="eg.ExampleBean"/> <bean id="anotherExample"

class="eg.ExampleBeanTwo"/></beans>

Page 77: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 78 Gpower Software

Usage Example

InputStream input = new FileInputStream("beans.xml");

BeanFactory factory = new XmlBeanFactory(input);

ExampleBean eb =

(ExampleBean)factory.getBean("exampleBean");

ExampleBeanTwo eb2 =

(ExampleBeanTwo)factory.getBean("anotherExample");

throw NoSuchBeanDefinitionException

ExampleBean eb = (ExampleBean)factory.getBean("exampleBean", ExampleBean.class);

throw BeanNotOfRequiredTypeException

Page 78: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 79 Gpower Software

Bean creation

• Via constructor– <bean id="exampleBean"

class="examples.ExampleBean"/>– <bean name="anotherExample"

class="examples.ExampleBeanTwo"/>

• Via static factory method– <bean id="exampleBean"

class="examples.ExampleBean2" factory-method="createInstance"/>

• Via instance factory method– <bean id="myFactoryBean" class="..."> ... </bean> – <!-- The bean to be created via the factory bean --> <bean

id="exampleBean" factory-bean="myFactoryBean" factory-method="createInstance"/>

Page 79: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 80 Gpower Software

Singleton or Non-singleton(prototype)

• <bean id="exampleBean"

class="examples.ExampleBean" singleton="false"/>

• <bean name="yetAnotherExample"

class="examples.ExampleBeanTwo" singleton="true"/>

Page 80: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 81 Gpower Software

Bean collaborators

public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

public void setBeanOne(AnotherBean b) { beanOne = b; }

public void setBeanTwo(YetAnotherBean b) { beanTwo = b; }

}

<bean id="exampleBean" class="eg.ExampleBean">

<property name="beanOne"><ref bean="anotherExampleBean"/></property>

<property name="beanTwo"><ref bean="yetAnotherBean"/></property>

</bean>

<bean id="anotherExampleBean" class="eg.AnotherBean"/>

<bean id="yetAnotherBean" class="eg.YetAnotherBean"/>

Page 81: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 82 Gpower Software

Bean Properties

public class ExampleBean {

private String s;

private int i;

public void setStringProperty(String s) { this.s = s; }

public void setIntegerProperty(int i) { this.i = i; }

}

<bean id="exampleBean" class="eg.ExampleBean">

<property name="stringProperty"><value>Hi!</value></property>

<property name="integerProperty"><value>1</value></property>

</bean>

Page 82: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 83 Gpower Software

Property Editor

• Convert String to objects

• Implement java.beans.PropertyEditor– getValue()/setValue(),getAsText()/setAsText()

• Standard Java– Bool, Byte, Color, Double, Float, Font, Int, Long, Short, String

• Standard Spring– Class, File, Locale, Properties, StringArray, URL

• Custom Spring– CustomBoolean, CustomDate, CustomNumber,StringTrimmer

Page 83: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 84 Gpower Software

Standard Property Editor

• Examples– <property name="intProperty"><value>7</value></property>– <property

name="doubleProperty"><value>0.25</value></property>– <property

name="booleanProperty"><value>true</value></property>– <property

name="colorProperty"><value>0,255,0</value></property>

java.awt.Color is initialized with RGB valuesjava.awt.Color is initialized with RGB values

Page 84: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 85 Gpower Software

Custom Property Editor

• Date ExampleDateFormat fmt = new SimpleDateFormat("d/M/yyyy");

CustomDateEditor dateEditor = new CustomDateEditor(fmt, false);

beanFactory.registerCustomEditor(java.util.Date.class, dateEditor);

<property name="date"><value>19/2/2004</value></property>

• StringTrimmer ExampleStringTrimmerEditor trimmer = new StringTrimmerEditor(true);

beanFactory.registerCustomEditor(java.lang.String.class, trimmer);

<property name="string1"><value> hello </value></property>

<property name="string2"><value></value></property>

<property name="string2"><null/></property>

Page 85: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 86 Gpower Software

Java.util.Properties

• Property Example<property name="propertiesProperty">

<value>

foo=1

bar=2

baz=3

</value>

</property>

<property name="propertiesProperty">

<props>

<prop key="foo">1</prop>

<prop key="bar">2</prop>

<prop key="baz">3</prop>

</props>

</property>

Page 86: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 87 Gpower Software

Java.util.List Set …

• List Example<property name="listProperty">

<list>

<value>a list element</value>

<ref bean="otherBean"/>

<ref bean="anotherBean"/>

</list>

</property>

Page 87: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 88 Gpower Software

Bean Factory for IOC Type 3

<bean id="exampleBean" class="examples.ExampleBean">

<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>

<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>

<constructor-arg><value>1</value></constructor-arg>

</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>

<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

private int i;

public ExampleBean(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

this.beanOne = anotherBean;

this.beanTwo = yetAnotherBean;

this.i = i;

}

}

Page 88: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 89 Gpower Software

Bean lifecycle

• Beans can be initialized by the factory before it first use

• public class ExampleBean {

• public void init() {

• // do some initialization work

• }

• }

• <bean id="exampleBean" class="eg.ExampleBean"

• init-method="init"/>

Page 89: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 90 Gpower Software

Bean lifecycle

• Beans can be cleaned up when not used anymore

• public class ExampleBean {

• public void cleanup() {

• // do some destruction work

• }

• }

• <bean id="exampleBean" class="eg.ExampleBean"

• destroy-method="cleanup"/>

Page 90: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 91 Gpower Software

PropertyPlaceholderConfigurer

• Merge properties from an external Properties file<bean id="dataSource"

class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<property name="driverClassName">

<value>${jdbc.driverClassName}</value>

</property>

<property name="url"><value>${jdbc.url}</value></property>

<property name="username"><value>${jdbc.username}</value></property>

<property name="password"><value>${jdbc.password}</value></property>

</bean>

jdbc.driverClassName=org.hsqldb.jdbcDriver

jdbc.url=jdbc:hsqldb:hsql://production:9002

jdbc.username=sa

jdbc.password=root

Jdbc.propertiesJdbc.properties

Page 91: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 92 Gpower Software

PropertyPlaceholderConfigurer

• Installing ConfigurerInputStream input = new FileInputStream("beans.xml");

XmlBeanFactory factory = new XmlBeanFactory(input);

Properties props = new Properties();

props.load(new FileInputStream("jdbc.properties"));

PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

cfg.setProperties(props);

cfg.postProcessBeanFactory(factory);

DataSource ds = (DataSource)factory.getBean("dataSource");

Page 92: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 93 Gpower Software

Advanced Features

• Autowiring

• Dependency checking

• BeanWrapper

• InitializingBean/DisposableBean

• BeanFactoryAware/BeanNameAware

Page 93: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 94 Gpower Software

Spring ApplicationContext

• A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner.

• ApplicationContext extends BeanFactory– Adds services such as international messaging capabilities.– Add the ability to load file resources in a generic fashion.

• Several ways to configure a context: – XMLWebApplicationContext – Configuration for a web

application.– ClassPathXMLApplicationContext – standalone XML

application context– FileSystemXmlApplicationContext

• Allows you to avoid writing Service Locators

Page 94: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 95 Gpower Software

Configuring an XMLWebApplicationContext

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/applicationContext.xml

</param-value>

</context-param>

<listener>

<listener-class> org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

Page 95: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 96 Gpower Software

Configuring an XMLWebApplicationContext

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/applicationContext.xml

</param-value>

</context-param>

<servlet>

<servlet-name>context</servlet-name>

<servlet-class> org.springframework.web.context.ContextLoaderServlet

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

Page 96: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 97 Gpower Software

AOP

• Complements OO programming

• Core business concerns vs. Crosscutting enterprise concerns

• Usages– Persistent– Transaction Management– Security– Logging– Debugging

Page 97: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 98 Gpower Software

AOP Concepts

• Aspect – Modularization of a concern

• Join point – Point during the execution of a program

• Advice – Action taken at a particular joinpoint

• Pointcut – Set of joinpoints when an advice should fire

• Introduction – Adding methiods of fields to an advised class.

• Target object – Object containing the joinpoint.

• Weaving – Assembling aspects to create an advised object.

Page 98: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 99 Gpower Software

AOP

Page 99: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 100 Gpower Software

Pointcut

• Set of joinpoints specifying when an advice should fire

public interface Pointcut {

ClassFilter getClassFilter();

MethodMatcher getMethodMatcher();

}

public interface ClassFilter {

boolean matches(Class clazz);

}

public interface MethodMatcher {

boolean matches(Method m, Class targetClass);

boolean matches(Method m, Class targetClass, Object[] args);

boolean isRuntime();

}

Restricts the pointcut to agiven set of target classesRestricts the pointcut to agiven set of target classes

Page 100: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 101 Gpower Software

Pointcut implementations

• Regexp

<bean id="gettersAndSettersPointcut"

class="org.springframework.aop.support.RegexpMethodPointcut">

<property name="patterns">

<list>

<value>.*\.get.*</value>

<value>.*\.set.*</value>

</list>

</property>

</bean>

Page 101: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 102 Gpower Software

Advices

• Action taken at a particular joinpoint

public interface MethodInterceptor extends Interceptor {

Object invoke(MethodInvocation invocation) throws Throwable;

}

Example

public class DebugInterceptor implements MethodInterceptor {

public Object invoke(MethodInvocation invocation)

throws Throwable {

System.out.println(">> " + invocation); // before

Object rval = invocation.proceed();

System.out.println("<< Invocation returned"); // after

return rval;

}

}

Spring implements an advice with aninterceptor chain around the jointpointSpring implements an advice with an

interceptor chain around the jointpoint

Page 102: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 103 Gpower Software

Advice types

• Around advice– The previous advice

• Before advuce

• Throws advice

• After returning advice

• Introduction advice

Page 103: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 104 Gpower Software

Spring Advisors• PointcutAdvisor= Pointcut + Advice.

• Each Built-in advice has a advisor

• Example<bean id="gettersAndSettersAdvisor"

class="...aop.support.RegexpMethodPointcutAroundAdvisor">

<property name="interceptor">

<ref local="interceptorBean"/>

</property>

<property name="patterns">

<list>

<value>.*\.get.*</value>

<value>.*\.set.*</value>

</list>

</property>

</bean>

Page 104: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 105 Gpower Software

ProxyFactory

• With a ProxyFactory you get advised objects– You can define pointcuts and advices that will be applied– It returns an interceptor as a proxy object– It uses Java Dynamic Proxy or CGLIB2

• It can proxy interfaces or classes

• Creating AOP proxies programmaticallyProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);

factory.addInterceptor(myMethodInterceptor);

factory.addAdvisor(myAdvisor);

MyBusinessInterface b = (MyBusinessInterface)factory.getProxy();</bean>

Page 105: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 106 Gpower Software

ProxyFactoryBean

• Used to get proxies for beans

• The bean to be proxied<bean id="personTarget" class="eg.PersonImpl">

<property name="name"><value>Tony</value></property>

<property name="age"><value>51</value></property>

</bean> PersonImpl implements Person interface

Page 106: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 107 Gpower Software

ProxyFactoryBean• The interceptors/advisors<bean id="myAdvisor" class="eg.MyAdvisor">

<property name="someProperty"><value>Something</value></property>

</bean>

<bean id="debugInterceptor" class="...aop.interceptor.NopInterceptor">

</bean>

• The proxy<bean id="person" class="...aop.framework.ProxyFactoryBean">

<property name="proxyInterfaces"><value>eg.Person</value></property>

<property name="target"><ref local="personTarget"/></property>

<property name="interceptorNames">

<list>

<value>myAdvisor</value>

<value>debugInterceptor</value>

</list>

</property>

</bean>

Page 107: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 108 Gpower Software

ProxyFactoryBean

• Using the bean– Clients should get the person bean instead of personTarget– Can be accessed in the application context or

programmatically

<bean id="personUser" class="com.mycompany.PersonUser">

<property name="person"><ref local="person" /></property>

</bean>

Person person = (Person) factory.getBean("person");

Page 108: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 109 Gpower Software

ProxyFactoryBean• If you need to proxy a class instead of an interafce

– Set the property proxyTargetClass to true, instead of proxyInterfaces

– Proxy will extend the target class• Constructed by CGLIB

<bean id="person" class="...aop.framework.ProxyFactoryBean">

<property name="proxyTargetClass"><value>true</value></property>

<property name="target"><ref local="personTarget"/></property>

<property name="interceptorNames">

<list>

<value>myAdvisor</value>

<value>debugInterceptor</value>

</list>

</property>

</bean>

Page 109: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 110 Gpower Software

AutoProxy

• Automatic proxy creation– Just declare the targets– Selected beans will be automatically

proxied

• No need to use a ProxyFactoryBean for each target bean

Page 110: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 111 Gpower Software

BeanNameAutoProxyCreator

• Select targets by bean name<bean id="employee1" class="eg.Employee">...</bean>

<bean id="employee2" class="eg.Employee">...</bean>

<bean id="myInterceptor" class="eg.DebugInterceptor"/>

<bean id="beanNameProxyCreator"

class="...aop.framework.autoproxy.BeanNameAutoProxyCreator">

<property name="beanNames"><value>employee*</value></property>

<property name="interceptorNames">

<list>

<value>myInterceptor</value>

</list>

</property>

</bean>

Page 111: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 112 Gpower Software

AdvisorAutoProxyCreator

• Automatic applies advisors in context to beans– Each dvisor has a pointcut and an

advice– If a pointcut applies to a bean it will

be intercepted by the advice

• Useful to apply the same advice consistently to many business objects

• Impossible to get an un-advised object

Page 112: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 113 Gpower Software

AdvisorAutoProxyCreator

• Example<bean id="debugInterceptor" class="app.DebugInterceptor"/>

<bean id="getterDebugAdvisor"

class="...aop.support.RegexpMethodPointcutAdvisor">

<constructor-arg>

<ref bean="debugInterceptor"/>

</constructor-arg>

<property name="pattern"><value>.*\.get.*</value></property>

</bean>

<bean id="autoProxyCreator"

class="...aop.framework.autoproxy.AdvisorAutoProxyCreator">

<property name="proxyTargetClass"><value>true</value></property>

</bean>

This advisor applies debugInterceptor to all get methods of any class

This advisor applies debugInterceptor to all get methods of any class

Page 113: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 114 Gpower Software

AOP Weaving

Page 114: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

Spring Framework

Integration

Page 115: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 116 Gpower Software

Mail

• Creating messageSimpleMailMessage msg = new SimpleMailMessage();

msg.setFrom("[email protected]");

msg.setTo("[email protected]");

msg.setCc(new String[] {"[email protected]", "[email protected]"});

msg.setBcc(new String[] {"[email protected]", "[email protected]"});

msg.setSubject("my subject");

msg.setText("my text");

Page 116: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 117 Gpower Software

Mail->MessageSender

• Defining a message sender<bean id="mailSender"

class="org.springframework.mail.javamail.JavaMailSenderImpl">

<property name="host"><value>smtp.mail.org</value></property>

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

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

</bean>

• Sending the messageMailSender sender = (MailSender) ctx.getBean("mailSender");

sender.send(msg);

Page 117: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 118 Gpower Software

Scheduling

• Built in support for – Java 2 Timer

• Timer• TimerTask

– Quartz• Schedulers• JobDetails• Triggers

Page 118: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 119 Gpower Software

Scheduling->Timer Task

• The task that we want to runpublic class MyTask extends TimerTask {

public void run() {

// do something

}

}

<bean id="myTask"

class="...scheduling.timer.ScheduledTimerTask">

<property name="timerTask">

<bean class="eg.MyTask"/>

</property>

<property name="delay"><value>60000</value></property>

<property name="period"><value>1000</value></property>

</bean>

Java bean that wraps a scheduledjava.util.TimerTask

Java bean that wraps a scheduledjava.util.TimerTask

Page 119: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 120 Gpower Software

Scheduling->TimerFactoryBean

• Creating the schedule<bean id="scheduler"

class="...scheduling.timer.TimerFactoryBean">

<property name="scheduledTimerTasks">

<list><ref bean="myTask"/></list>

</property>

</bean>

• The Timer starts at bean creation time

Creates a java.util.Timer objectCreates a java.util.Timer object

Page 120: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 121 Gpower Software

JDBC

• Make JDBC easier to use and less error prone

• Framework handles the creation and release resources

• Framework takes care of all exception handling

Page 121: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 122 Gpower Software

JDBC->JdbcTemplate

• Execute SQL Queries, update statements or stored procedure calls

• Iteration over ResultSets and extraction of returned parameter values

• ExampleDataSource ds =

DataSourceUtils.getDataSourceFromJndi("MyDS");

JdbcTemplate jdbc = new JdbcTemplate(ds);

jdbc.execute("drop table TEMP");

jdbc.update("update EMPLOYEE set FIRSTNME=? where LASTNAME=?",

new String[] {"JOE", "LEE"});

Page 122: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 123 Gpower Software

JDBC->JdbcTemplate

• Queries, using convenience methodsint maxAge = jdbc.queryForInt("select max(AGE)

from EMPLOYEE");

String name = (String)jdbc.queryForObject(

"select FIRSTNME from EMPLOYEE where LASTNAME='LEE'",

String.class);

List employees = jdbc.queryForList(

"select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE");Returns an ArrayList (one entry for each row) of HashMaps

(one entry for each column using the column name as the key)Returns an ArrayList (one entry for each row) of HashMaps

(one entry for each column using the column name as the key)

Page 123: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 124 Gpower Software

JDBC->JdbcTemplate

• Queries, using callback methodfinal List employees = new LinkedList();

jdbc.query("select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE",

new RowCallbackHandler() {

public void processRow(ResultSet rs) throws SQLException {

Employee e = new Employee();

e.setEmpNo(rs.getString(1));

e.setFirstName(rs.getString(2));

e.setLastName(rs.getString(3));

employees.add(e);

}

}

);

employees list will be populated with Employee objectsemployees list will be populated with Employee objects

Page 124: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 125 Gpower Software

Hibernate

• Define a DataSource and an Hibernate SessionFactory<bean id="dataSource" ...> ... </bean>

<bean id="sessionFactory" class="...LocalSessionFactoryBean">

<property name="mappingResources">

<list>

<value>employee.hbm.xml</value>

</list>

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">....DB2Dialect</prop>

</props>

</property>

<property name="dataSource">

<ref bean="dataSource"/>

</property>

</bean>

Page 125: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 126 Gpower Software

HibernateTemplate

• Create HibernateTemplateSessionFactory sessionFactory =

(SessionFactory) ctx.getBean("sessionFactory");

HibernateTemplate hibernate =

new HibernateTemplate(sessionFactory);

• Load and updateEmployee e = (Employee) hibernate.load(Employee.class,

"000330");

e.setFirstName("BOB");

hibernate.update(e);

Page 126: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 127 Gpower Software

HibernateTemplate

• Queries, using convenience methodsList employees = hibernate.find("from app.Employee");

List list = hibernate.find(

"from app.Employee e where e.lastName=?",

"LEE",

Hibernate.STRING);

List list = hibernate.find(

"from app.Employee e where e.lastName=? and e.firstName=?",

new String[] { "BOB", "LEE" },

new Type[] {Hibernate.STRING , Hibernate.STRING });

Page 127: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 128 Gpower Software

HibernateTemplate

• Queries, using callback methodsList list = (List) hibernate.execute(

new HibernateCallback() {

public Object doInHibernate(Session session) throws HibernateException {

List result = session.find("from app.Employee");

/ / do some further stuff with the result list

return result;

}

}

);

Page 128: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 129 Gpower Software

Transactions

• What is Distributed Transaction? Transaction spans more than one resource

Transaction Manager as the coordinator

Distributed Transaction Manager

Local Transaction Manager

Local Transaction Manager

Resource ManagerResource Manager Resource ManagerResource Manager

DatabaseDatabase DatabaseDatabase

Resource ManagerResource Manager

Messaging ServerMessaging Server

Page 129: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 130 Gpower Software

Spring Solution

• Use the same programming model for global or local transactions

• Transaction management can be– Programmatic– Declarative

• Four transaction managers available– DataSourceTransactionManager – HibernateTransactionManager– JdoTransactionManager– JtaTransactionManager

Page 130: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 131 Gpower Software

Examples

• Defining a JtaTransactionManager<bean id="dataSource"

class="...jndi.JndiObjectFactoryBean">

<property name="jndiName"><value>MyDS</value></property>

</bean>

<bean id="transactionManager"

class="...transaction.jta.JtaTransactionManager"/>

Page 131: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 132 Gpower Software

Examples

• Defining a HibernateTransactionManager<bean id="sessionFactory"

class="...orm.hibernate.LocalSessionFactoryBean">

...

</bean>

<bean id="transactionManager"

class="...orm.hibernate.HibernateTransactionManager">

<property name="sessionFactory">

<ref local="sessionFactory"/>

</property>

</bean>

Page 132: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 133 Gpower Software

Declarative transactions

• No need of TransactionTemplate

• Implemented using Spring AOP

• Simliar to EJB CMT– You specify transaction behaviour (or lack of it)

down to individual methods

Page 133: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 134 Gpower Software

<bean id=“mySessionFactory" class=

“org.springframework.orm.hibernate.LocalSessionFactoryBean“><property name="mappingResources">

<list> <value>com/matrix/bo/Order.hbm.xml</value>

<value>com/matrix/bo/OrderLineItem.hbm.xml</value></list>

</property><property name="hibernateProperties">

<props><prop key="hibernate.dialect">

net.sf.hibernate.dialect.DB2Dialect</prop><prop key="hibernate.default_schema">DB2ADMIN</prop><prop key="hibernate.show_sql">false</prop><prop key="hibernate.proxool.xml">

/WEB-INF/proxool.xml</prop><prop

key="hibernate.proxool.pool_alias">spring</prop></props>

</property>

</bean>

Wiring your Persistence Layer

Page 134: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 135 Gpower Software

<bean id=“myTransactionManager" class="org

.springframework

.orm

.hibernate

.HibernateTransactionManager">

<property name=“sessionFactory">

<ref local=“mySessionFactory"/>

</property>

</bean>

Wiring your Transaction Management

Page 135: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 136 Gpower Software

<bean id=“orderService" class="org.springframework.transaction.

interceptor.TransactionProxyFactoryBean">

<property name="transactionManager">

<ref local=“myTransactionManager"/>

</property>

<property name="target"><ref local=“orderTarget"/></property>

<property name="transactionAttributes"><props>

<prop key="find*">PROPAGATION_REQUIRED,readOnly,-OrderException

</prop> <prop key="save*">

PROPAGATION_REQUIRED,-OrderMinimumAmountException </prop> <prop key="update*">

PROPAGATION_REQUIRED,-OrderException </prop>

</props>

</property>

</bean>

Wiring a Service Object

Page 136: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 137 Gpower Software

public class OrderServiceSpringImpl implements IOrderService {

private IOrderDAO orderDAO;

// service methods…

public void setOrderDAO(IOrderDAO orderDAO) {

this.orderDAO = orderDAO;

}

}

Defining a Target to Proxy

Page 137: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 138 Gpower Software

<bean id=“orderTarget" class="com.meagle.service.spring.OrderServiceSpringImpl">

<property name=“orderDAO">

<ref local=“orderDAO"/>

</property>

</bean>

<bean id=“orderDAO" class="com.meagle.dao.hibernate.OrderHibernateDAO">

<property name="sessionFactory">

<ref local=“mySessionFactory"/>

</property>

</bean>

Wiring a Service Object (cont’)

Page 138: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 139 Gpower Software

Final Result

Page 139: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 140 Gpower Software

• Spring has it’s own exception handling hierarchy for DAO logic.

• No more copy and pasting redundant exception logic!

• Exceptions from JDBC, or a supported ORM, are wrapped up into an appropriate, and consistent, DataAccessException and thrown.

• This allows you to decouple exceptions in your business logic.

• These exceptions are treated as unchecked exceptions that you can handle in your business tier if needed. No need to try/catch in your DAO.

• Define your own exception translation by subclassing classes such as SQLErrorCodeSQLExceptionTranslator

Consistent Exception Handling

Page 140: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 141 Gpower Software

• Traditional J2EE development with EJB will become more POJO based with EJB 3.0

• Lightweight IoC container support will become more popular

• Future versions of J2EE will resemble frameworks like Spring and Hibernate for business logic and persistence logic respectively.– EJB 3.0 ~ (Spring + Hibernate)

• AOP is gaining momentum as an alternative to providing enterprise services

• Annotations will be helpful for applying AOP advice – J2SE 1.5

• IoC + AOP is a great non-invasive combination.

• If you are considering EJB 3.0 - Spring will make an easier migration path

Future Trends and Predictions

Page 141: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 142 Gpower Software

AOP Proxies

Page 142: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 143 Gpower Software

Spring+Hibernate Entity Enginee

Page 143: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 144 Gpower Software

• Examples– ContentService 内容服务接口 继承 EntityService– ContentServiceImpl 内容服务接口实现 继承 EntityServiceImpl ,实现

ContentService 接口– ContentDao 内容实体操作 继承 EntityDao– ContentDaoImpl 内容实体操作实现 继承 EntityDaoImpl ,实现 ContentDao

接口

Entity Enginee

Page 144: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 145 Gpower Software

• Examples

<bean id="contentDaoTarget" class="com.gpower.services.content.dao.ContentDaoImpl">

<property name="sessionFactory"> <ref bean="sessionFactory"/> </property></bean><bean id="contentDao"

class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>com.gpower.services.content.dao.ContentDao</value> </property> <property name="interceptorNames"> <list> <value>hibernateInterceptor</value> <value>contentDaoTarget</value> </list> </property></bean>

Entity Enginee

Page 145: Framework Concepts. Gpower Software 1 - 2 The enterprise challenge

1 - 146 Gpower Software

• Examples

<!-- Transactional proxy for the Application primary business object --><bean id="contentServiceTarget" class="com.gpower.services.content.ContentServiceImpl"> <property name="siteDao"> <ref bean="siteDao"/> </property> <property name="contentDao"> <ref bean="contentDao"/> </property> <property name="entityDao"> <ref bean="entityDao"/> </property></bean><bean id="contentService"

class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="target"> <ref bean="contentServiceTarget"/> </property> <property name="transactionAttributes">

<props> <prop key="get*">PROPAGATION_SUPPORTS</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props>

</property></bean>

Entity Enginee