Download presentation
Presentation is loading. Please wait.
1
Top 50 Java EE 7 Best Practices
Ryan Cuprak Michael Remijan [Ryan] - Welcome to the Top 50 Java Best Practices
2
About Us Ryan Michael @ctjava rcuprak@gmail.com http://www.cuprak.info
Michael @mjremijan I am Ryan, this is Michael,
3
EJB 3 In Action 2nd Edition
Updated For EE 7 EJB 3.2
4
Concurrency Utilities
Java EE 7 JSP 2.3 JSF 2.2 JSX-WS 2.2 JAX-RS 2 EL 3 Concurrency Utilities Servlet 3.1 Batch Applications Common Annotations 1.2 Interceptors 1.2 CDI 1.1 Managed Beans 1.0 EJB 3.2 JAXB Java API for JSON Connector 1.7 JPA 2.1 JTA 1.2 JMS 2 Java API for WebSocket
5
#1 JAX-RS: API Versioning
Version your JAX-RS with one of two approaches: 1. URL 2. Media Content or Header Param curl -H "Content-Type:application/srv-v4+json” … Return HTTP Status Codes for services moved/changed: 301 Moved Permanently 302 Found
6
#1 JAX-RS: API Versioning (Continued…)
Approach 1: URL Approach 2: Media Types
7
#1 JAX-RS: API Versioning (Continued…)
Service Moved Permanently
8
#2 JAX-RS: Error Handling
Provide ExceptionMappers to handle and process errors.
9
#2 JAX-RS: Error Handling (Continued…)
HTML content is hardly a friendly response for an API!
10
#2 JAX-RS: Error Handling (Continued…)
11
#3 JAX-RS: Caching Tell clients to cache data!
12
#4 JAX-RS + Bean Validation
Use Bean Validation to check data.
13
#5 JAX-RS: Compress Responses
Use gzip compression for responses to reduce bandwidth.
14
#6 Securing RESTful Services
Use tokens with RESTful Web Services (OWASP). Leverage JASPIC to setup JAAS environment.
15
#7 JAX-RS + EJB Use @Stateless and @Path together
Pooled, thread safe, monitored
16
#7 JAX-RS + EJB (Continued…)
17
#8 JAX-RS: Asynchronous API Gateway
Gateway calls multiple microservices asynchronously Combines results into a DTO
18
#8 JAX-RS: Async…(Continued…)
Gateway calls multiple microservices asynchronously Combines results into a DTO
19
#9 JPA: Pagination Use pagination for potential large result sets.
20
#9 JPA: Pagination (Continued…)
21
#10 JPA: Lazy Relationships
Avoid unnecessary queries – use Fetch on Lazy relationships.
22
#10 JPA: Lazy Relationships (Continued…)
SELECT MEETINGID, DATE, MEETINGABSTRACT, TITLE FROM MEETING WHERE (MEETINGID = ?) SELECT t1.SPEAKERID, t1.BIOGRAPHY, t1.FIRSTNAME, t1.LASTNAME FROM meeting_speakers t0, SPEAKER t1 WHERE ((t0.meetingid = ?) AND (t1.SPEAKERID = t0.speakerid))
23
#10 JPA: Lazy Relationships (Continued…)
SELECT t1.MEETINGID, t1.DATE, t1.MEETINGABSTRACT, t1.TITLE, t0.SPEAKERID, t0.BIOGRAPHY, t0.FIRSTNAME, t0.LASTNAME FROM SPEAKER t0, meeting_speakers t2, MEETING t1 WHERE ((t1.MEETINGID = ?) AND ((t2.meetingid = t1.MEETINGID) AND (t0.SPEAKERID = t2.speakerid))) 1 Query Not TWO!
24
#11 JPA: Cascade Don’t forget cascade levels to handle child data
cascade=ALL is equivalent to cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}
25
#12 JPA: Entity Graphs
26
#13 JPA + DAO Put CRUD operations into DAOs.
27
#14 JPA: hashcode() & equals()
The equals and hashcode are required for: Entity is added to a collection When re-attaching entities to a new persistence context. Important points: Do not use generated identifiers Use business key equality
28
#14 JPA: hashcode() & equals() Continued…
29
#15 JPA: Optimistic Locking
Don’t roll your own for optimistic locking: Integer
30
#15 JPA: Optimistic Locking (Continued…)
Timestamp
31
#16 JPA: Pessimistic Locking
PESSIMISTIC_READ, PESSIMISTIC_WRITE Lock timeout HINT
32
#17 JPA: Mapping Inheritance
Inheritance can have a big impact upon performance. Three approaches: Single table Joined-tables Table-per-class Denormalize for better performance
33
#18 JPA L2 Cache JPA 2 introduced the L2 Cache, use this cache for:
Entities that are frequently read Entities that are modified infrequently Not critical if stale L2 cache can consume large amounts of memory ALL NONE ENABLE_SELECTIVE DISABLE_SELECTIVE Are you using a default setting?
34
#18 JPA L2 Cache (Continued…)
Mark entity for L2 cache Bypass L2 cache
35
#19 JPA: Persisting ENUM ENUM is a good case of converting data types
Use
36
#19 JPA: Persisting ENUM (Continued…)
@Converter AttributeConverter<X,Y> X is my application, Y is the database
37
#20 EJB: Transaction Handling
EJBs exist to handle transactions. Keep them at the right layer Don’t ignore transactions. Default: REQUIRED JAX-RS endpoints, database reads & performance
38
#21 EJB: Stateless Thread Safety
Stateless beans are a pooled, managed resource Pools configurable by the application server
39
#22 EJB: Asynchronous @Asynchronous runs in container-managed thread
Return Future<> to get results later Ideal for wrapping JAX-RS calls Good way to avoid any of your own threading
40
#23 EJB: Security Use declarative security and let the container handle it Avoid programmatic security EE servers trust principal/roles passed between containers.
41
#23 EJB: Security (Continued…)
EE Configuration web.xml @DeclaredRoles @RolesAllowed Custom Configuration EE Server Realm glassfish-web.xml
42
#24 EJB: Avoid Lengthy Initialization
Don’t abuse startup delays You delay initialization of the container!
43
#24 EJB: Avoid Lengthy Initialization
44
#25 CDI: Observers In-memory event processing Very “reactive”
Decouple work to be done, avoids unnecessary dependencies Create an event to fire
45
#25 CDI: Observers (Continued…)
Fire the event Observers process the event
46
#26 CDI: Producer + Cache Use a producer to customize creation of an object Producer method is always called, so cache the instance
47
#27 CDI: Interceptors Limit to cross-cutting concerns
Do not use to change business logic Create an annotation
48
#27 CDI: Interceptors Create the interceptor
49
#27 CDI: Interceptors Apply the interceptor
50
#28 CDI: Decorators Use to enhance or decorate existing code
Open-close principle Do not use for cross-cutting concerns
51
#28 CDI: Decorators (Continued…)
/WEB-INF/beans.xml /META-INF/beans.xml
52
#29 CDI: Transactions Java EE introduced @Transactional for non-EJBs.
Pro: Easier to utilize transactions outside of EJB. Con: Mixes layers – transactions & rest etc.
53
#30 CDI: Bean Discovery Java EE 7 CDI is enabled by default.
beans.xml is no longer required as in EE 6 Bean discovery mode: Annotated – only annotated classes All – includes beans that are not annotated None – CDI disabled Default mode is ‘annotated’
54
#31 Batch: Java EE not SE Think Java EE for batch, not SE Batch API
Cron like schedule on EJB methods META-INF/batch-jobs/processInvoices.xml
55
#32: Batch Best Practices
Package/deploy batch jobs separately Implement logic to cleanup old jobs Implement logic for auto-restart Test restart and checkpoint logic Configure database to store jobs Configure thread pool for batch jobs Only invoke batch jobs from logic that is secured etc.)
56
#33 JAXB Primitive Data Types
anySimpleType float decimal double integer nonPositiveInteger long nonNegativeInteger int unsigneLong positiveInteger negativeInteger unsignedInt short unsignedInt byte unsignedByte
57
#34 JAXB: Date & Time Representation
Use XMLGregorianCalendar for dates Avoid java.util.Date and java.util.Calendar XMLGregorianCalendar Handles long fractions of seconds – important to .NET interoperability
58
#35 JAXB: Annotate Don’t let JAXB generate everything!
59
#36 JAX-WS: RPC vs. Document
Four different possibilities: RPC/Literal RPC/Encoded Document/Literal Document/Encoded Encoded is not supported by WS-I Default and most commonly used is Document/Literal Use Document/Literal RPC/Literal: Limited to basic XSD types WSDL will not include types section to constrain parameters
60
#37 JAX-WS: JAXB Gotcha Use either: DTO – Data Transfer Object
JAXB will serialize an entire object graph. Use either: DTO – Data Transfer Object @XmlTransient Oops!
61
#38 JAX-WS Interoperable Services
Design service starting with the WSDL Create data types using XSD Keep data types SIMPLE Avoid xsd:anyType Avoid sending Null values Use byte[] instead of String when character encoding is unknown
62
#39 SOAP Faults Types of SOAP faults:
Modeled – exception explicitly thrown by business logic. Mapped to wsdl:fault in WSDL file Unmodeled – RuntimeException, represented as generic SOAPFaultException
63
#40 JAX-WS Input/Output Processing
Use SOAP message handlers to pre/post process messages and handle SOAP faults.
64
#40 JAX-WS Input/Output Processing
65
#41 JAX-WS Security Specify Roles
66
#42 JAX-WS Large Files Use W3C Message Transmission Optimization Mechanism (MTOM) to handle large files.
67
#43 Deployment Classpath
Are you pulling in third-party JAR files? Do these JAR files include Java EE annotated classes? Are you accidently deploying web services, MDBs etc.? Are you including container dependencies? BAD!
68
#44 Threading Never create create threads.
Container manages resources.
69
#44 Threading… Thread Factory
70
#45 Distributed Caches Don’t treat @Singleton as a “global” singleton!
Use JCache implementation (ex. HazelCast) Java EE Server #1 Java EE Server #2 app.war app.war SingletonBean SingletonBean
71
#46 Testing: Load Oops! Load testing always at 100%? Scenario:
Message Driven Bean with a connection to a remote resource. Standing pool size: 3 Oops!
72
#46 Testing Load (Continued…)
Oops, resource only leak as bean instances fluctuate! Returning to standing pool size leaks resources.
73
#47 Testing: Integration
Use Arquillian:
74
#48 Java EE Tutorial Table of Contents
What’s in Java EE? 918 pages TOC is a great summary 30+ pages Highlights just how much is in EE
75
#49 There are no “small” applications
Don’t fall into these traps: “It’s just a simple application” “It only needs to do…” “Code it up real quick…” EE Specification exists for a reason Multiple users Concurrency Multi-threading Transaction management External resources Messaging
76
#50 Start with an EE Server
Because there are no “small” applications Start with an EE Server Avoid filling your WAR with “EE Features” because you are not using an EE server But Servers are “heavy-weight”? Payara WildFly TomEE Benefits “Light-weight” Regular updates Great online community support
77
Join Us!
78
Q&A
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.