Title: Framework
1Framework
2The enterprise challenge
3How 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
Business Application
Business Application
Database
Business Application
Business Application
Flexible foundation
4Component based solutions
5What 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 Taligents definition
With framework-oriented programming, software
development is one step closer towards a factory
mode of operation
6What 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
7Framework reduces development time
Time/EffortMan days
Without Framework
With Framework
3X
X
Business Functions
0
Large Scale Application Development
Small ScaleApplication development
8Framework reduces development time
3
-
5 Months
6
-
9 Months
Integration
Development Time (months)
Coding
Design
Requirement
With Framework
Without Framework
Statistics from Java World report
-
9Hibernate
10Hibernate Introduction
- Why object/relational mapping?
- Solving the mismatch with tools
- Basic Hibernate features
- Hibernate Query Options
- Detached Objects
11Hibernate Introduction
- The Structural Mismatch.
- Java types vs. SQL datatypes
- user-defined types (UDT) are in SQL1999
- current products are proprietary
- Type inheritance
- no common inheritance model
- Entity relationships.
12Hibernate Introduction
- 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
13Hibernate Introduction
- Why ORM
- Structural mapping more robust
- Less error-prone code
- Optimized performance all the time
- Vendor independence
14Hibernate Introduction
- What do RDBs do well?
- Work with large amounts of data
- Searching, sorting
- Work with sets of data
- Joining, aggregating
- Sharing
- Concurrency (Transactions)
- Many applications
- Integrity
- Constraints
- Transaction isolation
15Hibernate Introduction
- What do RDBs do badly?
- Modeling
- No polymorphism
- Fine grained models are difficult
- Business logic
- Stored procedures really bad
16Hibernate Introduction
- The Goal
- Take advantage of those things that relational
databases do well - Without leaving the language of objects / classes
17Hibernate Introduction
- Hibernate
- Opensource (LGPL)
- Mature
- Popular (15,000 downloads/month)
- Custom API
- Will be core of JBoss CMP 2.0 engine
18Hibernate Introduction
- 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
19Hibernate High Level Architecture
20Hibernate Full Cream Architecture
21Conception
- 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.
22Hibernate Mapping
23Hibernate Mapping
- Persistent Class
- JavaBean specification (or POJOs)
- No-arg constructor
- Accessor methods for properties
- Collection property is an interface
- Identifier property
public class AuctionItem private Long
_id private Set _bids private Bid
_successfulBid private String _description pub
lic Long getId() return _id private
void setId(Long id) _id id public
String getDescription() return
_description public void setDescription(Strin
g desc) _descriptiondesc
24Hibernate Mapping
- XML Mapping
- Readable metadata
- Column/table mappings
- Surrogate key generation strategy
- Collection metadata
- Fetching strategies
ltclass nameAuctionItem tableAUCTION_ITEMgt lt
id nameid columnITEM_IDgt ltgenerator
classnative/gt lt/idgt ltproperty
namedescription columnDESCR/gt ltmany-to-one
namesuccessfulBid columnSUCCESSFUL_BID_ID/gt
ltset namebids cascadeall lazytruegt
ltkey columnITEM_ID/gt ltone-to-many
classBid/gt lt/setgt lt/classgt
25Basic O/R Mapping
- Class
-
- ltclass
- name"ClassName"
- table"tableName"
- discriminator-value"discriminator_value"
- mutable"truefalse"
- schema"owner"
- proxy"ProxyInterface"
- dynamic-update"truefalse"
- dynamic-insert"truefalse"
- select-before-update"truefalse"
- polymorphism"implicitexplicit"
- where"arbitrary sql where condition"
- persister"PersisterClass"
- batch-size"N"
- optimistic-lock"noneversiondirtyall"
- lazy"truefalse"
- /gt
26Basic O/R Mapping
- ID
- ltid
- name"propertyName"
- type"typename"
- column"column_name"
- unsaved-value"anynonenullid_value"
- access"fieldpropertyClassName"gt
- ltgenerator class"generatorClass"/gt
- lt/idgt
- Generator
- Increment, sequence, hilo, seqhilo, uuid.hex,
native, assigned, foreign
27Basic O/R Mapping
- Composite-id
- ltcomposite-id
- name"propertyName"
- class"ClassName"
- unsaved-value"anynone"
- access"fieldpropertyClassName"gt
- ltkey-property name"propertyName"
type"typename" column"column_name"/gt - ltkey-many-to-one name"propertyName
class"ClassName" column"column_name"/gt - ......
- lt/composite-idgt
28Basic O/R Mapping
- Property
- ltproperty
- name"propertyName"
- column"column_name"
- type"typename"
- update"truefalse"
- insert"truefalse"
- formula"arbitrary SQL expression"
- access"fieldpropertyClassName"
- /gt
29Basic O/R Mapping
- Many to one
- ltmany-to-one
- name"propertyName"
- column"column_name"
- class"ClassName"
- cascade"allnonesave-updatedelete"
- outer-join"truefalseauto"
- update"truefalse"
- insert"truefalse"
- property-ref"propertyNameFromAssociatedCl
ass" - access"fieldpropertyClassName"
- unique"truefalse"
- /gt
- One to one
- ltone-to-one
- name"propertyName"
- class"ClassName"
- cascade"allnonesave-updatedelete"
- constrained"truefalse"
30Basic O/R Mapping
- Collection (ltsetgt, ltlistgt, ltmapgt, ltbaggt, ltarraygt)
- ltmap
- name"propertyName"
- table"table_name"
- schema"schema_name"
- lazy"truefalse"
- inverse"truefalse"
- cascade"allnonesave-updatedeleteall-delet
e-orphan" - sort"unsortednaturalcomparatorClass"
- order-by"column_name ascdesc"
- where"arbitrary sql where condition"
- outer-join"truefalseauto"
- batch-size"N"
- access"fieldpropertyClassName"
- gt
- ltkey .... /gt
- ltindex .... /gt
31Basic O/R Mapping
- Many-to-many
- ltmany-to-many
- column"column_name"
- class"ClassName"
- outer-join"truefalseauto"
- /gt
32Object state
- Transient Objects
- Objects instantiated using the new operator
arent immediately persistent. Their state is
transient, which means they arent associated
with any database table row, and so their state
is lost as soon as theyre 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 theyre no
longer under the management of Hibernate.
33Object Lifecycle
34Typical 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()
35Hibernate Introduction
- 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()
36Hibernate Introduction
- 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()
37Hibernate Introduction
- 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()
38Hibernate Introduction
- Hibernate query options
- Hibernate Query Language (HQL)
- minimal object-oriented dialect of ANSI SQL
- Criteria Queries
- Extensible framework for expressing query
criteria as objects - Includes query by example
- Native SQL queries
- Direct passthrough with automatic mapping
- Named SQL queries in metadata
39Hibernate Introduction
- Hibernate Query Language
- Make 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
40Hibernate Introduction
- HQL Example
- Simple
- from AuctionItem
- i.e. get all the AuctionItems
- List allAuctions session.createQuery(from
AuctionItem).list() - More realistic example
- select item
- from AuctionItem item
- join item.bids bid
- where item.description like hibernate
- and bid.amount gt 100
- i.e. get all the AuctionItems with a Bid worth gt
100 and description that begins with hibernate
41Hibernate Introduction
- 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 item
- left join fetch item.bids
- where item.description like description
- and item.successfulbid.amount gt minAmount
42Hibernate Introduction
- 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 item
- join item.bids bid
- where item.description like hib
- and bid.amount gt 1.0
43Hibernate Introduction
- 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)
44Hibernate Introduction
- Composing Objects
- Address of a User
- Address depends on User
ltclass nameUser tableUSERgt ltcomponent
nameaddressgt ltproperty namestreet
columnSTREET/gt ltproperty namezipCode
columnZIPCODE/gt ltproperty namecity
columnCITY/gt lt/componentgt lt/classgt
45Hibernate Introduction
- Layer Communication
- The presentation layer is decoupled from the
service layer and business logic
Presentation Layer
Remote?
DTO?
Service Layer
Domain Objects
46Hibernate Introduction
- DTOs are Evil
- Useless extra LOC
- Not objects (no behavior)
- Parallel class hierarchies smell
- Shotgun change smell
- Solution detached object support
47Hibernate Introduction
- Detached Object Support
- For applications using servlets session beans
- You dont need to select a row when you only want
to update it! - You dont 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)
48Hibernate Introduction
49Spring Framework
50Application Layering
- 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
51Application 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.
52Proposed Web App Layering
53More Application Layering Combinations
- Presentation/Business/Persistence
- StrutsSpringHibernate
- Struts Spring EJB
- JavaServer Faces Spring iBATIS
- Spring Spring JDO
- Flex Spring Hibernate
- Struts Spring JDBC
- You decide
54EJB (lt2.x) in the Service Layer
- Suns 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
55Spring
- 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
56Spring (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.
57Spring Benefits
- 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
58Spring Features
59Spring middle-tier using a third-party web
framework
60Remoting usage scenario
61EJBs - Wrapping existing POJOs
62Spring IoC AOP
- 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
63IoC/Dependency Injection
- Inversion of Control/Dependency Injection
- Beans do not depend on framework
- Container injects the dependencies
- Spring lightweight container
- Configure and manage beans
64Inversion of Control
- Dependency injection
- Beans define their dependencies through
constructor arguments or properties - The container provides the injection at runtime
- Dont talk to strangers
- Also known as the Hollywood principle dont
call me I will call you - Decouples object creators and locators from
application logic - Easy to maintain and reuse
- Testing is easier
65Inversion of Control
Girl want a boy friend
???? 1 ???? 2 ???? 3 ????
66Inversion of Control
????
public class Girl void kiss() Boy
boy new Boy()
67Inversion of Control
????
public class Girl void kiss() Boy
boy BoyFactory.createBoy()
68Inversion of Control
????
public class Girl void kiss(Boy boy)
// kiss boy boy.kiss()
69Inversion of Control
70Inversion of Control (Type 0)
public class Girl implements Servicable
private Kissable kissable public Girl()
kissable new Boy() public
void kissYourKissable()
kissable.kiss()
71Inversion 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() ltcontainergt
ltcomponent namekissable classBoy"gt
ltconfigurationgt lt/configurationgt
lt/componentgt ltcomponent namegirl"
classGirl" /gtlt/containergt
72Inversion of Control (Type 2)
- public class Girl
- private Kissable kissable
- public void setKissable(Kissable kissable)
- this.kissable kissable
-
- public void kissYourKissable()
- kissable.kiss()
-
-
- ltbeansgt ltbean idboy" classBoy"/gt
ltbean idgirl classGirl"gt ltproperty
namekissable"gt ltref
beanboy"/gt lt/propertygt
lt/beangtlt/beansgt
73Inversion 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.registerComponen
tImplementation(Boy.class)container.registerComp
onentImplementation(Girl.class)Girl girl
(Girl) container.getComponentInstance(Girl.class)
girl.kissYourKissable()
74Spring 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.
75Simple Spring Bean Example
- ltbean idorderBean classexample.OrderBean
init-methodinitgt ltproperty
nameminimumAmountToProcessgt10lt/propertygt ltpro
perty nameorderDAOgt ltref beanorderDAOBean
/gt lt/propertygtlt/beangt - public class OrderBean implements
IOrderBean public void setMinimumAmountToPro
cess(double d) this. minimumAmountToProcess
d public void setOrderDAO(IOrderDAO
odao) this.orderDAO odao
76Spring 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
77XMLBeanFactory
- Beanfactory Implementation
- Beans Definition
- ltbeansgt
- ltbean id"exampleBean" class"eg.ExampleBean"/
gt - ltbean id"anotherExample" class"eg.ExampleBea
nTwo"/gt - lt/beansgt
78Usage 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("exa
mpleBean", ExampleBean.class) - throw BeanNotOfRequiredTypeException
79Bean creation
- Via constructor
- ltbean id"exampleBean" class"examples.ExampleBean
"/gt - ltbean name"anotherExample" class"examples.Exampl
eBeanTwo"/gt - Via static factory method
- ltbean id"exampleBean" class"examples.ExampleBean
2" factory-method"createInstance"/gt - Via instance factory method
- ltbean id"myFactoryBean" class"..."gt ... lt/beangt
- lt!-- The bean to be created via the factory bean
--gt ltbean id"exampleBean" factory-bean"myFactory
Bean" factory-method"createInstance"/gt
80Singleton or Non-singleton(prototype)
- ltbean id"exampleBean"
- class"examples.ExampleBean"
singleton"false"/gt - ltbean name"yetAnotherExample"
- class"examples.ExampleBeanTwo"
singleton"true"/gt
81Bean collaborators
- public class ExampleBean
- private AnotherBean beanOne
- private YetAnotherBean beanTwo
- public void setBeanOne(AnotherBean b)
beanOne b - public void setBeanTwo(YetAnotherBean b)
beanTwo b -
- ltbean id"exampleBean" class"eg.ExampleBean"gt
- ltproperty name"beanOne"gtltref bean"anotherExample
Bean"/gtlt/propertygt - ltproperty name"beanTwo"gtltref bean"yetAnotherBean
"/gtlt/propertygt - lt/beangt
- ltbean id"anotherExampleBean" class"eg.AnotherBea
n"/gt - ltbean id"yetAnotherBean" class"eg.YetAnotherBean
"/gt
82Bean 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 -
- ltbean id"exampleBean" class"eg.ExampleBean"gt
- ltproperty name"stringProperty"gtltvaluegtHi!lt/val
uegtlt/propertygt - ltproperty name"integerProperty"gtltvaluegt1lt/valu
egtlt/propertygt - lt/beangt
83Property 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,StringTrim
mer
84Standard Property Editor
- Examples
- ltproperty name"intProperty"gtltvaluegt7lt/valuegtlt/pro
pertygt - ltproperty name"doubleProperty"gtltvaluegt0.25lt/value
gtlt/propertygt - ltproperty name"booleanProperty"gtltvaluegttruelt/valu
egtlt/propertygt - ltproperty name"colorProperty"gtltvaluegt0,255,0lt/val
uegtlt/propertygt
java.awt.Color is initialized with RGB values
85Custom Property Editor
- Date Example
- DateFormat fmt new SimpleDateFormat("d/M/yyyy")
- CustomDateEditor dateEditor new
CustomDateEditor(fmt, false) - beanFactory.registerCustomEditor(java.util.Date.cl
ass, dateEditor) - ltproperty name"date"gtltvaluegt19/2/2004lt/valuegtlt/pr
opertygt - StringTrimmer Example
- StringTrimmerEditor trimmer new
StringTrimmerEditor(true) - beanFactory.registerCustomEditor(java.lang.String.
class, trimmer) - ltproperty name"string1"gtltvaluegt hello
lt/valuegtlt/propertygt - ltproperty name"string2"gtltvaluegtlt/valuegtlt/property
gt - ltproperty name"string2"gtltnull/gtlt/propertygt
86Java.util.Properties
- Property Example
- ltproperty name"propertiesProperty"gt
- ltvaluegt
- foo1
- bar2
- baz3
- lt/valuegt
- lt/propertygt
- ltproperty name"propertiesProperty"gt
- ltpropsgt
- ltprop key"foo"gt1lt/propgt
- ltprop key"bar"gt2lt/propgt
- ltprop key"baz"gt3lt/propgt
- lt/propsgt
- lt/propertygt
87Java.util.List Set
- List Example
- ltproperty name"listProperty"gt
- ltlistgt
- ltvaluegta list elementlt/valuegt
- ltref bean"otherBean"/gt
- ltref bean"anotherBean"/gt
- lt/listgt
- lt/propertygt
88Bean Factory for IOC Type 3
- ltbean id"exampleBean" class"examples.ExampleBean
"gt - ltconstructor-arggtltref bean"anotherExampleBean
"/gtlt/constructor-arggt - ltconstructor-arggtltref bean"yetAnotherBean"/gtlt
/constructor-arggt - ltconstructor-arggtltvaluegt1lt/valuegtlt/constructor
-arggt - lt/beangt
- ltbean id"anotherExampleBean" class"examples.Anot
herBean"/gt - ltbean id"yetAnotherBean" class"examples.YetAnoth
erBean"/gt - 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
-
89Bean lifecycle
- Beans can be initialized by the factory before it
first use - public class ExampleBean
- public void init()
- // do some initialization work
-
-
- ltbean id"exampleBean" class"eg.ExampleBean"
- init-method"init"/gt
90Bean lifecycle
- Beans can be cleaned up when not used anymore
- public class ExampleBean
- public void cleanup()
- // do some destruction work
-
-
- ltbean id"exampleBean" class"eg.ExampleBean"
- destroy-method"cleanup"/gt
91PropertyPlaceholderConfigurer
- Merge properties from an external Properties file
- ltbean id"dataSource"
- class"org.apache.commons.dbcp.BasicDataSource"
- destroy-method"close"gt
- ltproperty name"driverClassName"gt
- ltvaluegtjdbc.driverClassNamelt/valuegt
- lt/propertygt
- ltproperty name"url"gtltvaluegtjdbc.urllt/valuegtlt/p
ropertygt - ltproperty name"username"gtltvaluegtjdbc.usernamelt
/valuegtlt/propertygt - ltproperty name"password"gtltvaluegtjdbc.passwordlt
/valuegtlt/propertygt - lt/beangt
- jdbc.driverClassNameorg.hsqldb.jdbcDriver
- jdbc.urljdbchsqldbhsql//production9002
- jdbc.usernamesa
- jdbc.passwordroot
Jdbc.properties
92PropertyPlaceholderConfigurer
- Installing Configurer
- InputStream 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("dataS
ource")
93Advanced Features
- Autowiring
- Dependency checking
- BeanWrapper
- InitializingBean/DisposableBean
- BeanFactoryAware/BeanNameAware
94Spring 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
95Configuring an XMLWebApplicationContext
- ltcontext-paramgt
- ltparam-namegtcontextConfigLocationlt/param-namegt
- ltparam-valuegt
- /WEB-INF/applicationContext.xml
- lt/param-valuegt
- lt/context-paramgt
- ltlistenergt
- ltlistener-classgt org.springframework.web.context.
ContextLoaderListener - lt/listener-classgt
- lt/listenergt
96Configuring an XMLWebApplicationContext
- ltcontext-paramgt
- ltparam-namegtcontextConfigLocationlt/param-namegt
- ltparam-valuegt
- /WEB-INF/applicationContext.xml
- lt/param-valuegt
- lt/context-paramgt
- ltservletgt
- ltservlet-namegtcontextlt/servlet-namegt
- ltservlet-classgt org.springframework.web.context.C
ontextLoaderServlet - lt/servlet-classgt
- ltload-on-startupgt1lt/load-on-startupgt
- lt/servletgt
97AOP
- Complements OO programming
- Core business concerns vs. Crosscutting
enterprise concerns - Usages
- Persistent
- Transaction Management
- Security
- Logging
- Debugging
98AOP 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.
99AOP
100Pointcut
- 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 a given set of target
classes
101Pointcut implementations
- Regexp
- ltbean id"gettersAndSettersPointcut"
- class"org.springframework.aop.support.RegexpMetho
dPointcut"gt - ltproperty name"patterns"gt
- ltlistgt
- ltvaluegt.\.get.lt/valuegt
- ltvaluegt.\.set.lt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
102Advices
- 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("gtgt " invocation) //
before - Object rval invocation.proceed()
- System.out.println("ltlt Invocation
returned") // after - return rval
-
-
Spring implements an advice with an interceptor
chain around the jointpoint
103Advice types
- Around advice
- The previous advice
- Before advuce
- Throws advice
- After returning advice
- Introduction advice
104Spring Advisors
- PointcutAdvisor Pointcut Advice.
- Each Built-in advice has a advisor
- Example
- ltbean id"gettersAndSettersAdvisor"
- class"...aop.support.RegexpMethodPointcutAroundAd
visor"gt - ltproperty name"interceptor"gt
- ltref local"interceptorBean"/gt
- lt/propertygt
- ltproperty name"patterns"gt
- ltlistgt
- ltvaluegt.\.get.lt/valuegt
- ltvaluegt.\.set.lt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
105ProxyFactory
- 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 programmatically
- ProxyFactory factory new ProxyFactory(myBusiness
InterfaceImpl) - factory.addInterceptor(myMethodInterceptor)
- factory.addAdvisor(myAdvisor)
- MyBusinessInterface b (MyBusinessInterface)facto
ry.getProxy()lt/beangt
106ProxyFactoryBean
- Used to get proxies for beans
- The bean to be proxied
- ltbean id"personTarget" class"eg.PersonImpl"gt
- ltproperty name"name"gtltvaluegtTonylt/valuegtlt/pr
opertygt - ltproperty name"age"gtltvaluegt51lt/valuegtlt/prope
rtygt - lt/beangt
PersonImpl implements Person interface
107ProxyFactoryBean
- The interceptors/advisors
- ltbean id"myAdvisor" class"eg.MyAdvisor"gt
- ltproperty name"someProperty"gtltvaluegtSomething
lt/valuegtlt/propertygt - lt/beangt
- ltbean id"debugInterceptor" class"...aop.intercep
tor.NopInterceptor"gt - lt/beangt
- The proxy
- ltbean id"person" class"...aop.framework.ProxyFac
toryBean"gt - ltproperty name"proxyInterfaces"gtltvaluegteg.Per
sonlt/valuegtlt/propertygt - ltproperty name"target"gtltref
local"personTarget"/gtlt/propertygt - ltproperty name"interceptorNames"gt
- ltlistgt
- ltvaluegtmyAdvisorlt/valuegt
- ltvaluegtdebugInterceptorlt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
108ProxyFactoryBean
- Using the bean
- Clients should get the person bean instead of
personTarget - Can be accessed in the application context or
programmatically - ltbean id"personUser" class"com.mycompany.PersonU
ser"gt - ltproperty name"person"gtltref local"person"
/gtlt/propertygt - lt/beangt
- Person person (Person) factory.getBean("person")
109ProxyFactoryBean
- 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
- ltbean id"person" class"...aop.framework.ProxyFac
toryBean"gt - ltproperty name"proxyTargetClass"gtltvaluegttruelt
/valuegtlt/propertygt - ltproperty name"target"gtltref
local"personTarget"/gtlt/propertygt - ltproperty name"interceptorNames"gt
- ltlistgt
- ltvaluegtmyAdvisorlt/valuegt
- ltvaluegtdebugInterceptorlt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
110AutoProxy
- Automatic proxy creation
- Just declare the targets
- Selected beans will be automatically proxied
- No need to use a ProxyFactoryBean for each target
bean
111BeanNameAutoProxyCreator
- Select targets by bean name
- ltbean id"employee1" class"eg.Employee"gt...lt/bean
gt - ltbean id"employee2" class"eg.Employee"gt...lt/bean
gt - ltbean id"myInterceptor" class"eg.DebugIntercepto
r"/gt - ltbean id"beanNameProxyCreator"
- class"...aop.framework.autoproxy.BeanNameAutoProx
yCreator"gt - ltproperty name"beanNames"gtltvaluegtemployeelt/v
aluegtlt/propertygt - ltproperty name"interceptorNames"gt
- ltlistgt
- ltvaluegtmyInterceptorlt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
112AdvisorAutoProxyCreator
- 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
113AdvisorAutoProxyCreator
- Example
- ltbean id"debugInterceptor" class"app.DebugInterc
eptor"/gt - ltbean id"getterDebugAdvisor"
- class"...aop.support.RegexpMethodPointcutAdvisor"
gt - ltconstructor-arggt
- ltref bean"debugInterceptor"/gt
- lt/constructor-arggt
- ltproperty name"pattern"gtltvaluegt.\.get.lt/val
uegtlt/propertygt - lt/beangt
- ltbean id"autoProxyCreator"
- class"...aop.framework.autoproxy.AdvisorAutoProxy
Creator"gt - ltproperty name"proxyTargetClass"gtltvaluegttruelt
/valuegtlt/propertygt - lt/beangt
This advisor applies debugInterceptor to all get
methods of any class
114AOP Weaving
115Spring Framework
116Mail
- Creating message
- SimpleMailMessage msg new SimpleMailMessage()
- msg.setFrom("me_at_mail.org")
- msg.setTo("you_at_mail.org")
- msg.setCc(new String "he_at_mail.org",
"she_at_mail.org") - msg.setBcc(new String "us_at_mail.org",
"them_at_mail.org") - msg.setSubject("my subject")
- msg.setText("my text")
117Mail-gtMessageSender
- Defining a message sender
- ltbean id"mailSender"
- class"org.springframework.mail.javamail.JavaMailS
enderImpl"gt - ltproperty name"host"gtltvaluegtsmtp.mail.orglt/va
luegtlt/propertygt - ltproperty name"username"gtltvaluegtjoelt/valuegtlt/
propertygt - ltproperty name"password"gtltvaluegtabc123lt/value
gtlt/propertygt - lt/beangt
- Sending the message
- MailSender sender (MailSender)
ctx.getBean("mailSender") - sender.send(msg)
118Scheduling
- Built in support for
- Java 2 Timer
- Timer
- TimerTask
- Quartz
- Schedulers
- JobDetails
- Triggers
119Scheduling-gtTimer Task
- The task that we want to run
- public class MyTask extends TimerTask
- public void run()
- // do something
-
-
- ltbean id"myTask"
- class"...scheduling.timer.ScheduledTimerTask"gt
- ltproperty name"timerTask"gt
- ltbean class"eg.MyTask"/gt
- lt/propertygt
- ltproperty name"delay"gtltvaluegt60000lt/valuegtlt/p
ropertygt - ltproperty name"period"gtltvaluegt1000lt/valuegtlt/p
ropertygt - lt/beangt
Java bean that wraps a scheduled java.util.TimerTa
sk
120Scheduling-gtTimerFactoryBean
- Creating the schedule
- ltbean id"scheduler"
- class"...scheduling.timer.TimerFactoryBean"gt
- ltproperty name"scheduledTimerTasks"gt
- ltlistgtltref bean"myTask"/gtlt/listgt
- lt/propertygt
- lt/beangt
- The Timer starts at bean creation time
Creates a java.util.Timer object
121JDBC
- Make JDBC easier to use and less error prone
- Framework handles the creation and release
resources - Framework takes care of all exception handling
122JDBC-gtJdbcTemplate
- Execute SQL Queries, update statements or stored
procedure calls - Iteration over ResultSets and extraction of
returned parameter values - Example
- DataSource ds DataSourceUtils.getDataSourceFromJ
ndi("MyDS") - JdbcTemplate jdbc new JdbcTemplate(ds)
- jdbc.execute("drop table TEMP")
- jdbc.update("update EMPLOYEE set FIRSTNME? where
LASTNAME?", - new String "JOE", "LEE")
123JDBC-gtJdbcTemplate
- Queries, using convenience methods
- int 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)
124JDBC-gtJdbcTemplate
- Queries, using callback method
- final 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
objects
125Hibernate
- Define a DataSource and an Hibernate
SessionFactory - ltbean id"dataSource" ...gt ... lt/beangt
- ltbean id"sessionFactory" class"...LocalSessionFa
ctoryBean"gt - ltproperty name"mappingResources"gt
- ltlistgt
- ltvaluegtemployee.hbm.xmllt/valuegt
- lt/listgt
- lt/propertygt
- ltproperty name"hibernateProperties"gt
- ltpropsgt
- ltprop key"hibernate.dialect"gt....DB
2Dialectlt/propgt - lt/propsgt
- lt/propertygt
- ltproperty name"dataSource"gt
- ltref bean"dataSource"/gt
- lt/propertygt
- lt/beangt
126HibernateTemplate
- Create HibernateTemplate
- SessionFactory sessionFactory
- (SessionFactory) ctx.getBean("sessionFactory")
- HibernateTemplate hibernate
- new HibernateTemplate(sessionFactory)
- Load and update
- Employee e (Employee) hibernate.load(Employee.cl
ass, "000330") - e.setFirstName("BOB")
- hibernate.update(e)
127HibernateTemplate
- Queries, using convenience methods
- List 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 )
128HibernateTemplate
- Queries, using callback methods
- List 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
-
-
- )
129Transactions
- 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 Manager
Resource Manager
Resource Manager
Database
Database
Messaging Server
130Spring 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
131Examples
- Defining a JtaTransactionManager
- ltbean id"dataSource" class"...jndi.JndiObjectFac
toryBean"gt - ltproperty name"jndiName"gtltvaluegtMyDSlt/valuegtlt/pro
pertygt - lt/beangt
- ltbean id"transactionManager"
- class"...transaction.jta.JtaTransactionMa