Upload
others
View
11
Download
0
Embed Size (px)
Citation preview
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
1
Overview of POJO programming
A simpler, faster way to build long-lived applications
by
Chris [email protected]
http://www.chrisrichardson.net
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
2
About Chris…Grew up in EnglandLive in OaklandTwenty years of software development experience
Building object-oriented software since 1986Using Java since 1996Using J2EE since 1999
Author of POJOs in ActionRun a consulting company that helps organizations build better software fasterChair of the eBIG Java SIG in Oakland (www.ebig.org)
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
3
Overview
POJOs + lightweight frameworks:Simplify developmentAccelerate developmentMake applications immune to the volatility of enterprise Java technology
Focus on the “backend” frameworks:Business tierDatabase access tier
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
4
Agenda
The trouble with traditional enterprise Java frameworksOverview of POJOsAssembling POJO applications with dependency injectionPersisting POJOs with HibernateMaking POJOs transactional with Spring
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
5
Classic EJB architecture example
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
6
Problems with intertwined business logic and infrastructure
Upgrading to new, better version of infrastructure framework is difficult/impossible:
Enterprise Java (1998-2006):Incompatible standards: EJB 1, EJB 2, EJB 3Many persistence options: EJB CMP 1/2, Hibernate 1/2/3, JDO 1/2, EJB 3 persistence
Makes development more difficultForced to think about business logic + infrastructure concerns simultaneouslyDevelopers need to know both
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
7
…problems
Makes testing more difficultMust deploy code/tests in application serverSlows down the edit-compile-debug cycle
EJB 2 prevented OO developmentEJB application servers are
Complex Expensive (some)
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
8
EJB as a cultIn 1999 I readily embraced EJBs and its development rituals:
writing DTOs and unused lifecycle methodsWaiting for EJBs to deploy
According to http://en.wikipedia.org/wiki/Cult
“a cult is a relatively small and cohesive group of people devoted to beliefs or practices that the surrounding culture or society considers to be far outside the mainstream”
But there is a better way….
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
9
Agenda
The trouble with traditional enterprise Java frameworksOverview of POJOsAssembling POJO applications with dependency injectionPersisting POJOs with HibernateMaking POJOs transactional with Spring
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
10
POJO = Plain Old Java Object
Java objects that don't implement any special interfaces or (perhaps) call infrastructure APIsCoined by Martin Fowler, Rebecca Parsons, and Josh MacKenzie to make them sound just as exciting as JavaBeans, Enterprise JavaBeansSimple idea with surprising benefits
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
11
POJO application design
POJO facade
Domain model Database access
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
12
POJO code example
Simple Java classesNo lookup code – uses dependency injection instead
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
13
But POJOs are insufficient…⇒ Lightweight frameworks
Endow POJOs with enterprise featuresObject/relational mapping framework:
Persists POJOsJDO, Hibernate, JPA, …
Spring framework:Popular open-source frameworkDeclarative transaction managementDependency injectionRemoting, security, …
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
14
Key point: non-invasive frameworks
Provide services without the application:Implementing interfacesCalling APIs
Configured using metadata:XMLJava 5 annotations
POJOs + non-invasive frameworks ⇒simple, faster development of applications that are immune to infrastructure changes
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
15
Deployment optionsWeb container-only server
Tomcat or JettySimple yet sufficient for many applications
Full-blown serverWebLogic, JBoss, WebSphereRicher set of featuresEnhanced manageability and availabilityJTAJMS…
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
16
Benefits of using POJOs
Separation of concernsBusiness logic is decoupled from infrastructureSwitch frameworks or upgrade more easilyNot everybody has to be an infrastructure framework expert
Simpler developmentThink about one thing at a timeBusiness logic, persistence, transaction management….
Faster developmentTesting without an application server (or a database)No deployment to slow you down
More maintainableModular object-oriented codeLoosely coupled design
Simpler, perhaps cheaper deploymentDeploy in a web-container only server
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
17
Drawbacks of POJOs…
…none except that lightweight frameworks have their limitationsUse EJBs if you need:
Distributed transactions initiated by a remote clientSome application server-specific features…
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
18
Agenda
The trouble with traditional enterprise Java frameworksOverview of POJOsAssembling POJO applications with dependency injectionPersisting POJOs with HibernateMaking POJOs transactional with Spring
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
19
Dependency injectionApplication components depend on:
One another Infrastructure components
Using JNDI or the new operator:Introduces couplingComplexity
Solution:Pass dependencies to a componentSetter injectionConstructor injection
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
20
Dependency injection example
public class MoneyTransferServiceImpl…
public MoneyTransferServiceImpl(AccountRepository
accountRepository, …){
this.accountRepository = accountRepository;
…}
public class HibernateAccountRepositoryimplements AccountRepository {
…}
You can implement dependency injection by hand but ….
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
21
Spring lightweight container
Lightweight container = sophisticated factory for creating objectsSpring bean = object created and managed by SpringYou write XML that specifies how to:
Create objects Initialize them using dependency injection
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
22
Spring code examplepublic class MoneyTransferServiceImpl…
public MoneyTransferServiceImpl(AccountRepository
accountRepository, …){
this.accountRepository = accountRepository;
…}
<bean name="MoneyTransferService"class="MoneyTransferServiceImpl">
<constructor-arg ref="AccountRepository"/>…
</bean>
<bean name="AccountRepository"class="HibernateAccountRepository">
…</bean>
public class HibernateAccountRepositoryimplements AccountRepository {
…}
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
23
Spring 2 – dependency injection into entities
Domain model entities need to access repositories/DAOs/etcBut they are created by the application or by Hibernate – not SpringPassing repositories as method parameters from services clutters the codeSpring 2 provides AspectJ-based dependency injection into entitiesConstructors automatically invoke Spring
@Configurable("pendingOrder")public class PendingOrder {
private RestaurantRepository restaurantRepository;
public void setRestaurantRepository(RestaurantRepository
restaurantRepository) {this.restaurantRepository =
restaurantRepository;}
<aop:spring-configured />
<bean id="pendingOrder" lazy-init="true"><property name="restaurantRepository"
ref="RestaurantRepositoryImpl" />
</bean>
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
24
Benefits of dependency injection
Simplifies codeNo calls to JNDI
Decouples components from:One anotherInfrastructure
Simplifies testingPass in a mock/stub during testing
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
25
Mock object code example
Test the MoneyTransferServiceImplwithout calling the real AccountRepository
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
26
Agenda
The trouble with traditional enterprise Java frameworksOverview of POJOsAssembling POJO applications with dependency injectionPersisting POJOs with HibernateMaking POJOs transactional with Spring
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
27
POJO persistence
Use an object/relational framework:Metadata maps the domain model to the database schemaORM framework generates SQL statements
HibernateVery popular open-source project
JDOStandard from Sun – JSR 12 and JSR 243Multiple implementations: Kodo JDO, JPOX
EJB 3/Java Persistence API (JPA)
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
28
Hibernate: code example
Provides transparent persistencePieces:
AccountHibernateBankingExample.hbm.xmlHibernateAccountPersistenceTestsHibernateAccountRepositoryHibernateAccountRepositoryTestsSpring beans
Only the repositories/DAOs call persistence framework APIs
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
29
ORM framework features 1Declarative mapping
Map classes to tables; fields to columns; relationships to foreign keys and join tables
CRUD APIE.g. Hibernate Session, JPA EntityManager
Query languageRetrieve objects satisfying search criteria
Transaction managementManual transaction managementRarely call directly – used by Spring
Detached objectsDetach persistent objects from the DBEliminates use of DTOsSupports edit-style use cases
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
30
ORM framework features 2Lazy loading
Provide the illusion that objects are in memoryBut loading all objects would be inefficient
⇒ load an object when it is first accessedEager loading
Loading objects one at a time can be inefficient⇒ load multiple objects per-select statement
CachingDatabase often the performance bottleneck⇒ cache objects in memory whenever you canEasy for readonly objectsOptimistic locking and cache invalidation for changing objects
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
31
O/R mapping framework benefitsImproved productivity
High-level object-oriented APILess Java code to writeNo SQL to write
Improved performanceSophisticated cachingLazy loadingEager loading
Improved maintainabilityA lot less code to write
Improved portabilityORM framework generates database-specific SQL for you
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
32
When and when not to use an ORM framework
Use when the application:Reads a few objects, modifies them, and writes them backDoesn’t use stored procedures (much)
Don’t use when:Simple data retrieval ⇒ no need for objectsLots of stored procedures ⇒ nothing to map toRelational-style bulk updates ⇒ let the database do thatSome database-specific features ⇒ not supported by ORM framework
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
33
Agenda
The trouble with traditional enterprise Java frameworksOverview of POJOsAssembling POJO applications with dependency injectionPersisting POJOs with HibernateMaking POJOs transactional with Spring
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
34
Making POJOs transactional
EJB 2 container-managed transactions are greatSpring provides declarative transactions for POJOsSimilar to CM transactions but
Runs outside of an application serverMore flexible exception handling
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
35
Spring AOPAOP enables the modular implementation of crosscutting concernsSpring AOP = simple, effective AOP implementationLightweight container can wrap objects with proxiesProxy executes extra code:
Before original methodAfter original methodInstead of…
Spring uses proxies for:transaction managementsecuritytracing…
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
36
Spring TransactionInterceptor
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
37
Spring code example<bean
name="AccountManagementFacade“class="AccountManagementFacadeImpl"> …
</bean>
<bean id="transactionProxyCreator“class=“...BeanNameAutoProxyCreator"><property name="beanNames">
<list><idref
bean="AccountManagementFacade"/> </list>
</property><property name="interceptorNames">
<list><idref
bean="BankingTransactionInterceptor"/></list>
</property></bean>
<bean id="myTransactionManager"class="HibernateTransactionManager">
…</bean>
<bean id="BankingTransactionInterceptor"class="TransactionInterceptor"><property name="transactionManager"
ref="myTransactionManager"/></bean>
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
38
Spring 2 – simplified XML<bean
name="AccountManagementFacade“class="AccountManagementFacadeImpl"> …
</bean>
<aop:config><aop:advisorpointcut="execution(* *..*Facade.*(..))"
advice-ref="txAdvice"/></aop:config>
<bean id="transactionManager"
class="HibernateTransactionManager">…</bean>
<tx:advice id="txAdvice"><tx:attributes>
<tx:method name="*"/></tx:attributes>
</tx:advice>
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
39
Spring remotingRemoting
Spring HTTPHessian/BurlapRMI…
Server uses a <Xyz>Exporter bean
Service to exposeInterface to expose
Client uses a <Xyz>ProxyFactoryBean
URL to remote service
<bean name="/accountManagement" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="TransferFacade"/>
<property name="serviceInterface“value="net.chrisrichardson…TransferFacade“
/></bean>
<bean id="httpInvokerProxy" class="org.springframework.remoting.httpinvoker.
HttpInvokerProxyFactoryBean"><property name="serviceUrl"
value="http://somehost:8080/accountManagement"/>
<property name="serviceInterface“value="net.chrisrichardson…TransferFacade“
/></bean>
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
40
Spring SecurityAcegi Security
Open source projectExtension to Spring
MethodSecurityInterceptorVerifies that caller is authorized
Invoke methodAccess instances
<bean id=“transferSecurity" class="org.acegisecurity.intercept.method.aopalliance.
MethodSecurityInterceptor">…<property
name="objectDefinitionSource"><value>
net.chrisrichardson…TransferFacade.*=
ROLE_CUSTOMER, ROLE_CSR</value>
</property>
</bean>
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
41
Deploying a Spring applicationOften packaged as a WARWeb.xml lists bean definition filesServletContextListenercreates Spring bean factoryWeb tier is either:
Injected with Spring beansCalls getBean()
<web-app>
<context-param><param-name>contextConfigLocation</param-name>
<param-value>/beans1.xml/beans2.xml</param-value>
</context-param>
<listener><listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class></listener>
..
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
42
Summary
Simplify developmentAccelerate developmentImprove maintainabilityIncrease immunity to rapidly evolving infrastructure frameworks
POJOs
+ =
Non-invasive frameworks
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
43
For more informationBuy my book ☺
Send email:[email protected]
Visit my website:
http://www.chrisrichardson.net
Please hand in your session evaluations
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
44
Extra slides
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
45
Thoughts about EJB 3 and POJOs☺ Better than EJB2☺ Supports POJOs☺ Reasonable ORM☺ Entity beans = JPA☺ Annotations are
concise☺ Has dependency
injection☺ It’s a standard
Less powerful than Spring, e.g. DI relies on JNDILess powerful than Hibernate, e.g. List<String>Session beans/MDBsmust be deployedComplexity of EJB lurking withinAnnotations couple your code to EJB3EJB’s poor track record as a standard
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
46
Using Spring with EJBs
Simplify EJB client code with SpringSpring encapsulates JNDI lookupClient gets EJB reference from SpringBetter: Client is injected with EJB reference
Move business logic into Spring beansSession EJBs delegate to Spring beansUse Spring dependency injectionSimpler code, easier testing
Simplify DAOs with Spring JDBCEliminates error-prone boilerplate code
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
47
Migrating to POJOs – part 1
2 year old application:Session EJBsEntity Bean-based domain modelSome JDBC DAOsBeginning development of version 2
Replaced entity beans with Hibernate:WAS vs. WLS portabilityTest business logic without persistenceTest persistence without a serverA much richer domain model
6/20/2006 Copyright (c) 2006 Chris Richardson. All rights reserved.
48
Migrating to POJOs – part 2
Used Spring beans for V2 codeIncrementally replaced V1 session beans with Spring beans when:
Enhancing itV2 code needed to call V1 code
End result:Richer domain modelFaster developmentV2 code was deployable as a web app.