View
4.095
Download
0
Category
Tags:
Preview:
Citation preview
Confidential
JEE Design Patterns
Prepared by: Marek StrejczekSubmitted on: 2012-10-19
About JEE, J2EE and design patterns
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
Agenda
2© Rule Financial 2012
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
JEE Design PatternsAgenda
3© Rule Financial 2012
About JEE, J2EE and design patterns
What is JEE
4© Rule Financial 2012
• JEE platform provides an API and runtime environment
for developing and running enterprise software
• including network and web services, and other large-scale, multi-
tiered, scalable, reliable, and secure network applications
• The platform incorporates a design based largely on
modular components running on an application server
Based on wikipedia.org
What is JEETechnologies
5© Rule Financial 2012
• Chosen JEE6 technologies (there are many more):• JCA
• EJB
• JPA
• JSF
• JAX-WS, JAX-RS
• JMS
• JDBC
• Servlet
• JTA
What is JEETechnologies cont’d
6© Rule Financial 2012
• Chosen JEE6
technologies:
• JCA
• EJB
• JPA
• JMS
• JTA
Accessing external systems
Single-threaded programming model,
remote invocations
Managing relational data
Async communication – good for
scalability
Distributed transactions, declarative
transactions
JEE Architecture
7© Rule Financial 2012
J2EE drawbacksPrior to JEE5
8© Rule Financial 2012
• Lots of boilerplate code
• Local, Remote, Remote Home
interfaces
• XML deployment descriptor
• plus another XML for vendor-specific
stuff
• JNDI lookups
• EJBs tightly coupled to J2EE API
• Both session and entity beans
• Lack of encapsulation of technical
details
Spring and Hibernate emerged as a viable alternative
J2EE DrawbacksDesign Patterns come to rescue
9© Rule Financial 2012
• Some design patterns were invented just to work
around platform limitations
• Example: Service Locator, Business Delegate
• Some design patterns solved genuine problems
inherent to enterprise environment
• Example: Session Facade, DAO
J2EE DrawbacksJEE comes to rescue
10© Rule Financial 2012
• Totally redesigned EJB programming model
• Dependency Injection
• Convention over Configuration
• POJO-based persistence
• Minimal coupling of business logic to EJB API
• Most APIs were not redesigned: JTA, JMS, JNDI, Servlets
Architecture styleSOA, DDD
11© Rule Financial 2012
• Service Oriented Architecture
• Business functionalities exposed using interoperable services
built from reusable components
• Domain Driven Design
• Mapping of business domain concepts into software artifacts
• Good when work together
• however easily degenerate - e.g. anemic model with
SOA
Design PatternWhat is it?
12© Rule Financial 2012
• A general reusable solution to a commonly occurring
problem within a given context in software design.
• Can speed up development process as it provides a
tested, proved development paradigm.
• Facilitates communication among
developers/architects by providing universal jargon.
Based on wikipedia.org
Design PatternA simple Builder
13© Rule Financial 2012
Questions?
14© Rule Financial 2012
Introduction
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
JEE Design PatternsAgenda
15© Rule Financial 2011
Business tier patterns
Service FacadeApplication Service
16© Rule Financial 2012
• Forces
• High-level business API is needed.
• State of the application must remain consistent.
• Logic can be invoked remotely.
• Realization behind the Service Facade should be encapsulated.
• Business API must not change when the realization is modified.
Service FacadeApplication Service
17© Rule Financial 2012
Service FacadeApplication Service
18© Rule Financial 2012
• Boundary between presentation and business layers.
• A stateless session bean.
• Coarse-grained methods, designed from domain
perspective.
• @TransactionAttributeType(REQUIRES_NEW).
• A composition of independent and reusable services.
• Very simple business logic can be realised directly.
Service FacadeBasic implementation
19© Rule Financial 2012
Service FacadeCRUD Facade
20© Rule Financial 2012
Service FacadeDual-view Facade
21© Rule Financial 2012
Service FacadeSOA Facade
22© Rule Financial 2012
Service FacadeLightweight asynchronous facade
23© Rule Financial 2012
EJB 3.1:
Service FacadeMultichannel facade – JAX-WS
24© Rule Financial 2012
Service FacadeMultichannel facade – JAX-RS
25© Rule Financial 2012
ServiceSession Facade
26© Rule Financial 2012
• Forces
• Services should be independent of each other.
• Services are not accessible from outside the business tier or
remotely.
• A Service is aimed to be used by another component or
Service Facade.
• State of the application must remain consistent.
• Business API must not change when the realization is modified.• In DDD a Service realizes cross-cutting, domain object-
independent logic. In SOA a Service plays a main role and
implements the actual business logic.
ServiceSession Facade
27© Rule Financial 2012
ServiceSession Facade
28© Rule Financial 2012
• Rationale for J2EE-style Session Facade is to large
extent gone.
• Entity beans are no longer remotely-accessible.
• Container can manage relations between different entities
itself.
• A session bean.
• Not concerned with remoting, transactions, security.
• These are responsibilities of Service Facade.
• Local interface only.
• @TransactionAttributeType(MANDATORY).
ServiceBasic implementation
29© Rule Financial 2012
ServicePOJO implementation
30© Rule Financial 2012
ServicePOJO implementation – cont’d
31© Rule Financial 2012
Service Facade + Service
32© Rule Financial 2012
Persistent Domain ObjectBusiness Object
33© Rule Financial 2012
• Forces
• Complex business logic.
• Validation rules are domain-related and sophisticated.
• Domain objects need to be persisted in a relational DB.
• J2EE Business Object pattern was invented around
shortcomings of the technology
• CMP persistence didn’t support inheritance or polymorphic
queries.
• Anemic model was the only viable solution.
Persistent Domain ObjectBusiness Object
34© Rule Financial 2012
• Anemic entities and procedural approach are widely
used.
• They didn’t go away even when JDO or Hibernate became
available.
• Procedural approach actually works quite well.
• However when the domain model is complex and full
of sophisticated business rules, the code may become
brittle and difficult to enhance.
Persistent Domain ObjectBusiness Object
35© Rule Financial 2012
Persistent Domain ObjectAnemic model
36© Rule Financial 2012
Persistent Domain ObjectPDO
37© Rule Financial 2012
Persistent Domain ObjectModel with PDOs
38© Rule Financial 2012
Persistent Domain ObjectModel with PDOs
39© Rule Financial 2012
Persistent Domain Object
40© Rule Financial 2012
• Self-contained domain objects.
• Clear responsibilities.
• Encapsulated state and behaviour.
• Best when PDOs are used in attached state.
• Otherwise be prepared for complex merging of changes…
• Accessing Entity Manager from inside JPA entities is
problematic.
• Lack of JavaBean-style getters/setters makes PDOs not
suitable for data-binding UI frameworks.
Persistent Domain ObjectGateway pattern
41© Rule Financial 2012
• Gateway pattern
• Not covered in this presentation. Too big and too
unusual – this presentation is already large enough.
• That pattern is related to exposing PDOs to the
presentation layer.
• Try this link to study on your own:
• http://www.javaworld.com/javaworld/jw-05-2009/jw-05-domain-
driven-design.html
Fluid Logic
42© Rule Financial 2012
• Forces
• Ability to execute parts of the business logic dynamically.
• Algorithms often change and therefore should be reloadable.
• A custom interpreter is too expensive to develop and maintain.
• Integration of scripting components with JEE environment is
desired.
• Solution:
• Implement volatile algos in a scripting language
that would be interpreted dynamically at runtime.
• Possible with JSR-223 (Scripting for the Java
Platform).
Fluid Logic
43© Rule Financial 2012
• Using dynamic languages to build enterprise
applications is still risky.
• Poor static analysis, refactoring facilities and IDE support.
• Lack of type safety requires writing more unit tests.
• Reasonable use of scripting can be advantageous,
though.
• Scripting can be used in any layer and for any
purpose.
Fluid Logic
44© Rule Financial 2012
Fluid Logic
45© Rule Financial 2012
• Script can be loaded as a resource at runtime, from
any location.
• The script can be invoked in the context of the EJB.
• Participates in transactions.
• Has access to container services.
• Testing of the dynamic scripts may be a challenge.
• Fortunately only little parts of the application are likely to be
scripted.
Fluid LogicConsequences
46© Rule Financial 2012
• Flexibility of the business logic is improved.
• Performance will suffer. Hopefully it’ll be still
acceptable.
• Heterogenous projects are more difficult to understand
and maintain.
• Security might suffer.
• SecurityManager remains there, but someone might use the
ScriptingEngine to introduce a malicious script into the
system.
• If support for multiple scripting languages is not
required then direct integration might be more
efficient (e.g. Rhino).
Questions?
47© Rule Financial 2012
Introduction
Business tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
JEE Design PatternsAgenda
48© Rule Financial 2011
Integration tier patterns
Data Access Object
49© Rule Financial 2012
• Forces
• Access a legacy (JPA-incompatible) data source or resource is
needed.
• Strict separation of business logic and persistence details is
needed.
• Resource access must be decoupled from the rest of the
application (e.g. because it uses a proprietary interface).
• The queries are very complex and it is desired to maintain
them in a separate place.
• Data access abstraction must be testable and mockable.
Data Access Object
50© Rule Financial 2012
• A DAO is a stateless session bean.
• @TransactionAttributeType.MANDATORY
• For JPA-incompatible access the JEE approach is
basically the same as before.
• EntityManager is a DAO in itself.
• In simple cases it can be injected directly into the business
logic.
• DAO that relies on JPA is basically a wrapper around
EntityManager.
Data Access ObjectCRUD Service (Generic DAO)
51© Rule Financial 2012
Data Access ObjectCRUD Service (Generic DAO)
52© Rule Financial 2012
Data Access ObjectOther variants
53© Rule Financial 2012
• A domain-specific DAO.
• A type-safe DAO designed to act on a particular domain object.
• Could contain domain-specific extensions going beyond
standard functionality provided by EntityManager.
• Detached-result DAO.
• If DAO returns detached objects then it’s a good practice to
indicate it in the type name of the returned value, e.g.
List<BookDTO> findByNamedQuery(String queryName)
Data Access ObjectOther variants
54© Rule Financial 2012
• Abstract DAO
• Business logic service extends an abstract class with DAO
capabilities.
• Not ok for purists, but may be pragmatic in small DB-driven
applications.
Transfer Object
55© Rule Financial 2012
• In J2EE intended:
• to decouple domain objects from its users and reduce
coupling between tiers.
• to transfer all requested data at once, to avoid many remote
calls to CMP entity bean getters.
Transfer ObjectRethinking the original intention
56© Rule Financial 2012
• Decoupling was often a myth, as structure of TOs was very
similar or identical to that of domain objects.
• Usually new feature impact cross-cuts all layers, so TOs
had to be modified at the same time as domain entites and
presentation forms, effectively crippling maintainability.
• JPA entites are by definition local and not available for
remote calls.
• Detached JPA entites can often be used as TOs!
Transfer ObjectRethinking the original intention
57© Rule Financial 2012
• Transfer Objects in JEE can be used to decouple external
interfaces from domain model.
• Service-oriented applications need to expose a stable interface.
• Change in domain model due to a request from one client should not
affect other clients.
• Transfer Objects can be used to provide client-specific views, providing
additional flexibility compared to detached JPA entites.
• Transfer Objects might carry only the required subset of the
object graph to reduce overhead in a distributed environment.
Transfer Object
58© Rule Financial 2012
• Transfer Object may represent a simplified view of domain
objects for use e.g. with web services.
• Transfer Object may carry additional metadata for the
presentation tier.
Transfer ObjectImplementation
59© Rule Financial 2012
• A serializable class, no logic.
• Many approaches:
• Java bean
• Builder-style, possibly final
• Generic DTO
• Data stored as key-value pairs.
• Most flexible, but verbose and not type safe.
Questions?
60© Rule Financial 2012
Introduction
Business tier patterns
Integration tier patterns
Retired J2EE patterns
Summary
JEE Design PatternsAgenda
61© Rule Financial 2011
JEE infrastructure patterns
Singleton
62© Rule Financial 2012
• Wanted: a bean that exists only once in a JVM.
• Could be useful for keeping master data cache or
configuration.
• Not possible to achieve in a portable way prior to EJB
3.1.
• In EJB 3.1: @Singleton
• In a clustered environment there will be multiple Singleton
instances!
Singleton
63© Rule Financial 2012
• Default settings for singletons:
• ConcurrencyManagementType.Container
• LockType.Write
Singleton
64© Rule Financial 2012
• Could be used to throttle access to legacy backend
resources.
• Contain cache data
• E.g. configuration, internationalization messages.
• If cache data is loaded at startup and is read-only then
LockType.READ mode could be used.
• Consider using a real caching solution, like EHCache.
• No cluster-wide singletons as of EJB 3.1.
Service Starter
65© Rule Financial 2012
• Wanted: certain logic must be executed before
business requests can be handled.
• E.g. huge XMLs must be parsed first.
• Prior to EJB 3.1:
• Invoke EJB from servlet’s init method. The servlet has <load-
on-startup> set to 1.
• In EJB 3.1:
• Annotate class with @Singleton and @Startup
• Put required logic inside a method annotated with
@PostConstruct.
Service Starter
66© Rule Financial 2012
• Sequence in which @Singleton EJBs are initialized can
be controlled using @DependsOn annotation.
Bean Locator
67© Rule Financial 2012
• Wanted: a way to access EJBs where Dependency
Injection won’t work.
• E.g. from POJOs, from outside of EJB container.
• Lookup of stateful EJBs from servlets.
• Similar concept to J2EE Service Locator
• JNDI lookups are ugly and should be hidden.
• However use of a Bean Locator is an exception rather than
rule.
• Bean Locator is used for looking up EJBs, while Service Locator
was used to fetch all type of resources (JMS destinations, data
sources, EJBs)
Bean Locator
68© Rule Financial 2012
• New in EJB 3.1: global JNDI naming of EJB components.• jndi:global[/<app-name>]/<module-name>/<bean-name>#[<fully-
qualified-interface-name>]
• Bean Locator returns the business interface (or bean
instance), while Service Locator fetched the home
interface.
• Bean Locator goes well with the GoF Builder pattern –
Builder is useful for creating JNDI names.
Other neat patterns
69© Rule Financial 2012
• Dependency Injection Extender
• Inject Guice or Spring beans into EJBs.
• These external components will participate in EJB transactions
and security context.
• Resource Binder
• Register custom resources in JNDI in a portable way.
• Context Holder
• Pass information between transaction participants without
polluting your application API. Uses
TransactionSynchronizationRegistry class.
Other neat patterns
70© Rule Financial 2012
Questions?
71© Rule Financial 2012
Introduction
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Summary
JEE Design PatternsAgenda
72© Rule Financial 2011
Retired J2EE patterns
Service Locator
73© Rule Financial 2012
• Original intention
• Abstract all JNDI usage and hide complexities of initial context
creation and JNDI lookups.
• Reasons for retirement
• Dependency Injection is available in most JEE components.
• Service Locator would increase complexity instead of
decreasing it.
• In exceptional cases – use the Bean Locator pattern.
Composite Entity
74© Rule Financial 2012
• Original intention
• Represent a set of interrelated persistent objects instead of
exposing fine-grained entity beans directly.
• Necessary as entity beans were available remotely.
• Also relations between persistent entities were not
transparent.
• Reasons for retirement
• JPA handles relations between entities well.
• JPA entities are not available remotely.
Value Object Assembler
75© Rule Financial 2012
• Original intention
• To extract, merge and transform data from different data
sources and expose them using Transfer Objects.
• Reasons for retirement
• EntityManager is able to return a submodel from a graph of
interconnected entities.
• Service or Service Facade is responsible for converting entities
into Transfer Objects. Separate pattern is not required.
• Meaning of TOs has dropped since in many cases detached
entities can be moved between layers directly.
Business Delegate
76© Rule Financial 2012
• Original intention
• Hide the complexity of accessing business services in EJB
architecture (JNDI lookups and remoteness of invocations)
from J2EE clients.
• Reasons for retirement
• Checked exceptions are gone from the API (e.g.
RemoteException) – EJB business interface is the same as
Business Delegate interface.
• Obtaining reference to an EJB is significantly simplified – even
if Dependency Injection cannot be used, the JNDI lookup
returns the business interface directly, without going through
the home interface.
Domain Store
77© Rule Financial 2012
• Original intention
• To transparently persist an object model, hiding the required
CMP J2EE plumbing.
• Reasons for retirement
• EntityManager can be considered as a standardized Domain
Store.
Questions?
78© Rule Financial 2012
Introduction
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
JEE Design PatternsAgenda
79© Rule Financial 2011
Summary
Useful facility: interceptorsNot covered in this presentation
80© Rule Financial 2012
• EJB come with a AOP framework.
• Lightweight
• Easy to use
• Still, lots of interesting capabilities - some patterns (not
described here) rely on this mechanism.
Useful facility: interceptors
81© Rule Financial 2012
Summary
82© Rule Financial 2012
• JEE is not heavyweight anymore.
• The paterns make application architecture cleaner and
more maintainable.
• Some patterns may be used in Spring-based
applications.
• References: • „Real World Java EE Patterns Rethinking Best Practices” Adam Bien
• http://www.javaworld.com/javaworld/jw-05-2009/jw-05-domain-driven-design.html
• http://www.corej2eepatterns.com/
Confidential
Thank you!
Recommended