More Related Content
Similar to Jee design patterns- Marek Strejczek - Rule Financial
Similar to Jee design patterns- Marek Strejczek - Rule Financial (20)
Jee design patterns- Marek Strejczek - Rule Financial
- 2. Agenda
About JEE, J2EE and design patterns
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
© Rule Financial 2012 2
- 3. JEE Design Patterns
Agenda
About JEE, J2EE and design patterns
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
© Rule Financial 2012 3
- 4. What is JEE
• 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
© Rule Financial 2012 4
- 5. What is JEE
Technologies
• Chosen JEE6 technologies (there are many more):
• JCA
• EJB
• JPA
• JSF
• JAX-WS, JAX-RS
• JMS
• JDBC
• Servlet
• JTA
© Rule Financial 2012 5
- 6. What is JEE
Technologies cont’d
• Chosen JEE6 technologies:
• JCA Accessing external systems
• EJB Single-threaded programming model, remote
invocations
• JPA Managing relational data
• JMS Async communication – good for scalability
• JTA Distributed transactions, declarative
transactions
© Rule Financial 2012 6
- 8. J2EE drawbacks
Prior to JEE5
• Lots of boilerplate code
• Local, Remote, Remote Home interfaces
• XML deployment descriptor
• plus another XML for vendor-specific stuff
Spring and Hibernate
• JNDI lookups
emerged as a viable
• EJBs tightly coupled to J2EE API alternative
• Both session and entity beans
• Lack of encapsulation of technical details
© Rule Financial 2012 8
- 9. J2EE Drawbacks
Design Patterns come to rescue
• 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
© Rule Financial 2012 9
- 10. J2EE Drawbacks
JEE comes to rescue
• 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
© Rule Financial 2012 10
- 11. Architecture style
SOA, DDD
• 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
© Rule Financial 2012 11
- 12. Design Pattern
What is it?
• 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
© Rule Financial 2012 12
- 15. JEE Design Patterns
Agenda
Introduction
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
© Rule Financial 2011 15
- 16. Service Facade
Application Service
• 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.
© Rule Financial 2012 16
- 18. Service Facade
Application Service
• 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.
© Rule Financial 2012 18
- 26. Service
Session Facade
• 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.
© Rule Financial 2012 26
- 28. Service
Session Facade
• 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).
© Rule Financial 2012 28
- 33. Persistent Domain Object
Business Object
• 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.
© Rule Financial 2012 33
- 34. Persistent Domain Object
Business Object
• 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.
© Rule Financial 2012 34
- 40. Persistent Domain Object
• 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.
© Rule Financial 2012 40
- 41. Persistent Domain Object
Gateway pattern
• 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
© Rule Financial 2012 41
- 42. Fluid Logic
• 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).
© Rule Financial 2012 42
- 43. Fluid Logic
• 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.
© Rule Financial 2012 43
- 45. Fluid Logic
• 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.
© Rule Financial 2012 45
- 46. Fluid Logic
Consequences
• 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).
© Rule Financial 2012 46
- 48. JEE Design Patterns
Agenda
Introduction
Business tier patterns
Integration tier patterns
JEE infrastructure patterns
Retired J2EE patterns
Summary
© Rule Financial 2011 48
- 49. Data Access Object
• 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.
© Rule Financial 2012 49
- 50. Data Access Object
• 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.
© Rule Financial 2012 50
- 53. Data Access Object
Other variants
• 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)
© Rule Financial 2012 53
- 54. Data Access Object
Other variants
• 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.
© Rule Financial 2012 54
- 55. Transfer Object
• 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.
© Rule Financial 2012 55
- 56. Transfer Object
Rethinking the original intention
• 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!
© Rule Financial 2012 56
- 57. Transfer Object
Rethinking the original intention
• 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.
© Rule Financial 2012 57
- 58. Transfer Object
• 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.
© Rule Financial 2012 58
- 59. Transfer Object
Implementation
• 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.
© Rule Financial 2012 59
- 62. Singleton
• 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!
© Rule Financial 2012 62
- 64. Singleton
• 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.
© Rule Financial 2012 64
- 65. Service Starter
• 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.
© Rule Financial 2012 65
- 66. Service Starter
• Sequence in which @Singleton EJBs are initialized can be
controlled using @DependsOn annotation.
© Rule Financial 2012 66
- 67. Bean Locator
• 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)
© Rule Financial 2012 67
- 68. Bean Locator
• 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.
© Rule Financial 2012 68
- 69. Other neat patterns
• 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.
© Rule Financial 2012 69
- 73. Service Locator
• 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.
© Rule Financial 2012 73
- 74. Composite Entity
• 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.
© Rule Financial 2012 74
- 75. Value Object Assembler
• 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.
© Rule Financial 2012 75
- 76. Business Delegate
• 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.
© Rule Financial 2012 76
- 77. Domain Store
• 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.
© Rule Financial 2012 77
- 80. Useful facility: interceptors
Not covered in this presentation
• EJB come with a AOP framework.
• Lightweight
• Easy to use
• Still, lots of interesting capabilities - some patterns (not described here)
rely on this mechanism.
© Rule Financial 2012 80
- 82. Summary
• 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/
© Rule Financial 2012 82