Pro Cloud-Native
Java EE Apps
DevOps with MicroProfile,
Jakarta EE 11 APIs, and Kubernetes
Second Edition
Luqman Saeed
Ghazy Abdallah
Apress
Pro Cloud-Native
Java EE Apps
DevOps with MicroProfile,
Jakarta EE 11 APIs,
and Kubernetes
Second Edition
Luqman Saeed
Ghazy Abdallah
Apress®
Pro Cloud-Native Java EE Apps: DevOps with MicroProfile, Jakarta EE 11
APIs, and Kubernetes, Second Edition
Luqman Saeed
Cantonments, Accra, Ghana
Ghazy Abdallah
Alwakra, Qatar
ISBN-13 (pbk): 979-8-8688-1395-5
https://doi.org/10.1007/979-8-8688-1396-2
ISBN-13 (electronic): 979-8-8688-1396-2
Copyright © 2025 by Luqman Saeed and Ghazy Abdallah
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Melissa Duffy
Editorial Project Manager: Gryffin Winkler
Cover designed by eStudioCalamar
Cover image designed by Kohji Asakawa from Pixabay
Distributed to the book trade worldwide by Springer Science+Business Media New York,
1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub. For more detailed information, please visit https://www.apress.
com/gp/services/source-code.
If disposing of this product, please recycle the paper
I dedicate this book to my two sons,
without whom this book would have been finished
much earlier and faster, and to my beloved wife,
who somehow managed to keep me sane.
—Luqman Saeed
I dedicate this book to my wife andfamilyfor supporting
me throughout and Luqman for honoring me as coauthor.
—Ghazy Abdallah
Table of Contents
About the Authors.............................................................................xxiii
About the Technical Reviewer
xxv
Introduction
xxvii
Chapter 1: The Theory of Jakarta EE and MicroProfile.........................1
Chapter Objectives........................................................................................... 2
What Is a Specification? ...................................................................................2
Java/Jakarta EE Release History ...................................................................... 4
From Java EE to Jakarta EE ..............................................................................6
Jakarta EE 11 Key Features.........................................................................7
Jakarta EE Profiles ..................................................................................... 9
Jakarta EE and MicroProfile............................................................................13
Key Specifications in MicroProfile 7.0........................................................14
Benefits of MicroProfile 7.0 ....................................................................... 17
Jakarta EE and the Spring Framework ........................................................... 17
Why Jakarta EE? ............................................................................................ 18
Standardization and Stability .................................................................... 19
Openness and Community-Driven Development ........................................ 19
Ease of Development and Flexibility...........................................................19
Portability and Vendor Neutrality ............................................................... 19
Rich Ecosystem and Resources................................................................. 19
v
TABLE OF CONTENTS
AI, LLMs, and Jakarta EE.................................................................................20
The AI Revolution in Enterprise Software ...................................................20
Potential Intersection with Jakarta EE........................................................20
Looking Ahead .......................................................................................... 21
Summary........................................................................................................21
Key Takeaways ......................................................................................... 22
Chapter 2: Jakarta EE, Microservices, and the Cloud.........................23
Chapter Objectives......................................................................................... 24
Jakarta EE: A Brief Evolutionary Recap........................................................... 24
Introduction to Cloud-Native Development ......................................................26
Key Principles of Cloud-Native Development ............................................. 26
The Cloud Native Computing Foundation (CNCF) Definition ........................ 27
The Twelve-Factor App Methodology..........................................................29
Jakarta EE Features Supporting Cloud-Native Development............................ 32
Modularity and Microservices Support.......................................................32
Lightweight Nature and Containerization Benefits ..................................... 33
Specific APIs for Cloud-Native Development.............................................. 34
Microservices with Jakarta EE........................................................................ 37
Designing Microservices with Jakarta EE .................................................. 37
Implementing Microservices ..................................................................... 38
Inter-service Communication .................................................................... 39
Challenges and Solutions ..........................................................................39
Containerization and Jakarta EE ..................................................................... 40
Open Container Initiative (OCI)................................................................... 41
Creating a Dockerfile for a Jakarta EE Application ..................................... 41
Best Practices for Containerizing Jakarta EE Applications.......................... 42
Challenges and Considerations for Containerized Jakarta EE Applications... 43
vi
TABLE OF CONTENTS
Jakarta EE in Different Cloud Environments ....................................................44
Public Cloud Deployments.........................................................................44
Private Cloud and Hybrid Scenarios ...........................................................45
Key Considerations for Cloud Deployments................................................ 45
Comparison with Other Cloud-Native Java Frameworks ..................................46
Key Takeaways ......................................................................................... 49
Future Direction of Jakarta EE in the Cloud-Native Landscape ........................ 50
Continued Focus on Cloud-Native Features ............................................... 50
Integration with Emerging Technologies ....................................................50
Improved Developer Experience................................................................ 51
Stronger Alignment with Cloud-Native Standards...................................... 51
Continued Commitment to Stability and Backward Compatibility ............... 52
Community-Driven Innovation ................................................................... 52
Integration with GraalVM ........................................................................... 52
Shaping the Future: Your Role in Jakarta EE’s Evolution...................................53
The Jakarta EE Future Directions Initiative ................................................ 53
How You Can Contribute ............................................................................54
Summary........................................................................................................55
Key Takeaways ......................................................................................... 55
Chapter 3: Architecting Enterprise Applications with Jakarta EE ..... 57
Domain-Driven Design in Jakarta EE .............................................................. 59
Core Principles of Domain-Driven Design .................................................. 59
Mapping DDD Concepts to Jakarta EE Components ........................................ 61
Entities......................................................................................................62
Repositories.............................................................................................. 63
Domain Services....................................................................................... 64
Domain Events.......................................................................................... 68
vii
TABLE OF CONTENTS
Layered Architecture...................................................................................... 72
Layered Architecture in Jakarta EE: The Benefits....................................... 73
Presentation Layer.................................................................................... 75
Application/Service Layer..........................................................................77
Domain Layer ........................................................................................... 78
Persistence Layer ..................................................................................... 78
Architectural Decision-Making in Jakarta EE Projects..................................... 79
Performance............................................................................................. 79
Scalability
80
Maintainability
80
Security ....................................................................................................80
Interoperability ......................................................................................... 80
Compliance...............................................................................................81
Development Team Expertise .................................................................... 81
Time to Market ......................................................................................... 81
Case Study: Microservices vs. Monolithic Architecture...............................81
Synchronous vs. Asynchronous Communication........................................ 83
Documenting Architectural Decisions.........................................................85
Conclusion .....................................................................................................88
Chapter 4: Managing Dependencies with CDI..................................... 91
Understanding Inversion of Control................................................................. 92
Traditional vs. Inverted Control.................................................................. 92
Jakarta CDI as an IoC Container ................................................................ 93
An Overview of CDI in Jakarta EE 11 .............................................................. 94
Key Features of CDI ...................................................................................95
Jakarta CDI Activation.................................................................................... 97
The beans.xml Configuration File .............................................................. 97
Bean Discovery Modes ..............................................................................97
viii
TABLE OF CONTENTS
The CDI Container .......................................................................................... 99
Core Responsibilities
99
Transparent Operation
103
Jakarta CDI Beans and Contextual Instances ................................................ 104
CDI Bean Types ....................................................................................... 106
Jakarta CDI Beans and Contextual Instances........................................... 109
Scopes and Contexts ................................................................................... 110
Bean Proxying......................................................................................... 111
Built-In Scopes ....................................................................................... 114
Injection Points ............................................................................................ 121
Field Injection Point ................................................................................. 121
Constructor Injection ...............................................................................121
Method Injection..................................................................................... 124
Jakarta Enterprise Beans..............................................................................125
Qualifiers......................................................................................................127
Custom Qualifiers ................................................................................... 128
Built-In Qualifiers.................................................................................... 130
Jakarta CDI Producers ..................................................................................135
Producer Methods .................................................................................. 136
Producer Fields....................................................................................... 140
Qualifying Producers ...............................................................................142
CDI Producers: Caveats ...........................................................................144
Stereotypes..................................................................................................145
Lifecycle Callbacks ...................................................................................... 148
@PostConstruct...................................................................................... 149
@PreDestroy........................................................................................... 150
ix
TABLE OF CONTENTS
Jakarta CDI Interceptors ...............................................................................150
The Interceptor Annotation
151
The Interceptor Bean
152
Using Stereotypes with Interceptors ........................................................155
CDI Decorators ............................................................................................. 156
Why Decorators? .................................................................................... 156
Jakarta CDI Events....................................................................................... 160
The Event Object..................................................................................... 160
The Event Observer .................................................................................163
Asynchronous Events ..............................................................................164
Transactional Observers .......................................................................... 166
Qualifying Events.................................................................................... 168
Event Metadata....................................................................................... 174
Conditional Observer Methods ................................................................ 175
Summary......................................................................................................177
Key Takeaways ....................................................................................... 177
Chapter 5: Persistence with Jakarta EE Persistence........................179
Jakarta Persistence (JPA) .............................................................................180
The JPA Runtime .................................................................................... 181
Data Modeling ........................................................................................ 181
Data Persistence .................................................................................... 182
Querying
Data Modeling with JPA
182
182
The Simplest Unit ................................................................................... 182
Primary Key Generation...........................................................................184
Customizing Columns..............................................................................191
Mapping Temporal Types ......................................................................... 194
x
TABLE OF CONTENTS
Mapping Large Objects............................................................................196
Simple Field Types...................................................................................197
Mapping Enums...................................................................................... 198
Transient Fields ...................................................................................... 202
Field and Property Access ....................................................................... 203
Organizing with Inheritance .................................................................... 203
Embeddables.......................................................................................... 206
Relationships
210
Data Persistence
220
Persistence Unit ..................................................................................... 220
Persistence Context.................................................................................221
Transactions
222
EntityManager
222
Persisting Entities................................................................................... 223
Querying Data .............................................................................................. 234
Finding by Primary Key............................................................................235
Jakarta Persistence Query Language (JPQL) ........................................... 235
Criteria API.............................................................................................. 243
From Object-Relational to NoSQL Models......................................................247
Jakarta NoSQL ............................................................................................. 247
Goals of Jakarta NoSQL...........................................................................248
NoSQL Database Categories.................................................................... 248
Programming Model for Entity Classes ....................................................250
Modeling with Jakarta NoSQL ................................................................. 251
Data Access Layer in Jakarta NoSQL........................................................255
The Bridge: Jakarta Data ..............................................................................259
From Template Pattern to Repository Pattern .......................................... 259
xi
TABLE OF CONTENTS
Jakarta Data: Unifying Data Access .............................................................. 260
Features of Jakarta Data .........................................................................260
Repository Interfaces in Jakarta Data ......................................................261
Creating Custom Repositories ................................................................. 263
Querying in Jakarta Data......................................................................... 264
Integration with Jakarta Persistence and Jakarta NoSQL ..............................266
Comparing Persistence Options.................................................................... 267
Portability Considerations........................................................................ 267
When to Use Different Jakarta Database Technologies ..................................269
Summary......................................................................................................271
Key Takeaways ....................................................................................... 272
Chapter 6: REST with Jakarta REST.................................................. 275
Modeling REST Services ...............................................................................276
Core REST Architectural Principles...........................................................277
Resource Naming Patterns...................................................................... 278
Anti-patterns to Avoid..............................................................................279
Designing for Evolution............................................................................280
Modeling the User Resource ......................................................................... 282
Resource Organization..................................................................................283
The Root Resource ..................................................................................284
API Versioning with getClasses ............................................................... 284
A Jakarta REST Resource ........................................................................ 286
HTTP Methods ........................................................................................ 287
The Response Object...............................................................................310
Exception Mappers ...................................................................................... 312
The Jakarta REST Client................................................................................314
The MicroProfile REST Client ........................................................................ 317
xii
TABLE OF CONTENTS
Documenting REST APIs with OpenAPI ..........................................................322
API-Level Documentation ........................................................................ 323
Resource Documentation ........................................................................ 324
Schema Documentation ..........................................................................326
Generated Documentation....................................................................... 328
Summary......................................................................................................329
Key Takeaways ....................................................................................... 330
Chapter 7: Managing Configurations ................................................ 333
Jakarta EE Configuration Fundamentals........................................................334
Resource Injection.................................................................................. 334
Environment Entries ................................................................................335
Alternatives and Qualifiers ...................................................................... 336
The Need for Cloud-Native Configuration ................................................. 336
MicroProfile Config ...................................................................................... 337
The Config Specification..........................................................................337
Default Config Sources and Ordinals........................................................339
Custom Config Sources ...........................................................................339
Converters in MicroProfile Config............................................................ 342
Config Values ............................................................................................... 346
The Config Bean ..................................................................................... 347
Direct Injection ....................................................................................... 348
Optional Injection.................................................................................... 349
Dynamic Value Access.............................................................................349
ConfigValue Metadata .............................................................................352
Chapter Summary ........................................................................................ 353
Key Takeaways ....................................................................................... 353
xiii
TABLE OF CONTENTS
Chapter 8: Resilience with the Fault Tolerance API..........................355
The Evolution of Fault Tolerance ................................................................... 356
Fault Tolerance Patterns ...............................................................................357
Core Fault Tolerance Patterns.................................................................. 357
Failure Categories .................................................................................. 359
@Fallback ....................................................................................................361
Annotation Approach ...............................................................................361
Using a Fallback Handler......................................................................... 363
@Timeout.....................................................................................................365
@Retry .........................................................................................................368
Retry Behavior ........................................................................................ 370
Jitter and Delays..................................................................................... 370
Maximum Duration ..................................................................................371
Scope and Application ............................................................................. 371
@CircuitBreaker........................................................................................... 372
Closed State (Normal Operation) ............................................................. 372
Open State (Fail Fast) ..............................................................................372
Half-Open State (Recovery Testing)..........................................................373
Circuit Breaker Usage..............................................................................373
Failure Counting Rules ............................................................................375
Integration with Other Patterns ............................................................... 375
Managing Circuit State ............................................................................ 376
@Bulkhead...................................................................................................376
Semaphore-Style Bulkhead..................................................................... 377
Thread Pool-Style Bulkhead....................................................................377
Integration with Other Fault Tolerance Annotations ..................................378
Lifecycle Management ............................................................................379
xiv
TABLE OF CONTENTS
@Asynchronous ........................................................................................... 379
Basic Usage............................................................................................ 380
Integration with Other Fault Tolerance Annotations
380
Context and Exception Handling.............................................................. 381
Implementation Considerations............................................................... 381
Configuring Fault Tolerance with Config ........................................................382
Configuration Patterns.............................................................................382
Configuration Hierarchy...........................................................................383
Dynamic Properties .................................................................................383
Configuration Effect.................................................................................384
Summary......................................................................................................384
Chapter 9: Metrics for Jakarta EE Applications: Monitoring and
Observability ..................................................................................... 387
Understanding Observability.........................................................................388
The Three Pillars of Observability ............................................................ 389
Taking Count of Distributed Tracing with MicroProfile Telemetry Metrics ....... 390
The Structure.......................................................................................... 390
Metrics Data Format................................................................................391
The Metrics Registry ...............................................................................391
Using Metrics.......................................................................................... 392
Metrics Metadata ................................................................................... 409
Other MicroProfile Spec Metrics.............................................................. 411
CDI Stereotypes and Metrics ................................................................... 413
Distributed Tracing with Telemetry ............................................................... 414
Telemetry Data Collection Options........................................................... 415
MicroProfile Telemetry Deep Dive ........................................................... 418
xv
TABLE OF CONTENTS
Summary......................................................................................................425
Key Takeaways ....................................................................................... 426
Looking Ahead ........................................................................................ 426
Chapter 10: Taking a Pulse with Health Check................................. 427
Health Checks in Cloud Environments ...........................................................428
Health API Structure..................................................................................... 428
Accessing Health Check Procedures
429
The HealthCheck Interface
429
The HealthCheckResponse...................................................................... 430
Health and CDI ............................................................................................. 430
Health Check Qualifiers ...........................................................................431
Combining Health Checks ............................................................................. 436
Producing Health Checks .............................................................................. 438
Best Practices for Cloud Health Checks.........................................................442
Separate Concerns with Different Health Check Types ............................. 442
Keep Checks Fast and Efficient ............................................................... 442
Provide Meaningful Information .............................................................. 446
Implement Proper Error Handling............................................................ 447
Configure Appropriate Check Intervals ..................................................... 448
Use CDI Scopes Appropriately ................................................................. 449
Monitor Health Check Performance..........................................................449
Common Health Check Patterns ................................................................... 450
Startup State Verification......................................................................... 450
Dependency Chain Validation .................................................................. 450
Resource Health Monitoring .................................................................... 451
Self-Healing Status..................................................................................451
Asynchronous Health State ..................................................................... 451
xvi
TABLE OF CONTENTS
Composite Health Status .........................................................................452
Progressive Detail Level ..........................................................................452
Kubernetes Integration .................................................................................452
Understanding Probe Mapping ................................................................ 453
Probe Configuration Strategy .................................................................. 453
Failure Handling ..................................................................................... 454
Startup Probe Optimization ..................................................................... 454
Resource Considerations.........................................................................454
Zero-Downtime Deployments.................................................................. 454
Production Best Practices ....................................................................... 455
Monitoring and Debugging ...................................................................... 455
Summary......................................................................................................456
Key Takeaways ....................................................................................... 456
Chapter 11: Security with JWT ......................................................... 457
Introduction..................................................................................................457
Token-Based Authentication .........................................................................458
The Header ............................................................................................. 459
The Claims (or Body) ...............................................................................459
The Signature ......................................................................................... 460
The MicroProfile JWT ................................................................................... 463
MicroProfile JWT Security Process.......................................................... 464
MicroProfile JWT Usage ................................................................................ 470
Getting Information from Tokens ............................................................. 472
MicroProfile JWT and the SecurityContext.....................................................476
Summary......................................................................................................476
Key Takeaways ....................................................................................... 477
xvii
TABLE OF CONTENTS
Chapter 12: Testing with TestContainers .......................................... 479
The Theory of Application Testing ................................................................. 480
Types of Tests ......................................................................................... 480
Principles of Testing ................................................................................482
Testing in Jakarta EE.................................................................................... 484
Unit-Testing Jakarta EE Components .......................................................485
Integration Testing in Jakarta EE ............................................................. 490
Summary......................................................................................................495
Key Takeaways ....................................................................................... 496
Chapter 13: Jakarta EE Cloud-Native Deployment and Operations... 497
Cloud-Native Architecture for Jakarta EE.......................................................498
Core Concepts ........................................................................................ 499
Application Server Evolution ................................................................... 500
Kubernetes Deployment Patterns ................................................................. 501
Deployment Types .................................................................................. 502
Service Discovery and Load Balancing ....................................................503
Configuration Management ..................................................................... 506
Persistent Storage .................................................................................. 508
Scaling and High Availability......................................................................... 510
Horizontal Pod Autoscaling...................................................................... 510
High Availability Configuration................................................................. 513
Monitoring and Observability ........................................................................ 515
Metrics Collection................................................................................... 516
Distributed Tracing ..................................................................................518
Logging and Debugging ................................................................................519
Log Management.................................................................................... 519
Remote Debugging .................................................................................. 519
xviii
TABLE OF CONTENTS
Deployment Strategies..................................................................................520
Rolling Updates ...................................................................................... 521
Blue-Green Deployments.........................................................................521
Canary Releases..................................................................................... 522
Maintenance and Operations ........................................................................ 523
Health Management ................................................................................523
Backup and Recovery..............................................................................523
Summary......................................................................................................526
Key Takeaways ....................................................................................... 526
Chapter 14: Monoliths, Moduliths, and Microservices with
Jakarta EE: Architectural Patterns ................................................... 529
Architectural Patterns in Jakarta EE ............................................................. 530
Evolution of Enterprise Architecture Patterns........................................... 530
Jakarta EE’s Role in Supporting Different Architectures ........................... 531
Common Architectural Considerations .....................................................532
Monolithic Architecture ................................................................................. 533
Structure and Characteristics.................................................................. 534
Advantages............................................................................................. 536
Challenges.............................................................................................. 538
When to Choose Monolithic Architecture.................................................. 539
Modulithic Architecture.................................................................................541
Structure and Characteristics.................................................................. 542
Implementation with Jakarta EE ............................................................. 542
Advantages and Disadvantages .............................................................. 543
When to Choose Modulithic Architecture.................................................. 546
Microservices Architecture ...........................................................................548
Structure and Characteristics.................................................................. 548
Implementation with Jakarta EE ............................................................. 549
xix
TABLE OF CONTENTS
Advantages and Disadvantages .............................................................. 551
When to Choose Microservices Architecture............................................ 553
Choosing the Right Pattern ...........................................................................556
Decision Framework................................................................................556
Migrating Architectural Patterns
559
Monolithic to Modulithic
559
Modulithic to Microservices .................................................................... 559
Monolithic to Microservices .................................................................... 559
Implementation Strategies ...................................................................... 560
Key Considerations..................................................................................562
Summary......................................................................................................566
Key Takeaways ....................................................................................... 566
Chapter 15: AI, LLMs, and Jakarta EE: The Next Frontier ................ 569
A Brief History of Artificial Intelligence (AI) .................................................... 570
AI and Machine Learning ..............................................................................571
Advantages of AI/ML
572
Automation and Efficiency....................................................................... 572
Pattern Recognition and Insight Generation............................................. 572
Personalization and Recommendation Systems ...................................... 573
Handling Complex and Unstructured Data................................................ 573
Disadvantages of AI and ML..........................................................................573
Data Dependency and Quality ................................................................. 573
Interpretability and Explainability ............................................................ 574
Limited Contextual Understanding ...........................................................574
Job Displacement and Ethical Considerations ......................................... 574
xx
TABLE OF CONTENTS
Machine Learning ........................................................................................ 575
Machine Learning Models ....................................................................... 575
Java AI/ML Frameworks for Jakarta EE Applications..................................... 578
Machine Learning................................................................................... 579
Neural Networks..................................................................................... 581
Expert Systems....................................................................................... 584
Natural Language Processing.................................................................. 587
AI Orchestration...................................................................................... 594
Best Practices for Jakarta EE Integration................................................. 595
Example Fraud Detection System............................................................ 598
The Future of AI in Jakarta EE Applications ...................................................601
Standardization and Integration .............................................................. 601
Evolving Deployment Architectures
602
Edge Computing and AI
602
Large Language Models in Enterprise Applications
602
AI-Enhanced Development Experience.....................................................603
Autonomous Enterprise Systems ............................................................ 603
Responsible AI in Enterprise Applications ................................................ 603
Conclusion ...................................................................................................604
Key Takeaways ....................................................................................... 605
Index.................................................................................................. 607
xxi
About the Authors
Luqman Saeed is a senior Java developer
with 7+ years of experience building scalable
cloud-native applications using Spring Boot,
Quarkus, and Jakarta EE. He is proficient
in various software architectural styles and
enterprise development practices. He is a
published author and creator of Udemy’s
largest enterprise Java course, reaching
20,000+ developers globally. He is also a
technical writer and conference speaker passionate about simplifying
complex concepts and driving innovation in software engineering.
Luqman is committed to sharing knowledge with the developer
community.
Ghazy Abdallah is a passionate enterprise Java developer, founder of the
Sudan Java User Group (SudanJUG), and a tinkerer. He enjoys the use of
modern cloud infrastructure to deliver enterprise applications and site
reliability engineering. He spends his time learning and sharing the latest
in cloud-native development.
xxiii
About the Technical Reviewer
Josh Juneau has been developing enterprise solutions since the early days
of Java EE. Application and database development have been his focus
since the start of his career. He became an Oracle database administrator
and adopted PL/SQL and Java for performing administrative tasks and
developing applications. Today, he primarily develops enterprise solutions
utilizing Jakarta EE and other alternative languages, such as Kotlin and
Groovy, running on Podman. In 2006, Josh began devoting time to the
Jython Project as editor and publisher of the Jython Monthly newsletter.
In late 2008, he began a podcast dedicated to the Jython programming
language. Josh was the lead author of The Definitive Guide to Jython
(Apress, 2010). Josh has since authored several other books on Java and
Jakarta EE. He has also been a co-host for the Offheap and Stackd podcasts
for a number of years. He works as a senior software engineer, and he
also writes technical articles for Oracle and OTN. He has been an active
member of the Java community, helping to promote the Java platform
and Jakarta EE. When not coding or writing, Josh enjoys spending time
with his family, especially swimming, fishing, playing ball, and watching
movies. To hear more from Josh or to check out some of his work, follow
his GitHub at github.com/juneau001. You can also follow him on Twitter at
@javajuneau.
xxv
Introduction
Enterprise Java has undergone a remarkable transformation since its
inception. What began as a heavyweight platform designed for monolithic
applications has evolved into a flexible, modular ecosystem perfectly
suited for today's cloud-native world. This evolution reflects the changing
needs of businesses and the technological shifts that have redefined how
we build, deploy, and maintain enterprise applications.
Jakarta EE, the successor to Java EE, stands at the center of this
transformation. After Oracle transferred Java EE to the Eclipse Foundation
in 2017, the platform was reborn with a renewed focus on innovation,
community involvement, and adaptability to modern development
paradigms. This transition marked more than a change in stewardship—
it represented a fundamental shift in philosophy toward openness and
agility.
Today's enterprise applications face challenges unimaginable
when Java EE was first conceived. Cloud computing has become the
default deployment model, pushing developers to rethink application
architecture. Microservices have replaced monoliths as the preferred
architectural pattern for complex systems. Container orchestration
platforms like Kubernetes have become standard infrastructure. And
the demand for resilient, observable, and secure applications has never
been higher.
Against this backdrop, Jakarta EE has proven remarkably adaptable.
Its core principles of portability, compatibility, and enterprise-grade
reliability remain as valuable as ever, while its embrace of modern
patterns and integration with cloud-native technologies make it uniquely
positioned to bridge the gap between established enterprise systems and
cutting-edge innovation.
xxvii
INTRODUCTION
This second edition explores Jakarta EE's expanding role in this
dynamic landscape, building on the foundation established in the
first edition while incorporating the latest advancements and best
practices that have emerged since. We'll examine how its specifications
provide a solid foundation for building applications that can thrive in
containerized environments, scale elastically with demand, and integrate
with the broader cloud-native ecosystem. From dependency injection
to Representational State Transfer (REST) services, from persistence to
security, Jakarta EE offers a comprehensive toolkit for tackling the most
demanding enterprise challenges.
Beyond the current state of enterprise Java, we'll also look toward
the horizon. The rise of artificial intelligence (AI) and large language
models (LLMs) presents new opportunities and challenges for enterprise
applications. How will Jakarta EE applications interact with AI services?
How might generative AI change the way we design and implement
business logic? These questions point to exciting possibilities for the future
of enterprise development.
Throughout this second edition, we maintain our practical approach,
balancing theoretical concepts with hands-on examples while updating
content to reflect the latest Jakarta EE specifications and industry
trends. Each chapter builds upon the last, gradually assembling a
complete picture of modern Jakarta EE development. Whether you're an
experienced Java developer transitioning to cloud-native architectures,
a reader of the first edition looking to update your knowledge, or a
newcomer seeking to understand enterprise Java, this book will provide
you with the knowledge and skills needed to succeed in today's rapidly
evolving technology landscape.
The enterprise Java ecosystem continues to evolve, driven by the
changing demands of business and advances in technology. Jakarta EE
stands ready to meet these challenges, offering a path forward that honors
the past while embracing the future. Let's begin our exploration of this
dynamic and powerful platform.
xxviii
CHAPTER 1
The Theory of Jakarta
EE and MicroProfile
Jakarta EE (formerly Java EE) is a set of community-developed, abstract
specifications that together form a platform for developing end-to-end,
multi-tier enterprise applications. Jakarta EE is built on the Java Standard
Edition and aims to provide a stable, reliable, and vendor-neutral platform
for the development of cloud-native enterprise applications.
Born from the legacy of Java EE and its predecessors, Jakarta EE has
adapted to meet the demands of modern cloud-native architectures while
maintaining the stability and standardization that enterprises require. This
chapter explores the journey of Jakarta EE, from its origins to its current
state as a flexible and powerful platform for enterprise Java development.
We’ll look into its key features, compare it with the Spring Framework,
and look ahead to its potential future in an era of artificial intelligence
and large language models. Whether you’re a seasoned Java developer, a
system architect, or a decision-maker evaluating enterprise technologies,
this chapter will provide you with a comprehensive understanding of
Jakarta EE’s role in today’s software ecosystem.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_1
1
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Chapter Objectives
By the end of this chapter, you will
1. Understand the evolution of Jakarta EE from its Java 2
Platform, Enterprise Edition (J2EE) roots to its
current state.
2. Understand the concept of specifications in Jakarta
EE and their importance.
3. Know the key features and improvements in
Jakarta EE 11.
4. Understand the relationship between Jakarta EE and
MicroProfile.
5. Recognize the differences and similarities between
Jakarta EE and the Spring Framework.
6. Appreciate the advantages of choosing Jakarta EE
for enterprise application development.
7. Get an overview of the potential impact of AI and
large language models on Jakarta EE development.
This chapter lays the foundation for understanding Jakarta EE’s role
in modern enterprise Java development, setting the stage for the practical
applications covered in subsequent chapters of this book.
What Is a Specification?
Jakarta EE comprises individual specifications, each covering a specific API,
grouped under an umbrella specification for each release. A specification
outlines the expected behavior of APIs, serving as a blueprint. Implementations
actualize these specifications, allowing developers to code against the abstract
specification and run their code on different implementations.
2
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Historically, Java EE specifications were developed under the Java
Community Process (JCP) through Java Specification Requests (JSRs).
GlassFish served as the reference implementation for the Java EE umbrella
specification, with other full, independently developed implementations
like WildFly, Open Liberty, and Payara available to choose from.
From Java EE 8 onward, the specification process moved to the Eclipse
Foundation, along with the GlassFish project. The concept of reference
implementations evolved into compatible implementations, emphasizing
cross-vendor neutrality and compatibility.
This shift marked a significant change in the specification
development process. The Jakarta EE Specification Process (JESP),
adopted by the Jakarta EE Working Group, now governs the development
of Jakarta EE specifications. The JESP is based on the Eclipse Foundation
Specification Process (EFSP) v1.3, with specific modifications tailored to
the needs of the Jakarta EE ecosystem.
Key aspects of the JESP include
•
Strict approval processes for modifications to the
specification process
•
Defined ballot periods for various stages of
specification development
•
Annual review requirements for active specification
projects
•
Mandated migration from the javax to jakarta
namespace
•
Clear guidelines on the use of the jakarta namespace
The JESP ensures a structured, community-driven approach to
specification development, maintaining the open and collaborative
spirit of Jakarta EE while adapting to the needs of modern enterprise Java
development.
3
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
To better understand the evolution of Jakarta EE and its predecessor
Java EE, let’s take a chronological journey through its release history. This
timeline highlights major versions and their significant features, providing
context for the platform’s growth from its J2EE roots to the modern Jakarta
EE ecosystem. Table 1-1 outlines major releases, their dates, and notable
characteristics.
Java/Jakarta EE Release History
Table 1-1. Chronological Java /Jakarta EE Release History
Java EE
Release
Version
Date
Key Features
JSR/
Notes
Jakarta
Version
J2EE 1.2
J2EE 1.3
December
Introduction of Enterprise —
First release of the
12, 1999
JavaBeans (EJBs)
platform
September Java Connector
24, 2001
58
—
151
—
244
Rebranding from
Architecture (JCA), Java
Message Service (JMS),
EJBs improvements
J2EE 1.4
November
Adherence to WS-I’s
11, 2003
Basic Profile 1.0 for
interoperable web services
Java EE 5
May 11,
Java annotations
2006
Java EE 6
J2EE to Java EE
Last major
December
CDI (Contexts and
10, 2009
Dependency Injection)
release under Sun
managed security, REST
Microsystems
316
APIs
(continued)
4
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Table 1-1. (continued)
Java EE
Release
Version
Date
Key Features
JSR/
Notes
Jakarta
Version
Java EE 7
May 28,
WebSocket, JSON
2013
processing APIs, HTML5
after Oracle
support in JSF
acquired Sun
342
First major release
Microsystems
Java EE 8
August 31,
HTTP/2, CDI-based
2017
security
366
Partly the result
of pressure from
community groups,
reduced scope
Jakarta
September Compatibility with Java
EE 8
10, 2019
8
First release
under the Eclipse
EE 8
Foundation
Jakarta
December
Namespace change
EE 9
8, 2020
from javax. to jakarta.*,
milestone,
removal of deprecated
preparation for
APIs*
future innovations
Jakarta
September Jakarta EE Core Profile,
EE 10
22, 2022
9
10
Significant
Modernization
CDI Lite, updates to
for cloud-native
various specifications
development,
improved developer
productivity
Jakarta
EE 11
Q4 2024
New specification:
11
Continued focus
Jakarta Data 1.0, 16
on cloud-native
updated specifications
development
including Persistence,
Concurrency, Security
5
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
From Java EE to Jakarta EE
The increasing gaps between Java EE releases, culminating in a four-year
hiatus between versions 7 and 8, raised concerns within the community
about Oracle’s commitment to the platform. In response, Oracle decided
to transfer Java EE to an open source foundation in 2017, choosing the
Eclipse Foundation after consulting with key stakeholders like RedHat
and IBM.
This monumental transfer was executed in three main stages:
1. Transfer of API and implementation code
2. Transfer of Test Compatibility Kit (TCK) code and
establishment of a new specification process
3. Refactoring of API package names and transfer of
specification documents
The process involved moving to the jakarta.* namespace, introducing
the Jakarta EE Specification Process (JESP), and rebranding Java EE as
Jakarta EE. The first release under this new regime, Jakarta EE 8, was
essentially Java EE 8 without under-the-hood changes. Jakarta EE 9 and 9.1
followed, introducing the full namespace change and support for Java 11.
Jakarta EE 10, released in 2022, continued the platform’s evolution
toward cloud-native development, introducing the Core Profile and
support for Java 17. This release set the stage for further innovations in
enterprise Java development.
Building on this foundation, Jakarta EE 11 represents the latest step
in the platform’s journey, bringing significant updates and new features
that reflect the changing landscape of enterprise Java development. Let’s
explore the key features of Jakarta EE 11.
6
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Jakarta EE 11 Key Features
Continuing the evolution of Jakarta EE, version 11 brings significant
updates and new features that reflect the changing landscape of enterprise
Java development. Let’s explore the key features of Jakarta EE 11
(Table 1-2).
Table 1-2. Jakarta EE 11 Features
Category
Specification/ Feature
Jakarta EE 11 Changes
Modernization and
Several Specifications
Removal of references to the
deprecated SecurityManager class
Cleanup
Jakarta Annotations and
Removal of the deprecated
Jakarta RESTful Web
@ManagedBean annotation
Services
Jakarta Data 1.0
New Specification
Provides standardized data access
with the repository pattern for easy
database access
Support for CDI extensions
New BasicRepository interface
New annotations: @Insert,
@Update, @Delete, @Save
Jakarta Data Query Language
(JDQL) complementing JPQL
(continued)
7
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Table 1-2. (continued)
Category
Specification/ Feature
Jakarta EE 11 Changes
Enhanced
Jakarta Concurrency 3.1
Integration with JEP 444, Virtual
Threads (JDK 21)
Concurrency Support
Support for Java Flow and
MicroProfile Reactive Streams
Operators
New @Schedule annotation
replacing the one from the retired
Jakarta Enterprise Beans spec
More CDI-centric approach, allowing
injection of default resource
implementations
Jakarta Persistence Jakarta Persistence 3.2
Support for Java record types as
Enhancements
embeddable classes
New methods added to key classes
and interfaces
Migration to the java.time API,
deprecating older date and time
classes
Improved Security
Features
Jakarta Security 4.0
New API supporting user choice of
authentication mechanism
Qualifiers for built-in authentication
mechanisms
New in-memory identity store
(continued)
8
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Table 1-2. (continued)
Category
Specification/ Feature
Jakarta EE 11 Changes
Upcoming integration with
MicroProfile JWT Authentication via
MicroProfile JWT Bridge
Validation
Jakarta Validation 3.1
Support for Java records
Jakarta Contexts and
Support for @Priority annotation on
Dependency Injection
producers
Improvements
CDI Enhancements
4.1
These updates demonstrate Jakarta EE’s commitment to staying
current with modern Java features and cloud-native development
practices. They provide you with powerful tools to build reliable, scalable,
and maintainable enterprise applications on the Java platform. To further
enhance flexibility and cater to different development needs, Jakarta EE
offers three profiles, each tailored to specific scenarios. Let’s explore these
Jakarta EE profiles and how they allow you to choose the most suitable set
of specifications for your projects.
Jakarta EE Profiles
A Jakarta EE profile is a defined subset of the Jakarta EE specifications
tailored for specific types of applications and deployment scenarios.
Profiles provide a standardized way to group related technologies, allowing
you to work with a more focused set of APIs that are relevant to your
particular development needs.
Jakarta EE offers three different profiles, each designed to cater to
different application requirements and development contexts.
9
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Jakarta EE Platform
The Jakarta EE Platform is the most comprehensive profile, comprising
the full set of Jakarta EE specifications. It is designed for developers
who require the complete range of Jakarta EE technologies for building
complex, multi-tier enterprise applications. This profile provides access
to all Jakarta EE APIs, offering the highest level of functionality and
flexibility for large-scale enterprise systems. Figure 1-1 shows the gamut of
specifications that make up the Platform Profile, with expected updates/
additions for Jakarta EE 11.
Figure 1-1. Jakarta EE Full Platform
Jakarta EE Web Profile
The Jakarta EE Web Profile is a subset of the Full Platform, specifically
targeted at web application development. It contains a set of web
technologies essential for creating modern web applications, including
10
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
•
Jakarta Servlet
•
Jakarta Server Faces
•
Jakarta Enterprise Beans Lite
•
Jakarta RESTful Web Services
•
Jakarta Persistence
•
Jakarta Contexts and Dependency Injection
•
Jakarta Bean Validation
This profile is ideal for building web applications that don’t require the
full enterprise feature set, offering a more lightweight alternative to the Full
Platform. Figure 1-2 shows the full set of specifications that make up the
Web Profile, with expected updates/additions for Jakarta EE 11.
Figure 1-2. Jakarta EE Web Profile
11
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Jakarta EE Core Profile
Introduced in Jakarta EE 10, the Core Profile is the most lightweight of
the three, targeting smaller runtimes suitable for microservices and
applications that benefit from ahead-of-time compilation. It provides a
minimal basis for cloud-native runtimes, including those that support
build-time applications. The Core Profile includes a limited set of
specifications, such as
•
Jakarta Contexts and Dependency Injection Lite
•
Jakarta RESTful Web Services
•
Jakarta JSON Processing
•
Jakarta JSON Binding (JSON-B)
•
Jakarta Annotations
This profile is designed for developers working on microservices,
serverless applications, or any scenario where a minimal, cloud-native
runtime is desired. Figure 1-3 shows the Core Profile specs along with
expected changes for Jakarta EE 11.
12
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Jakarta EE 11 Core Profile
JAKARTA E
Updated
Not Updated
New
Figure 1-3. Jakarta EE Core Profile
Each profile addresses different application needs, from full-scale
enterprise systems to lightweight microservices. With these profiles,
Jakarta EE provides you with the flexibility to choose the most appropriate
set of specifications for your projects, ensuring efficient development
and optimized runtime environments for various application types and
deployment scenarios.
Jakarta EE and MicroProfile
Jakarta EE and MicroProfile have evolved to address the needs of modern,
cloud-native application development. While Jakarta EE originated in the
era of monolithic architectures, it has adapted to support microservices
development. However, the Java Community Process (JCP) that governed
Jakarta EE’s evolution struggled to keep pace with rapid industry changes.
13
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
To bridge this gap, the MicroProfile project was launched at JavaOne
2016 by an independent group of Java EE vendors. It aimed to augment
Jakarta EE with specifications tailored for cloud-native, microservicesbased applications. MicroProfile built upon Jakarta EE, incorporating a
subset of its APIs along with new, specialized specifications.
The relationship between Jakarta EE and MicroProfile continues to
evolve. With the release of MicroProfile 7.0, we see further alignment and
integration between these two important Java enterprise ecosystems:
•
MicroProfile 7.0 now declares a dependency on
Jakarta EE 10 Core Profile instead of packaging it,
strengthening the connection between the platforms.
•
MicroProfile Metrics is no longer a MicroProfile
component specification. It has been replaced
by MicroProfile Telemetry 2.0, which offers
comprehensive capabilities for metrics, logs, and
tracing based on the OpenTelemetry (OTel) project.
•
MicroProfile Telemetry 2.0 and OpenAPI 4.0 introduce
backward-incompatible changes. REST Client 4.0,
while a major release, only has changes related to
alignment with Jakarta EE 10 Core Profile.
Key Specifications in MicroProfile 7.0
Figure 1-4 illustrates the key changes in MicroProfile 7.0.
14
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Open
Tracing 3.0
LRA 2.0
Reactive
Messaging
3.0 ‘
GraphQL
2.0
Reactive
Streams
Operators 3.0
Context
Propagation
1.3
Metrics 5.1
Standalone
Figure 1-4. MicroProfile 7.0 changes
These changes reflect the ongoing efforts to create a more cohesive
and powerful set of tools for developing cloud-native Java applications.
MicroProfile 7.0 comprises several key specifications shown in Table 1-3.
Table 1-3. MicroProfile 7.0 Spec Versions
Specification
Version
Description
MicroProfile
3.1
Provides a standardized way to externalize configuration
for Java microservices. Allows applications to read
Config
configuration properties from various sources like
property files, environment variables, system properties,
etc.
MicroProfile
4.1
Provides patterns for building resilient microservices,
handling potential failures with techniques like retries,
Fault Tolerance
timeouts, circuit breakers, and bulkheads.
MicroProfile
Health
4
Defines a standard way to check the health of a
microservice, enabling orchestration tools like Kubernetes
to monitor service health and react to failures.
(continued)
15
THE THEORY OF JAKARTA EE AND MICROPROFILE
CHAPTER 1
Table 1-3. (continued)
Specification
Version
Description
MicroProfile
2.1
Offers a mechanism for securing microservices using
JWT
JSON Web Tokens (JWTs) for authentication and
Authentication
authorization.
MicroProfile
4
Facilitates the generation and documentation of OpenAPI
specifications for microservices, making it easier to
OpenAPI
understand and interact with the service APIs.
MicroProfile
2
Provides a unified framework for capturing metrics,
logs, and distributed traces from microservices, aiding
Telemetry
in monitoring, troubleshooting, and understanding
application behavior.
MicroProfile
4
interacting with other microservices.
REST Client
Jakarta EE 10
Core Profile
Simplifies the development of type-safe REST clients for
—
Defines the core set of APIs for building Java enterprise
applications, providing foundational components for web
applications, messaging, and persistence.
Note
MicroProfile Metrics is now a standalone specification and
is no longer included in MicroProfile 7.0. MicroProfile Telemetry 2.0
replaces its functionality within the core set of specifications.
16
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Benefits of MicroProfile 7.0
This release offers several benefits:
•
Extensive integration of cloud-native computing
features
•
Vendor-neutral implementations ensuring code
portability and runtime interoperability
•
Annotation-based and programmatic APIs
•
Developer tools including MicroProfile Starter, VS Code
Extension Pack, IntelliJ plugin, and a CLI for project
generation
This combination of Jakarta EE and MicroProfile offers you a powerful
toolkit for building cloud-native Java applications. However, it’s not the
only option in the Java ecosystem. Another significant player in enterprise
Java development is the Spring Framework. Let’s explore how Jakarta EE
compares to and interacts with Spring, giving you a broader perspective on
the Java enterprise landscape.
Jakarta EE and the Spring Framework
A discussion of Jakarta EE’s history would be incomplete without
examining the Spring Framework. Early J2EE was complex, requiring
extensive XML configurations and component extensions. This led to its
reputation as an arcane platform used only by well-funded companies.
Rod Johnson’s 2002 book Expert One-on-One J2EE Design and
Development proposed increased use of dependency injection and plain
old Java objects (POJOs), contrasting with J2EE’s approach. The book’s
success led Johnson, along with Juergen Hoeller and Yann Caroff, to create
the Spring Framework in 2003. Spring quickly became popular, offering a
fresh alternative to J2EE for enterprise Java development.
17
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
As J2EE evolved into Java EE, it became more metadata-driven,
drawing inspiration from Spring with annotations and sensible defaults.
Java EE 7 significantly improved developer productivity compared with
J2EE, adopting CDI and a streamlined EJBs API similar to Spring’s original
patterns.
Meanwhile, Spring grew beyond its initial Inversion of Control (IoC)
role to encompass end-to-end application development. This growth
ironically made Spring more complex, akin to early J2EE.
In 2012, the Spring Boot project was initiated to simplify Spring’s
configuration, much like Spring initially simplified J2EE development.
Today, Jakarta EE and Spring are both productive enterprise Java
platforms, each influencing the other’s evolution. Their shared J2EE roots
make them more complementary than competitive. Understanding their
history reveals their similarities and the ease with which you can transfer
knowledge between them.
Why Jakarta EE?
You have so far taken a historical tour of Jakarta EE and how it relates
to MicroProfile. You have also looked at Spring from the perspective of
Jakarta EE. Together, these two platforms form the dominant options for
enterprises in the Java ecosystem. The Java platform still does have even
more frameworks out there for developing all kinds of applications.
As a Java developer, CTO, or the platform architect of an enterprise,
you are spoilt for choice when it comes to frameworks and platforms for
software development. A question you might be asking yourself is, Why
should I choose Jakarta EE as my primary software development platform?
What makes it a better choice?
18
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Standardization andStability
Jakarta EE specifications undergo rigorous peer review and testing,
ensuring long-term reliability and consistent behavior across different
implementations. This standardization is important for long-lived
enterprise applications and provides a stable foundation complemented
by MicroProfile’s innovative features.
Openness and Community-Driven Development
The Jakarta EE Specification Process allows anyone to contribute, fostering
innovation while maintaining backward compatibility. The code-first
approach ensures timely feedback and efficient resource usage.
Ease of Development and Flexibility
Jakarta EE offers minimal configuration requirements and follows
convention over configuration principles. Its modular nature allows you to
choose specific APIs as needed, scaling from lightweight microservices to
full-scale enterprise applications.
Portability and Vendor Neutrality
Applications developed using Jakarta EE standards can run on any
compatible implementation with minimal changes, preventing vendor
lock-in and enhancing deployment flexibility.
Rich Ecosystem and Resources
Jakarta EE benefits from extensive documentation, including official tutorials
and community-contributed resources. Regular conferences and a vibrant
developer community provide ongoing support and knowledge sharing.
19
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Jakarta EE’s strengths position it well for current enterprise needs.
However, as technology evolves, so too must our development platforms.
Emerging technologies like AI and large language models (LLMs) present
new opportunities for innovation in enterprise Java development. Let’s
briefly explore how Jakarta EE might integrate with these cutting-edge
technologies to shape the future of enterprise applications.
AI, LLMs, and Jakarta EE
As we look to the future of enterprise Java development, the integration of
artificial intelligence (AI) and large language models (LLMs) with Jakarta
EE presents exciting possibilities. This convergence has the potential to
upend how we build, deploy, and manage enterprise applications.
The AI Revolution in Enterprise Software
AI, particularly machine learning (ML) and deep learning, has already
made significant inroads in various domains of software development.
From predictive analytics to natural language processing, AI technologies
are enhancing the capabilities of applications across industries. LLMs,
a subset of AI focusing on processing and generating human-like text,
have recently gained prominence with models like GPT (Generative Pre­
trained Transformer) showcasing remarkable language understanding and
generation capabilities.
Potential Intersection with Jakarta EE
Jakarta EE, with its reliable infrastructure for building scalable, secure,
and distributed enterprise Java applications, provides an excellent
foundation for integrating AI and LLM capabilities. Some potential areas of
integration include
20
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
1. Intelligent Business Logic: AI models could be
embedded within Jakarta EE applications to provide
more sophisticated decision-making capabilities,
enhancing traditional rule-based systems.
2. Natural Language Interfaces: LLMs could power
advanced chatbots or voice interfaces for Jakarta
EE applications, improving user interaction and
accessibility.
3. Code Generation and Optimization: AI could assist
in generating boilerplate code, optimizing database
queries, or suggesting performance improvements
in Jakarta EE applications.
4. Predictive Maintenance: Machine learning models
could be integrated to predict system failures or
performance bottlenecks in Jakarta EE deployments.
5. Enhanced Security: AI could be employed to improve
threat detection and response in Jakarta EE applications,
adapting to new security challenges in real time.
Looking Ahead
The convergence of AI, LLMs, and Jakarta EE marks a new frontier in
enterprise Java development. Future chapters will explore options for
integrating AI and LLMs into Jakarta EE applications.
Summary
Jakarta EE has evolved significantly from its J2EE roots, emerging as a
robust, flexible, and modern platform for enterprise Java development.
This journey reflects the changing landscape of software architecture, from
monolithic applications to cloud-native microservices.
21
CHAPTER 1
THE THEORY OF JAKARTA EE AND MICROPROFILE
Key Takeaways
1. Jakarta EE 11 brings substantial improvements,
including enhanced concurrency support, new data
access APIs, and better alignment with modern Java
features.
2. The platform’s three profiles—Core, Web, and Full—
offer tailored solutions for different application
needs, from lightweight microservices to complex
enterprise systems.
3. Jakarta EE’s symbiotic relationship with MicroProfile
provides a comprehensive toolkit for cloud-native
development, balancing stability with innovation.
4. While sharing historical roots with the Spring
Framework, Jakarta EE offers unique advantages in
standardization, portability, and vendor neutrality.
5. The potential integration of AI and large language
models with Jakarta EE opens new frontiers in
enterprise application capabilities.
As we move forward, Jakarta EE’s commitment to open standards,
community-driven development, and adaptability to emerging
technologies positions it as a cornerstone of enterprise Java development.
This foundation sets the stage for our next chapter, where we’ll dive into
Jakarta EE’s role in the cloud-native ecosystem.
22
CHAPTER 2
Jakarta EE,
Microservices,
and the Cloud
Cloud-native application development has become the cornerstone
of modern enterprise software engineering. As we explored in Chapter
1, Jakarta EE has evolved significantly from its J2EE roots to meet the
demands of this new paradigm. This chapter explores the relationship
between Jakarta EE and the cloud-native landscape, examining how
Jakarta EE’s modularity, lightweight nature, and industry-standard feature
set make it a viable option for building microservices and deploying them
in cloud environments.
We’ll explore the journey of Jakarta EE toward cloud-native
compatibility, dissect its key features that support cloud-native
development, and investigate its role in microservices architecture and
containerization. By the end of this chapter, you’ll have a comprehensive
understanding of how Jakarta EE positions itself as a powerful platform for
cloud-native enterprise Java development.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_2
23
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Chapter Objectives
By the end of this chapter, you will
1. Understand the core principles of cloud-native
development and how they relate to Jakarta EE.
2. Recognize Jakarta EE’s evolution toward cloud­
native compatibility.
3. Identify key Jakarta EE features that support cloud­
native application development.
4. Understand how Jakarta EE facilitates microservices
architecture.
5. Understand the role of Jakarta EE in
containerization and different cloud environments.
6. Compare Jakarta EE with other cloud-native Java
frameworks.
7. Gain insight into the future direction of Jakarta EE in
the cloud-native landscape.
This chapter builds upon the historical context provided in Chapter 1,
offering a practical perspective on how Jakarta EE has adapted to meet the
needs of modern, cloud-native enterprise application development.
Jakarta EE: A Brief Evolutionary Recap
Jakarta EE’s journey began in 1999 with the introduction of Java 2
Platform, Enterprise Edition (J2EE) by Sun Microsystems. This platform
was designed to provide a comprehensive, standardized environment for
developing large-scale, distributed enterprise applications.
24
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Key milestones in Jakarta EE’s evolution include
1. J2EE 1.2 (1999): The initial release, bringing together
various enterprise Java technologies under one
umbrella
2. Java EE 5 (2006): Marked the rebranding from J2EE
to Java EE, introducing annotations and simplifying
development
3. Java EE 7 (2013): Enhanced developer productivity
and HTML5 support
4. Java EE 8 (2017): The last release under Oracle’s
stewardship, featuring enhanced security and
JSON support
5. Jakarta EE 8 (2019): Marked the transfer of Java EE
to the Eclipse Foundation and its rebranding as
Jakarta EE
6. Jakarta EE 9 (2020): Introduced the namespace
change from javax.* to jakarta.*, setting the stage for
future innovations
7. Jakarta EE 10 (2022): Introduced the Core Profile,
further enhancing cloud-native capabilities
8. Jakarta EE 11 (2024): Brings significant updates
including a new data access specification (Jakarta
Data 1.0), enhanced concurrency support, and
updates to Persistence, Security, and other
specifications, continuing the focus on cloud-native
development
25
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Throughout this evolution, Jakarta EE has maintained its commitment
to stability, standardization, and vendor neutrality. It has adapted from its
origins in monolithic application development to modern cloud-native
principles and microservices architecture.
The platform now offers three distinct profiles—Full Platform, Web
Profile, and Core Profile—catering to different application needs, from
complex enterprise systems to lightweight microservices. This flexibility,
combined with MicroProfile’s set of cloud-native specifications, positions
the platform as a versatile choice for modern enterprise Java development.
As we dive deeper into cloud-native development in this chapter,
we’ll see how this evolutionary journey has prepared Jakarta EE to meet
the challenges of today’s distributed, scalable, and resilient application
architectures.
Introduction to Cloud-Native Development
Cloud-native development marks a new way of creating and managing
applications. It uses the benefits of cloud computing to build and run
applications that can easily grow and adapt in various environments like
public, private, and hybrid clouds.
Key Principles of Cloud-Native Development
Cloud-native development is built upon a set of core principles that
guide the creation of scalable, resilient, and flexible applications. These
principles address the unique challenges of developing and deploying
software in distributed, dynamic cloud environments. As we explore these
key principles, we’ll see how Jakarta EE has evolved to support each of
them, positioning itself as a reliable platform for cloud-native enterprise
Java development:
26
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
1. Microservices Architecture: Applications are
decomposed into smaller, loosely coupled services
that can be developed, deployed, and scaled
independently.
2. Containers: Applications and their dependencies
are packaged in lightweight, portable containers,
ensuring consistency across different environments.
3. Dynamic Orchestration: Container orchestration
tools like Kubernetes automate the deployment,
scaling, and management of containerized
applications.
4. Continuous Delivery: Emphasis on automating
the software delivery process, enabling frequent,
reliable releases of code to production.
5. DevOps Culture: Promotes collaboration between
development and operations teams, fostering a
culture of shared responsibility and rapid iteration.
The Cloud Native Computing Foundation
(CNCF) Definition
The CNCF defines cloud-native technologies as those that “empower
organisations to build and run scalable applications in modern, dynamic
environments such as public, private, and hybrid clouds.” This approach
emphasizes the following:
•
Containerized Services: Applications and their
dependencies are packaged in containers, which are
lightweight, standalone executable software packages.
Containerization ensures consistency across different
development, testing, and production environments,
27
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
simplifying deployment and scaling. Jakarta EE
applications can be easily containerized, allowing
developers to use this key cloud-native principle.
•
Dynamically Orchestrated: Container orchestration
platforms, such as Kubernetes, automate the
deployment, scaling, and management of
containerized applications. This dynamic orchestration
enables better resource usage, high availability,
and transparent scaling of applications. Jakarta
EE’s modular nature and support for microservices
architecture make it well-suited for orchestrated
environments.
•
Microservices-Oriented: Applications are structured
as collections of loosely coupled, independently
deployable services. This architectural style enhances
flexibility, scalability, and the ability to evolve different
parts of an application independently. Jakarta EE,
particularly with its Web and Core profiles, provides
an excellent foundation for building microservices,
offering lightweight runtimes for service development
and communication.
These core principles of cloud-native development, as defined by
the CNCF, provide a high-level framework for building modern, scalable
applications. To implement these principles effectively, many developers
turn to the Twelve-Factor App methodology, which offers a more detailed
set of best practices for creating cloud-native applications. Let’s explore
how this methodology complements the CNCF’s definition and further
guides the development of cloud-native applications, including those built
with Jakarta EE and MicroProfile.
28
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
The Twelve-Factor App Methodology
The Twelve-Factor App, a methodology for building cloud-based
applications, has become a cornerstone of cloud-native development. It
outlines best practices for creating applications that are
•
Portable between execution environments
•
Suitable for deployment on modern cloud platforms
•
Minimizing divergence between development and
production
•
Scaling up without significant changes to tooling,
architecture, or development practices
These twelve factors provide a roadmap for developing cloud-native
applications, and both Jakarta EE and MicroProfile have evolved to support
these principles well. Let’s examine each factor and how Jakarta EE and
MicroProfile address them:
1. Codebase: One codebase tracked in revision control,
many deploys. Jakarta EE applications can be easily
version-controlled, with different deployments for
various environments.
2. Dependencies: Explicitly declare and isolate
dependencies. Jakarta EE’s modularity allows
individual artifacts (specification and profiles) to
be published and consumed through standard
dependency management tools like Maven
and Gradle.
3. Config: Store config in the environment. The
MicroProfile Config API allows externalization of
configuration and integrates seamlessly with the rest
of MicroProfile and Jakarta EE, adhering to this factor.
29
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
4. Backing Services: Treat backing services as attached
resources. Jakarta EE’s JNDI (Java Naming and
Directory Interface) and MicroProfile’s REST Client
facilitate this approach.
5. Build, Release, Run: Strictly separate build and run
stages. Jakarta EE applications can be built into WAR
or JAR files, separate from the runtime environment.
6. Processes: Execute the app as one or more stateless
processes. Jakarta EE’s RESTful web services support
this principle.
7. Port Binding: Export services via port binding.
Jakarta EE runtimes can be easily configured to bind
to specific ports.
8. Concurrency: Scale out via the process
model. Jakarta EE’s Concurrency Utilities and
MicroProfile’s Fault Tolerance API support scalable
concurrency models.
9. Disposability: Maximize responsiveness with
fast startup and graceful shutdown. Jakarta EE’s
lightweight runtimes, especially with the Core
Profile, enable quick startup and shutdown.
10. Dev/Prod Parity: Keep development, staging, and
production as similar as possible. MicroProfile
Config and Jakarta EE’s consistent APIs across
environments support this principle.
11. Logs: Treat logs as event streams. While traditionally
challenging for Java EE, MicroProfile Telemetry
and modern logging frameworks (such as Simple
Logging Facade for Java (SLF4J)) address this need.
30
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
12. Admin Processes: Run admin/management
tasks as one-off processes. Jakarta EE’s CDI and
MicroProfile’s Health Check API can be used to
implement admin processes.
A Note on Logging Frameworks
While Jakarta EE doesn’t mandate a specific logging framework,
several robust options align well with the twelve-factor methodology’s
logging requirements. SLF4J (Simple Logging Facade for Java) serves
as a popular abstraction layer, allowing applications to switch between
implementations like Logback or Log4j2 without code changes. These
modern frameworks support cloud-native features such as structured
JSON logging, asynchronous processing, and integration with container
platforms through stdout/stderr output rather than file-based logging.
For cloud environments, it’s recommended to implement logging
using SLF4J as the facade, configure structured logging (preferably in
JSON format), manage log levels through MicroProfile Config, and include
correlation IDs for distributed tracing. This approach ensures your
Jakarta EE applications maintain observability while running in cloud
environments, supporting both development debugging and production
monitoring needs through integration with modern log aggregation and
analysis tools.
Jakarta EE and MicroProfile together provide a comprehensive set
of APIs and specifications that align closely with the Twelve-Factor
App methodology. This alignment ensures that applications built using
these technologies are well-positioned to take advantage of cloud-native
principles, offering portability, scalability, and consistency across different
cloud environments.
31
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Using Jakarta EE and MicroProfile, you can create applications
that not only adhere to these best practices but also benefit from the
standardization and vendor neutrality that these platforms provide. Let’s
explore in more detail how specific features of Jakarta EE and MicroProfile
support cloud-native development practices.
Jakarta EE Features Supporting
Cloud-Native Development
Jakarta EE has evolved significantly to meet the demands of cloud-native
application development. Its modern incarnation provides a reliable set
of features that align well with cloud-native principles, making it a great
choice for enterprises looking to build scalable, resilient, and portable
applications.
Modularity and Microservices Support
Jakarta EE’s modular architecture forms a solid foundation for
microservices development. This modularity allows you to choose only the
components your applications need either individually or through profiles,
resulting in leaner applications that align with microservices principles.
The Jakarta EE Core Profile, introduced in Jakarta EE 10, is an example
of this modularity. It provides a minimal set of APIs optimized for
microservices development, including
32
•
Jakarta Annotations
•
Jakarta Contexts and Dependency Injection (CDI) (CDI
Lite section)
•
Jakarta Dependency Injection
•
Jakarta Interceptors
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
•
Jakarta JSON Processing
•
Jakarta JSON Binding
•
Jakarta RESTful Web Services
This core set of APIs enables the building of lightweight, focused
microservices without the overhead of unnecessary components.
Lightweight Nature
and Containerization Benefits
Jakarta EE’s journey toward a more lightweight framework significantly
benefits containerization efforts. The platform’s reduced footprint and
faster startup times make it well-suited for container-based deployments.
Key improvements include
1. Optimized Class Loading: Faster application
startup times, important for dynamic scaling in
containerized environments
2. Reduced Memory Footprint: Lower resource
requirements, allowing for higher container density
on host systems
3. Configuration Simplification: Easier to create
immutable container images with externalized
configuration
These enhancements make Jakarta EE applications more efficient in
containerized environments, aligning with cloud-native principles of rapid
scaling and resource efficiency.
33
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Specific APIs for Cloud-Native Development
Jakarta EE provides several APIs that are particularly useful for cloud­
native development.
Jakarta RESTful Web Services (JAX-RS)
Jakarta REST, or JAX-RS as it was known in the past, simplifies the creation
of RESTful web services, a fundamental component of microservices
architectures. It provides annotations and interfaces for building
HTTP-based services, enabling easy implementation of APIs that can
communicate across distributed systems. We cover Jakarta REST in detail
in Chapter 6. Listing 2-1 shows an example of a typical Jakarta REST
resource.
Listing 2-1. Jakarta REST resource
@Path("/users")
public class UserResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllUsers() {
// Implementation
}
}
Jakarta JSON Binding (JSON-B)
JSON-B offers a standard way to convert Java objects to and from JSON,
the de facto data exchange format in cloud-native applications. This
API simplifies data serialization and deserialization for microservices
communication. We will be touching on this API through the rest of this
book as it cuts across most of the core APIs. Listing 2-2 shows an example
of converting a Java object to and from JSON using the JSON-B API.
34
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Listing 2-2. JSON-B example
User user = new User("John Doe", "john@example.com");
String json = JsonbBuilder.create().toJson(user);
User deserializedUser = JsonbBuilder.create().fromJson(json,
User.class);
Jakarta Contexts and Dependency Injection (CDI)
Jakarta CDI provides a powerful dependency injection framework,
essential for building loosely coupled, easily testable microservices.
It promotes modularity and helps manage the lifecycle of stateful
components. Chapter 4 dives into the details of the Jakarta CDI API.
Listing 2-3 shows a quick example of the API.
Listing 2-3. Jakarta CDI scoped bean
@ApplicationScoped
public class UserService {
@Inject
private UserRepository repository;
public User findUser(Long id) {
// Implementation using injected repository
}
}
MicroProfile Config
MicroProfile Config provides a standard way to externalize application
configuration. This is especially important for cloud-native applications
that need to be configurable across different environments without code
changes, a core tenant of the Twelve-Factor App methodology. Chapter 7
explores MicroProfile Config. Listing 2-4 shows a snippet of how the API
is used.
35
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Listing 2-4. MicroProfile Config example
@Inject
@ConfigProperty(name = "app.feature.enabled", defaultValue =
"false")
private boolean featureEnabled;
Jakarta Persistence (JPA) and Jakarta Data
Jakarta Persistence, formerly JPA, along with the newcomer Jakarta Data
simplify database operations in cloud-native applications, providing an
abstraction layer that allows for easy switching between different database
providers, supporting the cloud-native principle of portability. Chapter 5
explores both Jakarta Persistence and Jakarta Data in detail. Listing 2-5
shows a quick example of Jakarta Persistence.
Listing 2-5. Jakarta Persistence example
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
// getters and setters
}
These APIs, among others in the Jakarta EE ecosystem, provide you
with the tools needed to build scalable and maintainable cloud-native
applications. They embody the principles of modularity, lightweight
design, and standardization that are especially important in modern,
distributed computing environments. Let’s explore how you can use
Jakarta EE to create efficient, scalable, and maintainable microservices
architectures.
36
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Microservices with Jakarta EE
Jakarta EE’s modular nature and cloud-native features make it well-suited
for developing microservices. This architectural style, which structures an
application as a collection of loosely coupled services, aligns well with the
strengths of the platform.
Designing Microservices with Jakarta EE
When designing microservices using Jakarta EE, you can take advantage of
several key principles:
1. Single Responsibility: Each microservice should
focus on a specific business capability. Jakarta EE’s
modularity supports this by allowing you to include
only the necessary APIs for each service.
2. Independence: Microservices should be
independently deployable. Jakarta EE’s support
for containerization facilitates this, allowing each
service to be packaged and deployed separately.
3. Data Autonomy: Each microservice should manage
its own data. Jakarta Persistence (JPA) and Jakarta
Data both provide standardized ways to handle data
access, making it easier to implement this principle.
4. API-First Design: RESTful APIs are core to
microservices communication. Jakarta RESTful
Web Services (JAX-RS) and MicroProfile Rest Client
offer a powerful toolkit for creating and consuming
these APIs.
37
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Implementing Microservices
Listing 2-6 shows a simplified example of how a service might be
implemented using Jakarta EE.
Listing 2-6. A simplified service example
@Path("/orders")
@ApplicationScoped
public class OrderService {
@Inject
private OrderRepository repository;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createOrder(Order order) {
Order savedOrder = repository.save(order);
return Response.status(Response.Status.CREATED)
.entity(savedOrder)
.build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getOrder(@PathParam("id") Long id) {
return repository.findById(id)
.map(order -> Response.ok(order).build())
.orElse(Response.status(Response.Status.NOT
FOUND).build());
}
}
38
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
This example shows a simple order service using Jakarta REST for API
or boundary definition, Jakarta CDI for dependency injection, and Jakarta
Persistence (implicitly through the repository) for data persistence.
Inter-service Communication
Microservices often need to communicate with each other. Jakarta EE
provides several options for this including
1. REST: Using Jakarta REST Client or the type-safe
MicroProfile REST Client API to make HTTP calls
between services
2. Messaging: Jakarta Messaging (JMS) for
asynchronous communication
3. Events: Jakarta Enterprise Beans for local,
synchronous events or MicroProfile Reactive
Messaging for distributed event-driven architectures
Challenges andSolutions
While Jakarta EE facilitates microservices development, it’s important to
address common challenges:
1. Service Discovery: While not part of Jakarta EE core,
a number of matured third-party libraries can be
used to implement dynamic service registration and
discovery of services.
2. Configuration Management: MicroProfile Config
allows externalization of configuration, important
for managing multiple microservices across
different environments.
39
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
3. Resilience: MicroProfile Fault Tolerance provides
annotations for implementing circuit breakers,
retries, and timeouts, enhancing the resilience of
microservices.
4. Monitoring: While Jakarta EE doesn’t provide
specific monitoring tools, it’s compatible with
various monitoring solutions. MicroProfile
Telemetry and Health offer standardized ways
to expose application metrics, traces, and
health checks.
The microservices architecture enabled by Jakarta EE sets the
groundwork for efficient containerization, a key aspect of cloud-native
development. Let’s explore how Jakarta EE applications can be effectively
containerized and deployed in cloud environments.
Containerization and Jakarta EE
Containerization has changed application deployment, offering
consistency across different environments and facilitating easier scaling
and management. Jakarta EE’s evolution has made it increasingly
container-friendly, aligning with modern, cloud-native deployment
practices.
Open Container Initiative (OCI)
The Open Container Initiative (OCI) has emerged to create open
industry standards around container formats and runtimes, allowing
interoperability between container tooling and runtimes.
40
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
While Docker has been the traditional choice for containerization,
Podman, a RedHat open source project, offers a daemon-less, rootoptional alternative that’s compatible with Docker containers. Both
runtimes support Jakarta EE applications equally well, with Podman
providing additional security benefits through its rootless operations.
Creating a Dockerfile for a Jakarta
EE Application
Creating a dockerized Jakarta EE application entails bundling your chosen
runtime or implementation as a docker image. Listing 2-7 shows a quick
example of how to create a Dockerfile for an application that uses Payara
Micro as its runtime.
Listing 2-7. Dockerfile of a Jakarta EE app
# Use an official Jakarta EE runtime as the base image
FROM payara/micro:latest
# Set the working directory in the container
WORKDIR /opt/payara/deployments
# Copy the WAR file into the container
COPY target/myapp.war .
# Expose the port the app runs on
EXPOSE 8080
# Define the command to run the application
CMD ["--deploy", "myapp.war", "--contextroot", "/"]
41
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
This container image definition uses Payara Micro as the runtime,
but you could use any Jakarta EE-compatible runtime like Open Liberty
(which we will be using for much of this course), WildFly, TomEE,
or GlassFish. The same container definition works with both Docker
and Podman commands—just replace docker with podman in your
commands.
Best Practices for Containerizing Jakarta
EE Applications
Every organization will have its own conventions for using containers in
their stack. However, there are some cross-cutting, high-level, universal
good practices that you should keep in mind:
1. Use Thin WARs: Package only your application code
and dependencies, relying on the runtime image for
server components.
2. Use Multi-stage Builds: Use a build stage to compile
and package your application and a runtime stage
for the final image.
3. Optimize for Layer Caching: Structure your
container definition to maximize layer caching,
placing less frequently changing items earlier in
the file.
4. Implement Health Checks: Use MicroProfile Health
to implement container health checks.
5. Consider JLink for Smaller Images: For Jakarta
EE Core Profile applications, consider using jlink
to create a custom JRE with only the necessary
modules.
42
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
6. Use Rootless Containers: When using Podman,
take advantage of its rootless container support for
enhanced security in production environments.
7. Use Container Groups: With Podman, use pod
groups to manage multiple containers as a single
unit, similar to Docker Compose but with additional
security benefits.
While these best practices set a good foundation for containerizing
Jakarta EE applications, it’s important to be aware of potential challenges
that may arise in containerized runtime environments. The choice
between Docker and Podman should be based on your specific security
requirements, existing infrastructure, and organizational policies. Both
runtimes will effectively run your Jakarta EE applications with minimal
differences in day-to-day operations.
Challenges and Considerations for Containerized
Jakarta EE Applications
1. Startup Time: While Jakarta EE has improved in this
area, some runtimes may still have longer startup
times. Consider using the Jakarta EE Core Profile or
optimized runtimes for faster startup.
2. Resource Usage: Monitor and optimize resource
usage, especially memory, to ensure efficient use of
container resources.
3. Session Handling: In a containerized environment,
prefer stateless designs or use distributed session
management.
43
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
4. Logging: Use centralized logging solutions to
aggregate logs from multiple containers; logs part of
MicroProfile Telemetry help facilitate this using the
OpenTelemetry (OTel) framework.
The challenges and considerations we’ve discussed for containerized
Jakarta EE applications set the stage for understanding how these
applications perform in various cloud environments. Jakarta EE’s promise
of “write once, run anywhere” extends to the cloud, offering flexibility and
portability across different providers and deployment models.
Jakarta EE in Different Cloud Environments
Jakarta EE’s standardized APIs and container-friendly nature make it wellsuited for deployment across various cloud environments. Whether you’re
using public, private, or hybrid cloud solutions, Jakarta EE applications can
be adapted to run efficiently in these diverse settings.
Public Cloud Deployments
Major public cloud providers support Jakarta EE applications:
•
AWS: Elastic Beanstalk, ECS, and EKS for deployment;
RDS for persistence
•
Azure: App Service for hosting; AKS for containerized
deployments; Azure SQL Database for persistence
•
GCP: App Engine; GKE for container orchestration;
Cloud SQL for data storage
Jakarta EE’s standardized APIs ensure consistent behavior across these
platforms, allowing you to take advantage of cloud-specific services while
maintaining portability.
44
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Private Cloud and Hybrid Scenarios
Jakarta EE applications can also be run in private and hybrid cloud setups:
•
Jakarta EE runtimes offer flexible deployment options,
including direct installation on VMs or containerization
for platforms like OpenStack, VMware vSphere, and
Red Hat OpenShift, suitable for both private and hybrid
cloud environments. Their reliance on standardized
APIs helps prevent vendor lock-in, enabling geographic
distribution of services and cost-effective management
across multiple cloud providers.
Key Considerations for Cloud Deployments
Deploying in diverse cloud environments presents a unique set of
challenges. You should consider several factors to ensure optimal
performance, security, and scalability of your Jakarta EE applications in
the cloud. Here are some key considerations:
1. Configuration Management: Use MicroProfile
Config for environment-specific settings.
2. Monitoring: Combine MicroProfile Telemetry with
cloud-native monitoring solutions offered by cloud
vendors.
3. Security: Integrate Jakarta Security and MicroProfile
JWT with cloud-provided security services.
4. Scalability: Design for horizontal scaling to take
advantage of cloud elasticity.
45
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Jakarta EE’s standards-based approach allows you to create cloud­
native and cloud-agnostic applications, providing flexibility across a wide
range of deployment scenarios. This flexibility in cloud environments
sets the stage for comparing Jakarta EE with other frameworks targeting
similar use cases, highlighting its unique position in the cloud-native Java
ecosystem.
Comparison with Other Cloud-Native
Java Frameworks
While Jakarta EE has evolved significantly from its J2EE days to meet
cloud-native development needs, it’s not the only option in this space.
Several other Java frameworks have emerged, each with its own approach
to cloud-native development. A basic overview of these alternatives will
help contextualize Jakarta EE’s position in the ecosystem. Table 2-1 shows
the similarities and differences between Jakarta EE and other notable Java
cloud-native frameworks.
46
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Table 2-1. Comparison ofJakarta EE and Other Java Frameworks
Framework Similarities
Differences
Spring Boot - Comprehensive solutions
- Spring Boot uses “Opinionated
for building enterprise Java
Defaults Configuration” often
applications
requiring less boilerplate code,
- Support for microservices
architecture
- Strong dependency injection
capabilities
whereas Jakarta EE is more
standards-based.
- Jakarta EE has a longer track
record in enterprise contexts and
wider vendor support.
- Spring Boot is flexible and
opinionated, allowing more
freedom in how to use its
features.
Quarkus
- Support for cloud-native and
- Quarkus is GraalVM native
microservices development
image-friendly offering
- Extensive API development
capabilities
exceptionally fast startup times.
- Jakarta EE supports a much
- Supports the same Jakarta
older and matured ecosystem.
EE and MicroProfile APIs
- Quarkus has a steeper learning
curve for developers who are
new to reactive programming.
(continued)
47
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Table 2-1. (continued)
Framework Similarities
Micronaut
Differences
- Supports microservices and
- Micronaut is GraalVM native
cloud-native development
image-friendly offering
- Offers dependency injection
and Aspect-Oriented
Programming (AOP) support
exceptionally fast startup times.
- Jakarta EE offers more
comprehensive support for
legacy Java EE features.
- Micronaut includes builtin support for serverless
deployments, making it easier
to integrate with serverless
platforms.
Helidon
- Offers MicroProfile support
- Suitable for microservices
development
- Helidon SE is more lightweight
and focuses on reactive
programming.
- Jakarta EE provides a fuller set
of enterprise APIs.
- Helidon has closer integration
with Oracle Cloud services, while
Jakarta EE remains vendor­
neutral and can be used across
different cloud providers.
48
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Key Takeaways
After comparing Jakarta EE with other cloud-native Java frameworks, we
can deduce several important points that highlight Jakarta EE’s position in
the ecosystem:
1. Standards vs. Innovation: Jakarta EE emphasizes
standardization and stability, while some
alternatives prioritize cutting-edge features.
2. Learning Curve: Jakarta EE uses existing Java EE
knowledge, potentially easier for teams with that
background.
3. Performance: Newer frameworks like Quarkus and
Micronaut may offer performance advantages in
specific scenarios.
4. Ecosystem: Jakarta EE has a vast, mature ecosystem
and wide vendor support.
5. Flexibility: Jakarta EE’s modular nature allows it to
be as lightweight or comprehensive as needed.
Jakarta EE is well-established in the cloud-native Java ecosystem,
valuing standards, a broad ecosystem, multi-vendor support, and
flexibility. As the tech landscape changes, Jakarta EE is actively evolving
to meet future cloud-native demands. Let’s explore the possible future
direction of Jakarta EE in an increasingly cloud-first development
landscape.
49
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Future Direction of Jakarta EE
in the Cloud-Native Landscape
As the cloud-native landscape continues to evolve, Jakarta EE will
continue positioning itself to remain a relevant platform for enterprise Java
development. Its future direction is shaped by community feedback from
individuals like you and organizations like yours, industry trends, and the
changing needs of cloud-native applications.
Continued Focus on Cloud-Native Features
Jakarta EE is expected to further enhance its cloud-native capabilities in
upcoming releases:
•
Expanded Microservices Support: Future versions
will likely include more features specifically designed
for microservices architectures, such as improved
configuration management.
•
Virtual Thread Support: Expect to see support for Java
21 Virtual Threads in Jakarta Concurrency.
Integration with Emerging Technologies
Jakarta EE is likely to integrate more closely with emerging technologies
that complement cloud-native development:
•
50
AI and Machine Learning: Future releases may include
APIs or integration points for AI and ML services,
allowing easier incorporation of these technologies into
Jakarta EE applications.
CHAPTER 2
•
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Edge Computing: As edge computing grows, Jakarta
EE may introduce features to support distributed
application architectures that span cloud and edge
environments.
Improved Developer Experience
The platform is expected to focus on enhancing the developer experience:
•
Faster Startup Times: Ongoing work to reduce
application startup times will continue, making Jakarta
EE more competitive in serverless and container
environments.
Stronger Alignment with Cloud-Native Standards
Jakarta EE will likely align more closely with cloud-native standards and
best practices:
•
Kubernetes Integration: Deeper integration with
Kubernetes, possibly including native Kubernetes APIs
or operators for Jakarta EE applications
•
Service Mesh Compatibility: Improved compatibility
and integration with popular service mesh
technologies
51
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Continued Commitment to Stability
and Backward Compatibility
While adopting cloud-native innovations, Jakarta EE will maintain its
commitment to stability:
•
Long-Term Support: Expect continued long-term
support for major versions, providing stability for
enterprise applications.
•
Smooth Migration Paths: Future releases will likely
offer clear migration paths from older versions,
allowing gradual adoption of new features.
Community-Driven Innovation
The open source nature of Jakarta EE means its future will be significantly
influenced by community contributions from members like you:
•
New Specifications: Expect new specifications to
emerge, driven by community needs and contributions.
•
Faster Release Cycles: The community may push
for more frequent releases to keep pace with rapidly
evolving cloud technologies.
Integration withGraalVM
Given the growing importance of native compilation for cloud-native
applications:
•
52
Native Compilation Support: Future versions may
offer improved support for GraalVM native image
compilation, enabling Jakarta EE applications to
compile to native executables for faster startup and
lower resource usage.
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
The future of Jakarta EE in the cloud-native landscape looks
promising, with a clear trajectory toward more cloud-native features,
improved developer experience, and deeper integration with modern
cloud technologies. As it evolves, Jakarta EE is poised to remain a robust
and relevant platform for building enterprise-grade, cloud-native Java
applications.
Shaping the Future: Your Role in Jakarta
EE's Evolution
As an open platform, Jakarta EE depends on community involvement and
contributions. Your expertise and insights can play a role in shaping the
future of enterprise Java in the cloud-native era.
The Jakarta EE Future Directions Initiative
The Eclipse Foundation recently announced a new initiative to drive
Jakarta EE’s future development. This initiative aims to
•
Brainstorm and research future directions for
enterprise and cloud-native Java.
•
Provide specific, prioritized recommendations to the
Jakarta EE and MicroProfile working groups.
•
Address emerging technologies, new industry use
cases, integrations, and messaging/marketing
strategies.
This interest group welcomes participants from diverse backgrounds,
including those outside traditional Java working groups, to contribute fresh
perspectives and ideas.
53
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
How You Can Contribute
1. Join the Discussion: Participate in Jakarta EE
community forums and mailing lists to share your
ideas and feedback.
2. Contribute Code: Submit pull requests to Jakarta EE
projects on GitHub to improve existing features or
implement new ones.
3. Participate in Working Groups: Join Jakarta EE
working groups to directly influence the platform’s
evolution.
4. Share Use Cases: Provide real-world examples
of how you’re using Jakarta EE in cloud-native
environments to help guide future developments.
5. Spread the Word: Help grow the Jakarta EE
community by sharing your experiences and
knowledge through blogs, talks, or social media.
Contributing to Jakarta EE means you’re not just improving a
technology platform; you’re helping shape the future of enterprise Java.
Your involvement ensures that Jakarta EE continues to meet your evolving
needs in the cloud-native landscape. To learn more about how you can
get involved and make a difference in the future of cloud-native Java
development, visit the Jakarta EE website or the Eclipse Foundation’s
Jakarta EE project page.
54
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
Summary
This chapter explored Jakarta EE’s evolution and its role in cloud-native
Java application development. We traced Jakarta EE’s journey from its
J2EE roots to its current position as a platform well-suited for building
microservices and deploying them in cloud environments.
Key Takeaways
1. Jakarta EE provides a standardized, vendor-neutral
platform for building cloud-native Java applications.
2. The platform’s modular nature allows developers
to choose components based on their specific
needs, from lightweight microservices to full-scale
enterprise applications.
3. Jakarta EE’s evolution aligns with cloud-native
principles, making it a viable choice for modern
application development while maintaining
backward compatibility.
4. Developers can use Jakarta EE’s extensive ecosystem
and wide vendor support while benefiting from its
adaptability to various cloud environments.
5. The open source nature of Jakarta EE allows for
community-driven innovation, with opportunities
for everyone to contribute to its future direction.
55
CHAPTER 2
JAKARTA EE, MICROSERVICES, AND THE CLOUD
This chapter highlighted Jakarta EE’s significant role in the cloud­
native Java ecosystem, demonstrating its adaptability to modern
development needs while maintaining its core strengths of standardization
and stability. As we move forward, it’s important to understand how to
effectively take advantage of these capabilities in real-world scenarios. The
next chapter will explore best practices and design patterns for crafting
scalable, maintainable, and high-performance enterprise applications
using Jakarta EE.
56
CHAPTER 3
Architecting
Enterprise
Applications with
Jakarta EE
Modern enterprise applications have evolved over the years to become more
than just functional software systems. They are now complex, distributed
interconnected ecosystems that need to be resilient, scalable, and adaptable
to changing business needs and consumer expectations. Jakarta EE, as we
saw in the previous chapters, is the open source evolution of Java EE (and
J2EE before that) that provides a rich set of specifications and APIs that not
only simplify the creation of enterprise-grade applications but also promote
architectural best practices. Two key architectural concepts that have
proven invaluable in the development of such complex modern systems are
Domain-Driven Design (DDD) and layered architecture.
Domain-Driven Design, a methodology introduced by Eric Evans,
emphasizes aligning software design with business realities. It encourages
modeling of software based on the core business domain, creating a
ubiquitous language between technical and non-technical stakeholders.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_3
57
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
This approach is well-suited to Jakarta EE’s strengths, particularly in
applications that need to implement and manage complex business logic.
Jakarta EE’s middleware capabilities provide an ideal foundation for
implementing DDD concepts, allowing you to focus on modeling intricate
business domains while leveraging the platform’s enterprise-grade features.
Layered architecture, on the other hand, provides a structured
approach to organizing application components. By separating concerns
into distinct layers—typically presentation, business logic, and data
access—it promotes modularity, maintainability, and scalability.
Jakarta EE’s various specifications, such as Jakarta Server Faces (JSF) for
presentation, Jakarta CDI for business logic, and Jakarta Persistence (JPA)
for data access, naturally lend themselves to this architectural style.
The goal of this chapter is to explore how Domain-Driven Design and
layered architecture can be effectively applied within the context of Jakarta
EE applications. We’ll dive into architectural decision-making processes,
examining how these concepts influence the design and implementation
of scalable enterprise systems. Through the case study application, JWallet,
we’ll demonstrate practical applications of these principles, showcasing how
Jakarta EE’s features support and enhance these architectural approaches.
By the end of the chapter, you will
58
•
Understand the core principles of Domain-Driven
Design (DDD) and how they apply to Jakarta EE
applications.
•
Grasp the concept of layered architecture and its
benefits in enterprise application development.
•
Learn how to make informed architectural decisions
based on project requirements and constraints.
•
Be able to apply DDD and layered architecture
principles to design scalable, maintainable, and highperformance Jakarta EE applications.
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Domain-Driven Design in Jakarta EE
Domain-Driven Design (DDD1), a methodology introduced by Eric Evans
in his seminal book Domain-Driven Design: Tackling Complexity in the
Heart of Software, emphasizes aligning software design with business
realities. It aims to base complex designs on a model of the domain,
fostering a common understanding between technical and domain experts
within the organization.
Jakarta EE, through its loosely coupled yet cohesive set of
specifications, is well-suited to the use of domain-driven architecture.
The core specifications like Jakarta Persistence and Jakarta REST focus
on core domains of data and bounded contexts. The direct linkage of the
specification to the different aspects of the application domain makes
it straightforward to implement DDD with Jakarta EE. Domain-Driven
Development, at its core, is guided by a number of principles and patterns.
Core Principles of Domain-Driven Design
At the heart of Domain-Driven Design (DDD), we find a collection of
interconnected principles and patterns that guide the creation of software
that closely mirrors the complexities of the real-world domain it serves.
These principles and patterns are as follows.
Ubiquitous Language
A ubiquitous language is the common theme that binds together all
stakeholders—developers, domain experts, and business analysts. It’s
a shared vocabulary made up of domain-specific terms and concepts
that encompasses every facet of the project. This ensures clear and
unambiguous communication and fosters a shared understanding of the
1 https://martinfowler.com/bliki/DomainDrivenDesign.html
59
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
domain. For instance, in the context of a digital wallet application like
JWallet, terms like “wallet,” “transaction,” and “exchange rate” form the
core vocabulary of the ubiquitous language.
Bounded Contexts
Bounded contexts define distinct boundaries within a domain, each
with its own model. In JWallet, bounded contexts include account
management, wallet operations, and currency exchange. This modular
approach enhances maintainability and prevents model complexity.
Bounded contexts are a core DDD pattern for managing large models
by dividing them into conceptual domains. Each context has its own
ubiquitous language and model, enabling teams to focus on specific areas
without conflicts or inconsistencies.
Entities
Entities are the “main actors” of the domain model, representing objects
that possess a unique and enduring identity that go beyond different
states or representations. In JWallet, a Wallet is an entity. An entity is
transcendental in DDD because its identity does not change with changes
in its attributes. For example, an instance of a Wallet entity will maintain
its identity throughout the life of the application even as its balance, an
attribute, changes with transactions.
Value Objects
In contrast to entities, value objects embody characteristics or attributes
but lack a conceptual identity. They are defined by their values and
are considered interchangeable if their attributes match. In the
JWallet application, Money could be conceptualized as a value object
encapsulating an amount and a currency.
60
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Aggregates
Aggregates function as clusters or groupings of domain objects that are
treated as a cohesive unit. They maintain consistency and ensure that
changes within the aggregate adhere to the established business rules.
In JWallet, a Wallet coupled with its associated Transactions could be
modeled as an aggregate.
Repositories
Repositories serve as gateways to access aggregates. They abstract the
underlying persistence mechanism and provide a means to retrieve and
store aggregates. In JWallet, we have repositories for managing Wallets and
Transactions.
Domain Events
Domain events chronicle significant occurrences within the domain. They
capture changes of state and facilitate communication between different
parts of the system. In the JWallet scenario, a TransactionCompleted event
could be dispatched to signal the successful execution of a transaction.
Domain-Driven Design allows us to develop software that is not only
maintainable but also closely aligned with constantly changing business
needs and user expectations. Now let us see code snippets from the JWallet
sample application for this book mapped to the above principles, starting
with entities.
Mapping DDD Concepts to Jakarta
EE Components
Jakarta EE provides a rich set of APIs that align well with DDD concepts.
61
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Entities
Entities in DDD can be directly mapped to JPA entities. For instance,
Listing 3-1 shows the Wallet entity modeled with Jakarta Persistence.
Listing 3-1. Wallet entity class
@Entity
public class Wallet extends BaseEntity {
private String authUserId;
private String currency;
private BigDecimal balance;
@OneToMany(mappedBy = "wallet")
private Set<Transaction> transactions;
public synchronized void credit(final BigDecimal amount) {
setBalance(getBalance().add(amount));
}
public synchronized void debit(final BigDecimal amount) {
BigDecimal newBalance = getBalance().subtract(amount);
if (newBalance.signum() == -1) {
throw new WalletOverdrawnException();
} else {
setBalance(newBalance);
}
}
public BalanceResponse.BalanceResponseData
toBalanceResponseData() {
BalanceResponse.BalanceResponseData data = new
BalanceResponse.BalanceResponseData();
data.setWalletId(this.getId());
62
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
data.setBalance(this.getBalance());
data.setCurrency(this.getCurrency());
return data;
}
}
The Wallet entity is a Jakarta Persistence entity that is marked as such
with the @Entity annotation. It extends a BaseEntity class and does have
some methods to carry out some functions. Chapter 5 explores Jakarta
Persistence in detail. For now, the entity is an example of the modeling of
the “main actors” of the domain as entities. An instance of this class, once
created, will hold its identity throughout its life, despite changes in some of
its attributes like balance and the number of transactions.
Repositories
The new Jakarta Data specification in Jakarta EE 11 introduces native
support for the repository pattern. As repositories are a facade to the data
in DDD, they normally encapsulate common actions like create, read,
update, and delete (CRUD) that are carried out on the data. Listing 3-2
shows the repository facade using the new Jakarta Data specification.
Listing 3-2. WalletRepository
@Repository(dataStore = "jdbc/jwallet-postgres")
public interface WalletRepository extends
CrudRepository<Wallet, Long> {
}
The WalletRepository interface extends the jakarta.data.repository.
CrudRepository interface. This interface is a CDI bean containing methods
that map to the create, read, update, and delete (CRUD) operations most
common to all data. The shown repository is all there is to it. The Jakarta
63
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Data implementation, at runtime, will provide a concrete implementation
of the interface for dependent components that rely on this interface.
Chapter 5 covers Jakarta Data in detail. Any application component that
needs the WalletRepository to carry out operations can use Jakarta CDI
@Inject to inject a contextual instance. Chapter 4 explores Jakarta CDI
in detail.
Domain Services
Domain services are tied to bounded contexts, where logical segments
of the application are grouped together and have common operations
carried out on them. For example, in JWallet, a WalletService is a domain
service that encapsulates the logic of operations that can be carried out on
instances of the Wallet entity. Listing 3-3 shows the WalletService interface,
with Listing 3-4 showing its implementation by SimpleWalletService.
Listing 3-3. WalletService interface
@ApplicationScoped
public interface WalletService {
BalanceResponse getBalance(final long walletId);
BalanceResponse createWallet(final CreateWalletRequest
request);
TransactionsResponse getTransactions(final long walletId);
TransactionResponse debit(final TransactionRequest
transactionsRequest);
TransactionResponse credit(final TransactionRequest
transactionsRequest);
}
64
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Listing 3-4. WalletService implementation by SimpleWalletService
@ApplicationScoped
public class SimpleWalletService implements WalletService {
WalletRepository walletRepository;
TransactionRepository transactionRepository;
RateService rateService;
@Inject
public SimpleWalletService(WalletRepository wallet,
TransactionRepository txn, RateService rate) {
this.walletRepository = wallet;
this.transactionRepository = txn;
this.rateService = rate;
}
@Override
public BalanceResponse getBalance(final long walletId) {
Wallet wallet = walletRepository.findById(walletId).
orElseThrow();
return BalanceResponse.of(wallet.
toBalanceResponseData());
}
@Override
public BalanceResponse createWallet(final
CreateWalletRequest request) {
Wallet wallet = new Wallet();
wallet.setBalance(BigDecimal.ZERO);
wallet.setCurrency(request.getCurrency());
wallet.setAuthUserId(jsonWebToken.getSubject());
wallet = walletRepository.save(wallet);
65
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
return BalanceResponse.of(wallet.
toBalanceResponseData());
}
@Override
public TransactionsResponse getTransactions(final long
walletId) {
Wallet wallet = walletRepository.findById(walletId).
orElseThrow();
Set<TransactionResponseData> transactionResponseDataSet
= wallet.getTransactions().stream()
.map(Transaction::toTransactionResponseData)
.collect(Collectors.toSet());
return TransactionsResponse.of(transactionResponse
DataSet);
}
@Override
public TransactionResponse debit(final TransactionRequest
transactionsRequest) {
Wallet wallet =
walletRepository.findById(transactionsRequest.
getWalletId()).orElseThrow();
BigDecimal calculatedAmount = rateService.convert(
wallet.getCurrency(), transactionsRequest.
getAmount(), transactionsRequest.
getCurrency());
wallet.debit(calculatedAmount);
walletRepository.update(wallet);
Transaction transaction = new Transaction();
66
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
transaction.setType(TransactionType.DEBIT);
transaction.setWallet(wallet);
transaction.setCurrency(transactionsRequest.
getCurrency());
transaction.setAmount(transactionsRequest.getAmount());
transaction = transactionRepository.save(transaction);
return TransactionResponse.of(transaction.
toTransactionResponseData());
}
@Override
public TransactionResponse credit(final TransactionRequest
transactionsRequest) {
Wallet wallet =
walletRepository.findById(transactionsRequest.
getWalletId()).orElseThrow();
BigDecimal calculatedAmount = rateService.convert(
wallet.getCurrency(), transactionsRequest.
getAmount(), transactionsRequest.
getCurrency());
wallet.credit(calculatedAmount);
walletRepository.update(wallet);
Transaction transaction = new Transaction();
transaction.setType(TransactionType.CREDIT);
transaction.setWallet(wallet);
transaction.setCurrency(transactionsRequest.
getCurrency());
transaction.setAmount(transactionsRequest.getAmount());
transaction = transactionRepository.save(transaction);
67
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
return TransactionResponse.of(transaction.
toTransactionResponseData());
}
}
The SimpleWalletService implements the WalletService contract to
define operations that can be carried out on given instances of a Wallet
entity in JWallet. Service components in Jakarta EE applications are
modeled using Jakarta CDI. In the past, Enterprise JavaBeans or EJBs were
used for that. However, the Jakarta EE platform is transitioning the good
parts of EJBs to Jakarta CDI; thus, this book will focus on using Jakarta CDI
to model business services. Chapter 4 covers Jakarta CDI in detail.
Domain Events
Jakarta CDI’s event mechanism allows you to broadcast type-safe
application events that can be routed to any registered listener interested
in that event type. In JWallet, a TransactionCompletedEvent can be used
to broadcast the completion of a transaction to listeners so they can take
custom actions. For instance, a listener could be interested in a wallet
transaction so it can send an email notification to the holder of the wallet.
Another could be interested in the same event to send an SMS notification.
Listing 3-5 shows the TransactionCompletedEvent payload.
Listing 3-5. TransactionCompletedEvent payload class
public record TransactionCompletedEvent(Long txId, String
authUserId) {
}
The payload type determines the type of event that will be fired. A
Transaction event can be fired on a transaction event like a DEBIT on a
wallet. For example, Listing 3-6 shows the SimpleWalletService firing a
TransactionCompletedEvent when a debit transaction occurs.
68
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Listing 3-6. SimpleWalletService event broadcast
@Action
@NoArgsConstructor
public class SimpleWalletService implements WalletService {
@Inject
JsonWebToken jsonWebToken;
@Inject
private Event<TransactionCompletedEvent>
transactionCompletedEvent;
@Override
public TransactionResponse debit(final TransactionRequest
transactionsRequest) {
Wallet wallet =
walletRepository.findById(transactionsRequest.
getWalletId()).orElseThrow();
BigDecimal calculatedAmount = rateService.convert(
wallet.getCurrency(), transactionsRequest.
getAmount(), transactionsRequest.
getCurrency());
wallet.debit(calculatedAmount);
walletRepository.update(wallet);
Transaction transaction = new Transaction();
transaction.setType(TransactionType.DEBIT);
transaction.setWallet(wallet);
transaction.setCurrency(transactionsRequest.
getCurrency());
transaction.setAmount(transactionsRequest.getAmount());
transaction = transactionRepository.save(transaction);
69
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
TransactionCompletedEvent event = new Transaction
CompletedEvent(transaction.getId(), jsonWebToken.
getSubject());
transactionCompletedEvent.fireAsync(event);
return TransactionResponse.of(transaction.
toTransactionResponseData());
}
}
The SimpleWalletService fires an event using the jakarta.
enterprise.event.Event interface. This construct is provided as part
of the Jakarta CDI API. It has methods to fire both sync and async
CDI events. In the SimpleWalletService example above, an async
TransactionCompletedEvent is fired in the debit method. We use async
events in order to not hold the currently executing thread. Again, the next
chapter dives deep into the innards of Jakarta CDI. For now, suffice to say
the Jakarta CDI event mechanism allows us to broadcast domain events in
a type-safe, loosely coupled way.
Table 3-1 shows a summary of how the constructs in JWallet
translate to the principles and patterns of DDD to help reinforce your
understanding of how Jakarta EE constructs aid in DDD.
70
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Table 3-1. Jakarta EE Constructs to DDD Concepts
DDD Concept JWallet Application
Entities
Value objects
Description
Wallet, Account,
Core objects with unique identities and
Transaction
lifecycle.
Money, ExchangeRate
Immutable objects representing a specific
value or measurement.
Aggregates
Repositories
Wallet (root) with its
A cluster of associated objects treated as a
Transactions
single unit for data changes.
WalletRepository,
Manage the persistence and retrieval of
AccountRepository,
aggregates.
TransactionRepository
Domain
TransferService,
Encapsulate complex domain logic that
services
ExchangeRateService
spans multiple entities.
Bounded
Account Management, Separate areas of the application with
contexts
Wallet Operations,
their own models and language, promoting
Currency Exchange
modularity and maintainability.
While DDD focuses on modeling the domain and its interactions,
it doesn’t prescribe a specific technical architecture. This is where
the concept of layered architecture comes in. Layered architecture
complements DDD by providing a structural foundation that organizes
code into distinct, manageable layers. It offers a way to separate concerns
and manage the complexity that often arises in enterprise applications.
Now that we’ve explored how DDD principles can be applied in
Jakarta EE applications, let’s examine how layered architecture provides a
complementary structural approach to organizing code.
71
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Layered Architecture
Layered architecture is a classic pattern in software design that organizes
an application into distinct layers, each with its own responsibilities and
concerns. A typical layered architecture consists of four main layers as
shown in Table 3-2 and visualized in Figure 3-1.
Table 3-2. Layers in a Layered Architecture
Layer
Purpose
Presentation layer
Handles user interactions, HTTP requests/responses
Application/service layer
Orchestrates data flow, application logic
Domain layer
Contains core business logic, domain model
Persistence layer
Handles data storage, retrieval
Figure 3-1. Visual representation of layered architecture
As you can see, the four layers are themselves bounded contexts
from DDD. Even though the service, domain, and persistence layers are
different conceptually, in some applications, you will find the domain and
persistence layers merged into the service layer. Yet in some others, you
will find the domain and persistence layers merged together so the four
layers become three—presentation, service and persistence. Whichever
permutation an application uses, keep in mind that at its core, the layered
72
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
architecture conceptually has these four layers to help you be able to
structure your applications. But you may be wondering, Why should you
care about layered architecture when building with Jakarta EE?
Layered Architecture in Jakarta EE: The Benefits
Implementing a layered architecture in Jakarta EE applications offers
several advantages such as the following.
Separation ofConcerns
•
Assigns Distinct Responsibilities to Each Layer: This
prevents the mixing of concerns within the codebase,
making it easier to understand and manage.
•
Organizes the Codebase for Better Comprehension: By
separating concerns, layered architecture provides a
clear structure that is easier to follow and maintain.
Maintainability
•
Changes in One Layer Minimally Impact Others:
This reduces the risk of unintended side effects when
making modifications to the codebase.
•
Simplifies Maintenance and Update Processes: Layered
architecture allows for more focused maintenance
efforts, as changes can be isolated to specific layers.
73
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Testability
•
Allows for Independent Testing of Layers: Each layer
can be tested in isolation, making it easier to identify
and fix bugs. There will always be bugs.
•
Enhances Unit Testing and Facilitates Test-Driven
Development: Layered architecture provides a solid
foundation for writing effective unit tests and adopting
test-driven development practices.
Flexibility
•
Permits Independent Modification or Replacement
of Layers: This allows for easier adaptation to new
technologies and changing requirements without
affecting the entire application.
•
Supports Easier Integration of New Technologies
and Adaptation to Changing Requirements: Layered
architecture provides a modular structure that makes it
easier to incorporate new technologies or features.
Reusability
•
Enables the Reuse of Lower Layers Across Various
Applications or Modules: Common functionalities can
be encapsulated in lower layers, reducing development
time and effort.
It’s important to note that the benefits of a layered architecture are in
some ways similar to the benefits of microservices. This is because both
paradigms are similar in that both advocate the use of bounded contexts.
74
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Microservices can be said to be a subset of layered architecture. Each
layer identified in Table 3-2 can be separated into a microservice of the
application. Layered architecture is also perfectly suited to monolithic
applications. In such applications, each layer still acts as a self-contained
module, with inter-module dependencies managed through well-defined
value objects and repositories. Now let us see how to implement a layered
architecture in JWallet, the sample application for this book.
Presentation Layer
JWallet uses Jakarta REST, previously known as Java API for RESTful Web
Services (JAX-RS), to implement the presentation layer. This specification
provides a set of Java APIs for creating web services according to the
Representational State Transfer (REST) architectural pattern. Here’s an
example from the WalletResource in Listing 3-7.
Listing 3-7. WalletResource example
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("wallets")
public class WalletResource {
@Inject
WalletService walletService;
@Context
SecurityContext securityContext;
@POST
public BalanceResponse createWallet(CreateWalletRequest
createWalletRequest) {
return walletService.createWallet(createWalletRequest);
}
75
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
@GET
@Path("{walletId}/balance")
public BalanceResponse getBalance(@PathParam("walletId")
long walletId) {
return walletService.getBalance(walletId);
}
@GET
@Path("{walletId}/transactions")
public TransactionsResponse getTransactions(@PathParam
("walletId") long walletId) {
return walletService.getTransactions(walletId);
}
@POST
@Path("{walletId}/transactions/debit")
public TransactionResponse debit(@PathParam("walletId")
long walletId, TransactionRequest transactionsRequest) {
return walletService.debit(transactionsRequest);
}
@POST
@Path("{walletId}/transactions/credit")
public TransactionResponse credit(@PathParam("walletId")
long walletId, TransactionRequest transactionsRequest) {
return walletService.credit(transactionsRequest);
}
}
This resource class handles the HTTP endpoints related to wallet
operations, delegating business logic to the service layer. In this case, the
WalletResource (the presentation layer) delegates all business-related
actions to the WalletService. As the resource class itself is concerned with
76
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
accepting and responding to HTTP requests, it is a good example of the
Single Responsibility Principle. It focuses solely on handling the HTTP
protocol specifics (GET, POST), request parsing (consuming and returning
JSON), and response formatting, while leaving the actual business
operations to the service layer. This clear separation of concerns enhances
maintainability and allows for easier testing and modification of each layer
independently. The WalletResource class can be unit-tested independently
of the other parts of the application.
Application/Service Layer
The service layer is implemented using Jakarta Contexts and Dependency
Injection (CDI) beans. Jakarta CDI, which evolved from the Java EE CDI
specification, provides a powerful set of services for managing the lifecycle
and interactions of Java EE components. These components orchestrate
the flow of data and encapsulate application-specific logic. Here’s an
example of the WalletService implementation reproduced in Listing 3-8.
Listing 3-8. WalletService implementation
@ApplicationScoped
public class SimpleWalletService implements WalletService {
@Inject
private WalletRepository walletRepository;
public BalanceResponse createWallet(final
CreateWalletRequest createWalletRequest) {
Wallet wallet = new Wallet();
wallet.setBalance(BigDecimal.ZERO);
wallet.setCurrency(createWalletRequest.getCurrency());
wallet = walletRepository.save(wallet);
77
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
return getBalance(wallet.getId());
}
public void debit(Long walletId, BigDecimal amount) {
Wallet wallet = walletRepository.findById(walletId);
wallet.debit(amount);
walletRepository.save(wallet);
}
}
The WalletService implementation coordinates between the
presentation layer and the domain/persistence layers, handling operations
like wallet creation and debit.
Domain Layer
And at the domain layer, represented by JPA entities, we have likes of
the Wallet entity as shown in Listing 3-1. It not only represents the data
structure of a Wallet but also encapsulates business rules like preventing
overdrafts in the debit method.
Persistence Layer
The persistence layer is implemented using the Jakarta Persistence API
and the new Jakarta Data. The WalletRepository, as shown in Listing 3-2,
uses Jakarta Data to create a repository facade for carrying out wallet
operations.
By structuring JWallet using this layered architecture, a clear separation
of concerns is created. Each component has a well-defined responsibility,
making the application easier to understand, maintain, and extend. The
presentation layer handles HTTP interactions, the service layer orchestrates
operations, the domain layer encapsulates the core business entities, and the
persistence layer manages data storage and retrieval.
78
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
This architecture also facilitates testing. The domain logic can be
unit-tested in isolation, mock the repositories to test the services, and use
integration tests to verify the correct interaction between layers. As we
progress through this chapter, you’ll see how this layered architecture,
combined with the DDD principles we discussed earlier, forms the
backbone of maintainable Jakarta EE applications. However, arriving at
these architectural choices is not a straightforward process. Each decision,
from choosing DDD to implementing a layered architecture, involves
careful consideration of various factors.
How do we decide which architectural patterns to adopt? What factors
influence these decisions? And how do we document and communicate
these choices to ensure alignment across the development team?
Architectural Decision-Making in Jakarta
EE Projects
Architectural decisions in Jakarta EE projects are influenced by a myriad of
factors, each playing a role in shaping the final structure of the application.
Throughout the development process, from choosing DDD as the design
philosophy to implementing a layered architecture, these factors must
be carefully considered. Let’s explore the key considerations that guide
architectural choices.
Performance
Jakarta EE applications must efficiently handle high loads and process
large data volumes. This involves optimizing database queries,
implementing caching strategies, and leveraging Jakarta EE’s built-in
performance features like connection pooling.
79
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Scalability
Enterprise applications need to accommodate growth in users, data, and
transactions. This requires designing for horizontal and vertical scaling,
using stateless components, and implementing effective load balancing
strategies. SOLID2 is an acronym for five design principles intended to
make software designs more understandable, flexible, and maintainable.
These principles are Single Responsibility, Open-Closed, Liskov
Substitution, Interface Segregation, and Dependency Inversion.
Maintainability
With long lifespans, enterprise applications demand easy maintenance.
This involves writing clean, modular code, adhering to SOLID principles,
and implementing comprehensive logging and monitoring.
Security
Protecting sensitive data and ensuring secure operations is critical.
This includes implementing robust authentication and authorization,
encrypting data at rest and in transit, and regularly updating dependencies
to address vulnerabilities.
Interoperability
Jakarta EE applications often integrate with various systems and services.
This necessitates designing flexible APIs, implementing standard
protocols, and ensuring data format compatibility across different systems.
2 https://en.wikipedia.org/wiki/SOLID
80
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Compliance
Many industries have specific regulatory requirements. The architecture
must accommodate these, which may involve implementing audit trails,
ensuring data privacy, and providing mechanisms for data retention and
deletion.
Development Team Expertise
The team’s skills and experience influence architectural choices.
Leveraging the team’s strengths while providing opportunities for growth
can lead to more effective implementation and maintenance.
Time toMarket
Project deadlines and business pressures impact decisions. This may
involve choosing familiar technologies for faster development, using rapid
prototyping techniques, or implementing a minimum viable product
(MVP) approach.
When making architectural decisions, it’s important to consider these
factors in the context of your specific project requirements and constraints.
Let’s look at a real-world scenario to illustrate this process.
Case Study: Microservices vs.
Monolithic Architecture
Consider the JWallet application. In its current form, it’s structured as a set
of microservices developed within a common project. However, this wasn’t
an arbitrary decision. Let’s examine the thought process behind why we
made such an architectural decision for the app.
81
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Factors Considered
1. Scalability: As a financial application, JWallet needs
to handle a potentially large number of users and
transactions.
2. Flexibility: Different components (wallet, account,
rate) might need to scale independently based on
usage patterns.
3. Team Structure: We’re a team of two, living
on separate continents with different but
complementary skill sets.
4. Deployment: We want the ability to deploy and
update services independently.
5. Technology Diversity: Different services might
benefit from different libraries.
Given these factors, we chose a microservices architecture. This
decision allows us to
82
•
Scale each service independently based on its
specific load.
•
Deploy and update services without affecting the entire
application.
•
Allow specialized teams to work on different services
concurrently.
•
Use the most appropriate technology for each service.
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
However, this decision also comes with trade-offs:
•
Increased complexity in service communication and
data consistency
•
Need for a more sophisticated deployment and
monitoring infrastructure (Chapter 9 covers metrics
and observability)
•
Potential performance overhead due to network
communication between services
To mitigate these challenges, we’ve implemented patterns like
•
Using Jakarta CDI events for loose coupling between
services
•
Using MicroProfile Health and Telemetry for improved
monitoring and observability
Synchronous vs. Asynchronous Communication
Another architectural decision we faced was choosing between
synchronous and asynchronous communication for certain operations.
Let’s consider the debit operation in the WalletService implementation in
Listing 3-9.
Listing 3-9. Debit method of the WalletService implementation by
SimpleWalletService
public TransactionResponse debit(final TransactionRequest
transactionsRequest) {
Wallet wallet =
walletRepository.findById(transactionsRequest.
getWalletId()).orElseThrow();
83
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
BigDecimal calculatedAmount = rateService.convert(
wallet.getCurrency(), transactionsRequest.
getAmount(), transactionsRequest.
getCurrency());
wallet.debit(calculatedAmount);
walletRepository.update(wallet);
Transaction transaction = new Transaction();
transaction.setType(TransactionType.DEBIT);
transaction.setWallet(wallet);
transaction.setCurrency(transactionsRequest.
getCurrency());
transaction.setAmount(transactionsRequest.getAmount());
transaction = transactionRepository.save(transaction);
TransactionCompletedEvent event = new Transaction
CompletedEvent(transaction.getId(), jsonWebToken.
getSubject());
transactionCompletedEvent.fireAsync(event);
return TransactionResponse.of(transaction.
toTransactionResponseData());
}
Here, we’re using asynchronous communication (fireAsync) to notify
other parts of the system about the completed transaction. This decision
was influenced by
1. Performance: We don’t want to hold up the debit
operation waiting for all listeners to process
the event.
84
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
2. Loose Coupling: Asynchronous events allow
us to add new listeners without modifying the
debit method.
3. Reliability: If a listener fails, it doesn’t affect the core
debit operation.
However, this decision means we need to handle potential
inconsistencies if an event listener fails. We address this through retry
mechanisms where necessary. Chapter 8 covers this in detail. After making
an architectural decision, how can it be communicated to the whole team?
Documenting Architectural Decisions
To ensure that the rationale behind these decisions is preserved and
communicated effectively, we use Architectural Decision Records (ADRs).3
An ADR is a document that captures an important architectural decision
made along with its context and consequences. Figure 3-2 shows a
visualization of the ADR process, which entails the actual architectural
decision-making, documenting it with an ADR record and then effectively
communicating it to all stakeholders of the project.
3 https://adr.github.io/
85
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Preserve And Communicate Architectural
Decisions
Make
architectural
decisions
Document
decisions with
ADRs
Communicate
decisions
effectively
Figure 3-2. Visualization of the ADR process
Listing 3-10 below a simplified example of an ADR for the
microservices architectural decision.
Listing 3-10. A sample ADR file
Title: Use Microservices Architecture for JWallet
Status: Accepted
Context:
JWallet needs to handle a large number of users and
transactions.
Different components may need to scale independently.
We want to enable independent deployment of components.
The team is organised into small, specialised groups.
Decision:
We will implement JWallet as a set of microservices.
86
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Consequences:
Positive:
- Can scale services independently.
- Can deploy and update services independently.
- Allows specialised teams to work concurrently on different
services.
Negative:
- Increases complexity in service communication.
- Requires more sophisticated deployment and monitoring
infrastructure.
Mitigations:
- Will use CDI events for loose coupling.
- Will implement Saga pattern for distributed transactions.
- Will utilise MicroProfile Health and Metrics for improved
monitoring.
This file can be stored as a plain text (.txt) file, a Markdown (.md) file,
or an AsciiDoc (.adoc) along with the project. The specific file extension
isn’t as important as the content structure and the consistency in format
across all ADRs in a project. The key is to use a format that is
•
Easy to read and write
•
Version control friendly
•
Easily convertible to other formats if needed
The collection of ADRs of a project together form the project’s
decision log.
87
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
Conclusion
As we’ve seen, documenting architectural decisions through ADRs
provides a clear record of the reasoning behind key choices in Jakarta
EE applications. This practice not only preserves valuable context for
future team members but also encourages thoughtful consideration of
architectural decisions.
Throughout this chapter, we’ve explored how Domain-Driven Design
(DDD) and layered architecture can be effectively applied within Jakarta
EE applications. Let’s recap the key takeaways:
1. Domain-Driven Design aligns software design with
business realities, creating a shared understanding
between technical and non-technical stakeholders.
Jakarta EE’s specifications naturally support DDD
concepts, allowing developers to focus on modeling
complex business domains.
2. Layered architecture provides a structured approach
to organizing application components, promoting
modularity, maintainability, and scalability. Jakarta
EE’s various specifications map well to different
layers, supporting clear separation of concerns.
3. Architectural decision-making in Jakarta EE
projects involves careful consideration of factors
such as performance, scalability, maintainability,
security, and team expertise. Each decision involves
trade-offs that must be weighed against project
requirements and constraints.
4. Documenting architectural decisions through
Architectural Decision Records (ADRs) ensures that the
rationale behind important choices is preserved and
communicated effectively across the team and over time.
88
CHAPTER 3
ARCHITECTING ENTERPRISE APPLICATIONS WITH JAKARTA EE
The importance of thoughtful architecture in building successful
enterprise applications with Jakarta EE cannot be overstated. A welldesigned architecture serves as the foundation upon which robust,
scalable, and maintainable applications are built. It guides development
efforts, facilitates team collaboration, and enables the application to evolve
in response to changing business needs.
As you develop your own Jakarta EE projects, we encourage you to
apply the principles and practices discussed in this chapter. Consider
how DDD can help you model your business domain more effectively.
Use layered architecture to organize your application components.
Make informed architectural decisions based on your specific project
requirements and constraints. And don’t forget to document these
decisions for the benefit of your team and future maintainers. Oh, and your
future self!
Remember, good architecture is not about following a set of rigid rules,
but about making informed choices that best serve your application’s
needs. As you gain experience, you’ll develop a deeper understanding
of how to leverage Jakarta EE’s capabilities to create powerful, flexible
enterprise applications.
In the next chapter, we’ll dive deeper into Jakarta CDI, exploring
how this powerful specification enables loose coupling and dependency
injection in Jakarta EE applications. This will build upon the architectural
concepts we’ve discussed, showing how Jakarta CDI supports and
enhances the implementation of well-designed Jakarta EE applications.
Let’s go!
89
CHAPTER 4
Managing
Dependencies
with CDI
As enterprise applications grow in complexity, the need for efficient and
manageable ways of handling dependencies becomes critical. Jakarta
Contexts and Dependency Injection (CDI) is a powerful specification
within the Jakarta EE platform designed to simplify the management
of dependencies and promote loose coupling between application
components. By doing so, it enhances the flexibility, maintainability, and
scalability of modern enterprise systems.
In this chapter, we will take a detailed look at Jakarta CDI, exploring
how it facilitates dependency management and helps achieve loose
coupling in Jakarta EE applications. Through practical examples, we will
demonstrate how to effectively use CDI to design maintainable, flexible
systems that can evolve with changing business requirements.
By the end of this chapter, you will
•
Understand what CDI is and how it helps achieve loose
coupling in Jakarta EE applications.
•
Know how to use the core features of CDI including
scopes, qualifiers, producers, and events.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_4
91
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
•
Be able to apply CDI interceptors and decorators to
implement cross-cutting concerns.
•
Learn CDI best practices and common patterns for
dependency injection.
•
Gain practical experience using CDI in a real
application through examples.
Understanding Inversion of Control
Before going into Jakarta CDI specifics, it is important to understand the
fundamental principle that underlies dependency injection: Inversion
of Control (IoC). IoC is a design principle, popularized by Martin Fowler,
that moves the control of object creation, lifecycle management, and
dependency resolution from your application code to a container or
framework.
Traditional vs. Inverted Control
In traditional programming
92
•
Objects are responsible for creating and managing their
own dependencies.
•
Components are tightly coupled to their dependencies.
•
Testing and maintaining code becomes more difficult.
•
Changes to dependencies require modifications
throughout the codebase.
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
With Inversion of Control
•
Dependencies are injected into objects rather than
created by them.
•
Components declare what they need rather than how
to get it.
•
The container manages object lifecycle and
dependency resolution.
•
Components become more loosely coupled and easier
to test.
•
Changes to implementations can be made without
modifying dependent code.
Jakarta CDI as an IoC Container
Jakarta CDI implements the IoC principle through its container, which
serves as a central authority for
•
Managing object creation and destruction
•
Resolving and injecting dependencies
•
Maintaining object scope and context
•
Handling cross-cutting concerns through interceptors
and decorators
•
An event mechanism for loosely coupled
communication between components
Jakarta CDI, as an implementation of the Inversion of Control pattern,
provides a container runtime that manages component lifecycles and
dependencies in Jakarta EE applications. At its core, CDI shifts the
responsibility of object creation and dependency management away
93
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
from application code and into a centralized container. This fundamental
change in control flow—from components creating their dependencies to
having them injected—is what makes Jakarta CDI such a powerful tool for
building maintainable enterprise applications.
Think of CDI as an automated assembly line in a factory. Rather
than each component needing to know how to construct and wire up its
dependencies, the CDI container acts as the factory floor—coordinating
the creation, assembly, and lifecycle management of all components.
When a component needs a dependency, it simply declares what it needs
through annotations, and the container ensures those dependencies
are properly instantiated and injected at runtime. This automation
significantly reduces the complexity of managing inter-component
relationships while promoting loose coupling and easier testing.
An Overview of CDI in Jakarta EE 11
The latest version of the CDI specification being shipped with Jakarta
EE 11 is Jakarta CDI 4.1. This release introduces several architectural
improvements and new features while maintaining backward
compatibility for most use cases. Key enhancements include method
invokers, executable methods, standardized interceptor binding
access, and the ability to apply @Priority annotations to producers. The
specification continues to support both CDI Lite and CDI Full variants,
with CDI Lite designed for restricted environments and CDI Full providing
the complete feature set.
A significant architectural change in 4.1 is the refactoring of Expression
Language (EL) integration, with EL-related BeanManager methods being
deprecated and moved to a new subinterface. This change removes the
direct dependency on Jakarta Expression Language from the core API,
making the codebase more modular. The specification has also been
restructured to eliminate circular dependencies and delegate integration
requirements to the broader Jakarta platform specifications.
94
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
For developers, new features like programmatic access to assignability
rules and enhanced BeanConfigurator capabilities for decorator
application provide more flexible and powerful dependency management
options. The specification also clarifies several areas including managed
bean requirements, unproxyable bean behavior, and the timing of
getReference() calls during deployment validation. This chapter and the
rest of the book focuses on CDI Full, which provides the complete feature
set available in Jakarta EE 11.
Key Features of CDI
Jakarta CDI comes with a set of features that help in developing loosely
coupled, complex enterprise applications. Having a loosely coupled
application means that the various application components aren’t rigidly
tied to each other. This way, it is easy to substitute one component for
another without having to significantly rewrite the application. The
following are the core features that the CDI API has available.
Type-Safe Dependency Resolution Mechanism
Jakarta CDI uses Java types to resolve dependencies. Unlike other
dependency injection implementations that are string based, CDI
uses Java types through a combination of metadata and Java beans to
resolve declared dependencies. This is achieved through a sophisticated
resolution mechanism that allows selection of dependencies at
development or deployment time.
Well-Defined Lifecycle Contexts
CDI supports binding stateful objects to a well-defined, extensible lifecycle
context. Each instance of a bean that you request from the runtime has a
predictable lifecycle, complete with callbacks that can be hooked into.
95
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Integration with the Web Tier
Through integration with the Jakarta Unified Expression Language (EL),
bean objects can be accessed directly from a Jakarta Server Faces page.
Interceptors
Jakarta CDI interceptors allow associating interceptors with Java objects
through type-safe interceptor bindings. These interceptors can be used to
implement features that are orthogonal to the core of any given bean such
as logging.
Events
Jakarta CDI events are a powerful, type-safe way to have completely
separate components of an application communicate in a fully decoupled
way through the use of event notifications. One component can fire an
event, and any registered listeners of that event will be notified or called by
the CDI runtime, passing in the requisite event object automatically.
An SPI for Creating Extensions
Jakarta CDI provides a service provider interface (SPI) for the creation of
portable extensions that integrate with the container.
These are the main features provided by Jakarta CDI for enterprise
application development on the Jakarta EE platform. The rest of this
chapter goes into detail about how to take advantage of these features in
application development starting with how to activate CDI in a Jakarta EE
application.
96
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Jakarta CDI Activation
The beans.xml Configuration File
Jakarta CDI uses a lightweight XML configuration file called beans.xml
to control its behavior within an application. This small configuration
file serves as the primary mechanism for enabling and configuring CDI
features. Listing 4-1 shows a typical example of a beans.xml file.
Listing 4-1. - Typical CDI beans.xml config file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/
beans_4_1.xsd"
version="4.1"
bean-discovery-mode="all">
</beans>
The most important attribute in this file is bean-discovery-mode,
which determines how CDI scans and processes components in an
application. This setting significantly influences CDI’s behavior during
application startup.
Bean Discovery Modes
The bean-discovery-mode attribute can take three values, each offering
different levels of CDI activation.
97
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
All
•
Enables comprehensive CDI scanning
•
Processes all eligible classes as potential CDI beans
•
Includes POJOs without explicit CDI annotations
•
Provides the most extensive CDI integration
•
Recommended for full Jakarta EE applications
Annotated (Default)
•
Scans only for classes with CDI bean-defining
annotations
•
Creates “implicit beans” from annotated components
•
Default behavior when no explicit mode is set
•
More selective than “all” mode
•
Suitable for applications requiring specific CDI
integration
None
98
•
Effectively disables CDI scanning
•
No automatic bean discovery
•
Rarely used in practice
•
Might be useful in specific scenarios where CDI should
be explicitly disabled
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
When using the “all” mode, as shown in the sample beans.xml in
Listing 4-1, every eligible class in the application becomes a potential
CDI bean, regardless of whether it carries specific CDI annotations. This
approach offers maximum flexibility and reduces the need for explicit
bean-defining annotations, though it requires careful consideration of
which classes should be included in CDI’s scope. All further discussions
in this chapter and the rest of the book assume an explicit bean discovery
mode set to all.
The CDI Container
The CDI container serves as the central implementation of the Inversion
of Control pattern. Rather than components managing their own
dependencies, the container takes on this responsibility, acting as an
automated orchestrator that handles component lifecycle management,
dependency resolution, and context management.
Core Responsibilities
The CDI container’s responsibilities extend far beyond simple dependency
injection. It serves as a sophisticated runtime component that manages
the entire lifecycle of your application’s beans, from initial validation
through creation, usage, and eventual destruction. Let’s explore each of
these core responsibilities in detail.
Startup Validation
One of the container’s most critical responsibilities is performing
comprehensive validation during application startup. This early,
preemptive validation prevents many common issues from surfacing at
runtime, when they would be much more difficult to debug and fix.
99
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
When your application starts (or boots), the container first scans your
codebase according to the bean-discovery-mode specified in your beans.
xml file. During this scan, it builds a complete model of your application’s
components and their relationships. Consider this example in Listing 4-2.
Listing 4-2. A simple bean declaration
@ApplicationScoped
public class SimpleRateService implements RateService {
@Inject
@RestClient
RateResource rateResource;
}
The container will validate this component by
•
Verifying that SimpleRateService has an injectable
implementation
•
Making sure a RateResource implementation exists
with the @RestClient MicroProfile qualifier
•
Checking that all scope combinations are valid
•
Confirming that any qualifiers or interceptors are
properly defined
If any validation fails, the container throws clear, descriptive errors
during startup. An example of such an error is shown in Listing 4-3.
Listing 4-3. Example CDI validation error
WELD-001408: Unsatisfied dependencies for type RateResource
with qualifiers @RestClient at injection point
[BackedAnnotatedField]
@Inject @RestClientRateResource rateResource
100
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
An error message like this results from the container not finding
a concrete implementation of the mentioned class, in this case the
RateResource at startup. This “fail fast” mechanism ensures there are
rarely CDI validation errors at runtime.
Instance Management
The most visible responsibility of the container is its management of
bean instances throughout their lifecycle. This management is far more
sophisticated than simple object creation—it involves instance creation,
dependency injection, and contextual lifecycle events.
Using the example in Listing 4-2, the container will
1. Create a new SimpleRateService instance.
2. Create a RateSource instance and inject it into the
rateResource field.
3. Call the @PostConstruct (discussed later) method
after all fields of the SimpleRateService have been
fully initialized.
4. Maintain the created SimpleRateService instance
throughout the life of the application instance.
5. Invoke @PreDestroy when the application-scoped
context is being destroyed.
6. Ensure all instances are properly released for
garbage collection.
This lifecycle management extends to all scopes (application,
session, request, etc.), with the container making sure that instances are
created and destroyed at exactly the right moments. All of these are done
transparently, without your involvement.
101
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Dependency Resolution
The container’s dependency resolution capabilities represent a
sophisticated system for matching injection points with the correct
implementations, incorporating a rich set of criteria including qualifiers,
alternatives, and contextual data. Still on the example in Listing 4-2, the
container must
1. Identify all RateResource interface implementations.
2. Match qualifiers to find the correct implementation
for the RateResource.
3. Resolve any field injection of type RateResource to
the right concrete type based on a combination of
qualifiers.
The container also manages advanced scenarios including
•
Producer methods and fields for dynamic instance
creation
•
Decorator chains for adding behavioral modifications
•
Interceptor bindings for cross-cutting concerns
•
Alternative implementations for different deployment
scenarios
This sophisticated resolution system ensures that your components
receive exactly the dependencies they need, while maintaining the
flexibility to adapt to different configurations and requirements. What
makes this system particularly powerful is its transparent operation—the
container performs all these complex tasks behind the scenes, allowing
you to focus on your application’s core business logic.
102
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Transparent Operation
While the container’s responsibilities are complex, it operates
transparently to application code. You will rarely need to interact with the
container directly, instead focusing your application code on
•
Defining components and their relationships through
annotations
•
Declaring scopes and qualifiers as needed
•
Writing business logic without concerning yourself
with instance management
The container works behind the scenes to ensure
•
Application components receive their dependencies
automatically.
•
Component instances are created and destroyed at
appropriate times.
•
Cross-cutting concerns are applied consistently.
•
Resources are properly managed throughout the
application lifecycle.
This separation of concerns—where business logic remains focused
on its primary responsibility, while the container handles technical
concerns—is the core of how Jakarta CDI implements the Inversion of
Control pattern in practice. At the heart of this implementation are two
fundamental concepts: beans and their contextual instances. Beans
serve as the blueprints that define your application’s components, while
contextual instances represent the container-managed objects created
from these blueprints.
103
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Jakarta CDI Beans
and Contextual Instances
A bean is the most atomic component in Jakarta CDI. A bean is any
Java class that has either a no-arg constructor or at least one injectable
constructor. It can optionally be explicitly annotated with one or more CDI
annotations. The few restrictions on a CDI bean are that it cannot be an
inner or abstract class. A CDI bean isn’t very different from a JavaBean.1
In fact, any JavaBean is automatically a CDI bean. Technically, this kind of
bean is called a managed bean—managed in the sense that the creation
and destruction of such bean instances are fully managed by the CDI
container.
The other technical kind of CDI bean is session beans. Session beans
are components annotated with any of the bean-defining metadata from
the EJBs spec, namely, @Stateless, @Stateful, and @Singleton. Any bean
annotated with any of these annotations is automatically a CDI bean
in addition to being an EJB and has the features and services provided
by both specifications. We will talk about EJBs in a section later in this
chapter.
You implement your application logic in a bean class and optionally
add CDI features to it using one or more CDI annotations. You can then
declare dependencies on your beans in other components, which are also
beans. An example of a CDI bean is shown in Listing 4-4.
Listing 4-4. The WalletService as a CDI bean
public class WalletService {
}
1 What is a JavaBean exactly? - Stack Overflow
104
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-4 shows a simple POJO called WalletService.
This class is a fully valid CDI bean that can be injected into other
beans. Even though WalletService doesn’t have any CDI attributes yet,
it will still be scanned at boot time by the container because our bean
discovery mode in the beans.xml file is set to all. We can explicitly add
CDI features to the WalletService bean by giving it some attributes using
some CDI annotations. Listing 4-5 shows the WalletService with some CDI
attributes added through annotations.
Listing 4-5. The WalletService with CDI attributes
@RequestScoped
@Transactional
public class WalletService {
}
Listing 4-5 shows the WalletService bean given some CDI attributes.
The @RequestScoped annotation tells the CDI container in what
context instances of this bean should be put. The @Transactional
annotation is an interceptor that will automatically demarcate
transactional boundaries for methods invoked on instances of the
WalletService. The set of CDI attributes you can give a bean are qualifiers,
scopes, alternatives, and name (we’ll be discussing these later in this
chapter). This bean can be injected into other beans by annotating a field
of type WalletService with the @Inject annotation as shown in Listing 4-6.
Listing 4-6. A dependency declaration on our WalletService
CDI bean
public class WalletResourceImpl implements WalletResource {
@Inject
WalletService walletService;
}
105
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-6 shows an injection of the WalletService bean into the
WalletResourceImpl component.
The field type of the walletService variable is WalletService. This brings
us to the question of how the container is able to resolve the type to use in
resolving an injection point.
CDI Bean Types
An injection point is any field or parameter that is expected to be
instantiated by the CDI container. So, for instance, the walletService field
annotated with @Inject as shown in Listing 4-6 is an injection point. The
CDI container will inject a contextual instance of type WalletService into
the variable walletService. But how will the CDI container be able to know
the type to resolve a variable to for any given injection point? Obviously
we will need a way to tell the runtime the types of our CDI beans so it can
correctly resolve each injectable field to its type.
Technically, a CDI bean is any Java class that implements the jakarta.
enterprise.inject.spi.Bean<T> interface. This interface represents a bean
and defines everything the CDI container needs to manage instances of
the bean. The Bean interface itself extends the jakarta.enterprise.inject.spi.
BeanAttributes<T> interface. This interface contains the methods
106
•
getName(): Get the EL name of a bean if the @Named
annotation has been used on the bean.
•
getQualifiers(): Get the set of qualifiers of the bean.
•
getTypes(): Get a set of the bean types of the bean.
•
getScope(): Get the scope of the bean.
•
getStereotypes(): Get the set of stereotypes of the bean.
•
isAlternative(): Boolean method that determines if the
bean is an alternative or not.
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
These methods return relevant information that helps the CDI
container resolve injection points to the right bean types. In addition,
the Bean interface also contains the create() and destroy() methods,
which are called by the container to, respectively, create and destroy
instances of a bean. In practice you will not need to explicitly implement
the Bean interface. CDI implementations can generate Bean<T>
interface implementations from your beans on your behalf. Through
implementation of the Bean<T> interface for your beans, the CDI
container can resolve a bean type through its type, by a combination of
type and qualifiers, and by name (in Expression Language).
Resolution by Type
The type of any CDI bean is all superclasses of that bean up to java.
lang.Object, all implemented interfaces, either directly or indirectly,
and the class itself. The WalletService bean, as an example, will have
its types be java.lang.Object and WalletService because it doesn’t have
any superclasses other than Object nor implements any interfaces. The
WalletResourceImpl however (Listing 4-6) has three types; it is an Object, a
WalletResource, and a WalletResourceImpl.
Resolution by Type and Qualifier
Qualifiers in CDI are a way to label or qualify CDI components to further
identify them to the CDI container. The WalletResourceImpl.java class as
shown in Listing 4-6 implements the WalletResource interface. This means
that we can have an injection point of type WalletResource as shown in
Listing 4-7.
107
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-7. Injecting into a field by interface type
public class HelloResourceImpl implements HelloResource {
@Inject
WalletResource walletResource;
}
Listing 4-7 shows HelloResourceImpl declaring a dependency on
WalletResource in the variable walletResource. WalletResource is an
interface that is implemented by WalletResourceImpl. As interfaces can be
implemented by more than one class, the injection point walletResource
as declared in Listing 4-7 would need to be qualified, because the CDI
container will not know at runtime which WalletResource implementation
to inject into any given injection point of type WalletResource. We will
come back to this when we talk about CDI qualifiers in a bit.
Resolution by Name
The two previous bean resolution mechanisms, namely, resolution by type
and by type and qualifier, are type-safe. The third way of resolving beans is
by name. You can access instances of a given bean in string­
based environments like the Jakarta EE platform’s Expression Language.
A bean can be resolved when accessed in EL by annotating it with the
built-in qualifier @Named. Listing 4-8 shows the WalletService annotated
with @Named.
Listing 4-8. The use of @Named to resolve the bean in EL
@Named
@RequestScoped
@Transactional
public class WalletService {
}
108
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-8 shows the WalletService annotated with the @Named
qualifier.
With that qualifier in place, the WalletService can be accessed through
an EL expression. By default, the WalletService can be accessed through
the automatically available variable walletService in an EL expression like
this: #{walletService.someMethod()}. When accessed this way, the CDI
container will take care of creating an instance and injecting it into the
variable.
No matter what mechanism is used to resolve a bean instance, the CDI
container will always create the right instance for the given field type. The
technical term for the instances of beans created by the CDI container for
satisfying injection points is contextual instances. This brings us to the
question, What is a contextual instance?
Jakarta CDI Beans and Contextual Instances
The previous section defined a CDI bean as a Java class that optionally
has CDI metadata associated with it and can be used to satisfy injection
points. A bean, then, is a source of instances used to satisfy dependency
requests in a Jakarta EE application. The instances of a bean created by the
CDI container to satisfy injection points are technically called contextual
instances.
The Bean<T> interface discussed in the previous section also extends
the Contextual<T> interface. The Contextual<T> interface is where the
Bean<T> interface inherits the create and destroy methods from. Instances
created from any bean implementing the Bean<T> interface are called
contextual types. Since CDI runtimes generally create implementations
of the Bean<T> interface on your behalf, you end up with contextual
instances injected into your injection points.
When a request is made for a bean instance from the CDI container via
the use of the @Inject annotation on an injection point, the container must
ensure that the contextual instance returned is associated with the right
109
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
scope. Contextual bean instances are always associated with a scope. You
can either explicitly associate a bean with a scope or have the container
associate it with a default scope in the absence.
Scopes andContexts
You can think of a CDI scope as a well-defined lifetime within which a
bean instance can exist. When a given scope is destroyed, so are all the
bean instances associated with that scope. Different beans with different
scopes can be injected into each other. The CDI container takes care of
ensuring the right bean is injected into each dependent injection point.
As an example, we have a SecurityManager that we want to have only
a single instance for the entire lifetime of the application—from boot to
shutdown. This SecurityManager controller has a dependency on another
controller, UserService, that is scoped to each HTTP request. Listing 4-9
shows the UserService controller.
Listing 4-9. The UserService controller
@RequestScoped
@Transactional
public class UserService {
@Inject
UserRepository userRepository;
}
Listing 4-9 shows the UserService class annotated with
@RequestScoped.
This is one of the built-in scopes (more about the various scopes in a
bit). This bean declares a dependency on the UserRepository, which is also
another RequestScoped bean. Listing 4-10 shows the SecurityManager
controller.
110
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-10. The SecurityManager controller
@ApplicationScoped
public class SecurityManager {
@Inject
UserService userService;
}
Listing 4-10 shows the SecurityManager controller and its dependency
declaration on the UserService controller.
Note that the SecurityManager is annotated with @ApplicationScoped.
This is also one of the built-in scopes. Even though the UserService and
SecurityManager are associated with different scopes, the CDI container
will ensure that all clients of the SecurityManager see different instances of
the userService contextual object. It achieves this through the use of bean
proxying.
Bean Proxying
The SecurityManager controller class will have a single instance through
the entire life of the application. However, it declares a dependency on a
bean that is scoped to each HTTP request. What this means is that each
client of the SecurityManager should have a different instance of the
UserService bean injected. This creates an apparent paradox: how can
a single, long-lived SecurityManager instance work with a UserService
dependency that needs to be different for each request? The answer lies in
CDI’s proxy mechanism.
111
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Proxy Objects
When you inject a bean into another component, what you get is not a
direct reference to the bean instance itself. Instead, the container provides
a specially generated proxy object. The userService reference in the
SecurityManager controller shown in Listing 4-10 is not a direct reference
to the contextual instance but a client proxy object.
When any method is called on userService, the client proxy intercepts
the call and performs several following steps:
1. It determines which request is currently active.
2. It locates or creates the correct UserService instance
for that request.
3. It delegates the method call to that instance.
4. It returns the result back to the caller.
This proxying mechanism is transparent to your code—you work with
the injected reference as if it were a direct reference to the bean instance.
The container handles all the complexity of finding or creating the right
instance for the current context.
Why Proxies?
The Jakarta CDI proxy-based approach solves a number of challenges in
dependency injection including the following.
Scope Independence
Without proxies, it would be impossible to inject a request-scoped bean
into an application-scoped bean. The proxy ensures that regardless of
scope mismatches, each method call gets routed to the correct instance for
the current context.
112
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Lazy Initialization
Proxies enable the container to defer instance creation until it’s actually
needed. This is particularly important for request-scoped beans, where
creating instances too early would waste resources.
Circular Dependencies
Proxies solve the problem of circular dependencies—situations where two
or more beans depend on each other. Without proxies, this would create
an impossible chicken-and-egg scenario: neither bean could be created
because each requires the other to exist first.
Consider a real-world example in an ecommerce system where
an order service needs customer information and a customer service
needs order history. Proxies solve this apparent deadlock by acting as
placeholders, allowing both services to be constructed and wired together
without requiring either to be fully initialized first. This enables you to
model your components based on their logical relationships rather than
technical constraints.
Proxy Requirements
While proxies are generally transparent, there are some requirements CDI
stipulates when designing your beans.
Method Visibility
•
Proxied methods must be public or protected.
•
Private methods can’t be intercepted by the proxy.
113
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Class Requirements
•
Classes must be non-final (the proxy needs to
extend them).
•
Must have a no-argument constructor or a constructor
annotated with @Inject.
Method Finality
•
Final methods can’t be intercepted.
•
Avoid making methods final unless absolutely
necessary.
Proxies create scope independence. But what are the available scopes
in Jakarta CDI?
Built-In Scopes
Jakarta CDI comes with a number of built-in scopes that cater to the
common needs of most applications. You can create your own scope
if you want. But in order to create a cohesive platform and provide a
uniform base for other APIs to build on, the CDI spec comes with a total
of five built-in scopes. They are @ApplicationScoped, @RequestScoped,
@SessionScoped, @ConversationScoped, and the @Dependent
pseudo-scope.
@ApplicationScoped
The @ApplicationScoped annotation on a bean makes the bean an
application-scoped singleton. What this means is that for the entire
lifetime of any given application running instance, only a single
contextual instance of this @ApplicationScoped bean will be created.
114
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The SecurityManager controller shown in Listing 4-10 is an applicationscoped bean. The application scope itself is created at container boot
time. However, the first and only contextual instance of this bean will
be created when a method is first invoked on a proxy. After creation, no
matter how many SecurityManager bean proxies the container creates, all
method invocations will be delegated to the same bean instance across the
application.
It does not matter what other scope the SecurityManager gets injected
into. All method invocations will eventually be serviced by the same
bean instance. That instance will be destroyed by the container when the
application scope is destroyed during application shutdown.
@RequestScoped
The @RequestScoped annotation on a bean associates the bean with an
external request originating from a servlet request, a web service request,
or a remote EJB request. The container will also create a request scope
during a CDI event (we will talk about CDI events in a later section)
dispatch to an async observer method.
For a servlet request, the CDI container will create a request scope
when service() or doFilter() methods are invoked on a servlet or servlet
filter, respectively. For a web service, the container will create a request
scope for each web service invocation through Jakarta REST. A request
is also created for each remote EJB invocation during the handling of
the invocation by the EJB. A request scope will also be created when the
CDI container dispatches an event to an async method observer of that
particular event. For all these invocations, the request scope will be created
and destroyed once the invocation ends.
The UserService controller shown in Listing 4-9 is scoped to the
request context through the @RequestScoped annotation. For each web
service call on the UserResourceImpl resource, a new request scope will be
115
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
created and a new contextual instance of the UserService will be created
and associated with that scope, because the UserResourceImpl declares a
dependency on the UserService controller as shown in Listing 4-11.
Listing 4-11. The UserResourceImpl and its dependent declaration
on the UserService controller
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("users")
public class UserResourceImpl implements UserResource {
@Inject
UserService userService;
}
Listing 4-11 shows the @RequestScoped UserService controller
injected into the UserResourceImpl REST web service class.
For each REST method invoked on the UserResourceImpl class, a
new request scope will be created along with the contextual instances
of UserResourceImpl and UserService contextual instances associated
with that scope. After the method invocation returns, both the scope and
associated contextual instances will be destroyed.
@SessionScoped
The session-scoped context can be associated with a bean through the
@SessionScoped annotation. This scope is tied to a single user session and
is shared between all servlet requests that occur in the same HTTP request.
The session scope is active during the service method of any servlet,
during the doFilter() method of any servlet filter, and when the container
calls any ServletRequestListener, AsyncListener, or HttpSessionListener.
This scope is destroyed when the session times out. But before the
session gets destroyed, the container will make sure there are no uncalled
116
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
HttpSessionListeners for that session. This ensures that the session is not
destroyed while there are still listeners attached to it. Listing 4-12 shows
the use of the @SessionScoped annotation on the UserSession controller.
Listing 4-12. The use of @SessionScoped
@SessionScoped
public class UserSession implements Serializable {
@Inject
SecurityManager securityManager;
}
Listing 4-12 shows the UserSession controller.
It declares a dependency on the SecurityManager. Remember from
Listing 4-10 that the SecurityManager is an @ApplicationScoped bean.
The UserSession is the first bean we are seeing that implements the
Serializable interface. Why? Because the @SessionScoped annotation on a
bean makes the bean passivation capable. What this means is that during
runtime, when the CDI container determines that there are idle instances
of session-scoped beans, it can temporarily transfer the state of such bean
instances to secondary storage. Effectively, the container will passivate or
save the state of the idle instances. The Serializable interface marks the
bean as such. In addition, all fields in a session-scoped bean should be
equally serializable or transient.
@ConversationScoped
The conversation scope is a special scope for holding a “conversation”
between a client and the server. It is longer than a request scope
but shorter than a session or application scope. You can think of a
conversation with the example of a sign-up form that spans multiple
pages. Each page is a conversation between your browser and the
server, and once you reach the final page and hit the submit button, the
117
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
conversation terminates. CDI provides the built-in Conversation bean for
managing the conversation state in a conversation-scoped bean. Listing 4-13
shows a conversation-scoped SignupManager.
Listing 4-13. The SignupManager as a conversation-scoped bean
@ConversationScoped
public class SignupManager implements Serializable {
@Inject
Conversation conversation;
public void beginSignup() {
beginConversation();
}
public void submit() {
endConversation();
}
private void beginConversation() {
if (conversation.isTransient()) {
conversation.begin();
}
}
private void endConversation() {
if (!conversation.isTransient()) {
conversation.end();
}
}
}
118
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-13 shows the Signup bean.
It also implements the Serializable interface because it might get
passivated by the container, just like a session-scoped bean. Similarly, all
fields in a conversation-scoped bean should be passivation capable or
transient. By default, a @ConversationScoped bean is in transient mode.
That is, a contextual instance of a conversation-scoped bean is likely to
be destroyed by the container at any time because it’s transient. You will
have to explicitly initiate a conversation-scoped bean into a conversation.
The way to achieve that is through the use of methods on the Conversation
interface.
The SignupManager declares a dependency on the Conversation
bean through an injection point of said type. An instance of the
Conversation interface will be created by the container automatically.
Method beginSignup() first makes a call to method beginConversation().
The beginConversation() method first makes a check by calling
Conversation#isTransient() to check if the bean is in transient mode.
This method returns true if the bean is currently not in any
conversation state, or, technically, a long-running conversation. Why this
check? Because if we call the Conversation#begin() method on a bean
that is already in a long-running conversation, an IllegalStateException
will be thrown by the container. Method beginConversation() only starts
the long-running conversation if that check returns true by calling the
Conversation#begin() method. After this invocation, the bean is put into
the conversation scope. This scope will transcend a single request, but
shorter than a session scope.
After the registration is done and ready to be submitted, method
submit() first calls method endConversation(). This method does an
inverse check on the bean to see if it’s in a long-running conversation and
then calls the Conversation#end() method. This is also because if you
invoke Conversation#end() on a Conversation that is not long-running, the
container throws an IllegalStateException.
119
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The Conversation#begin method also optionally takes a String parameter
as the conversation ID. This ID will be associated with the conversation
that is started by the method. In the absence of an explicit ID, the container
generates one for you. You can get the ID associated with the current
long-running conversation by calling the Conversation#getId() method. It
returns the ID or null if the conversation is transient. You can also set and
get the timeout of the conversation in milliseconds through the methods
Conversation#setTimeout() and Conversation#getTimeout(), respectively.
@Dependent Pseudo-scope
@Dependent is a pseudo-scope that is dependent upon where it is used.
It is the default scope that a bean is put into when no explicit scope is
defined. It is dependent because the @Dependent-scoped bean takes or
inherits the scope of the bean into which it is injected. A dependentscoped bean has two distinguishing qualities, namely:
•
No injected instance of the bean is ever shared between
multiple injection points.
•
Any instance of the bean injected into an object that is
being created by the container is bound to the lifecycle
of the created object.
Effectively every request for a dependent-scoped bean always results
in a new bean. And the actual scope of this dependent bean instance will
be the scope of whatever bean it’s being injected into. We will touch a little
more on dependent scope in later sections of this book when we cover
other CDI constructs.
So far we have talked about beans and their possible scopes. At the
heart of CDI is managing dependencies between these beans in their
different scopes. The “entry point” to using the dependency management
magic wand in CDI is through the use of the @Inject annotation at
injection points.
120
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Injection Points
An injection point in Jakarta CDI represents a place where a request
for a contextual instance is made. When a type at a specific location is
annotated with the @Inject annotation, the CDI container instantiates that
particular variable on behalf of the application. CDI provides three broad
categories of injection points.
Field Injection Point
A field injection point is what has been discussed so far in this book. It
is simply annotating a field of a given bean type in a class with @Inject.
In Listing 4-13, the field conversation of type Conversation is annotated
with @Inject. The container will take care of providing the right contextual
instance of the annotated field type into the variable conversation. It
effectively guarantees the prevention of a NullPointerException when
methods are invoked on the conversation variable at runtime. Field
injection is simple and easy to read. However, keep in mind that it could
make unit-testing components complex especially if the fields have private
visibility.
Constructor Injection
The second Jakarta CDI injection point is the constructor injection point.
Remember when we defined a CDI bean as any Java class with a no­
arg constructor or a bean with at least one CDI injectable constructor?
Constructor injection is when you annotate a constructor of a bean with
@Inject, passing in beans that CDI can instantiate as arguments. Listing 4-14
shows the SignupManager conversation-scoped bean refactored to use a
constructor injection to instantiate the conversation field.
121
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-14. The SignupManager using a constructor
injection point
@ConversationScoped
public class SignupManager implements Serializable {
Conversation conversation;
@Inject
public SignupManager(final Conversation conversation) {
this.conversation = conversation;
}
}
Listing 4-14 shows the SignupManager bean using constructor
injection to instantiate the conversation field. This constructor injection
will be called automatically by the container.
It is important to note that when using constructor injection, all the
arguments passed to the constructor must be CDI beans or at least beans
that the container knows how to instantiate (through, e.g., producer
methods, discussed in a later section). The application will fail CDI boot
validation if any of the constructor parameters is not a valid CDI bean.
Also, each bean is allowed only one constructor injection. A bean can
still have a no-arg constructor and other constructors, but having more
than one constructor injection point will result in errors at application
boot time.
One good use of the constructor injection is for testing. When you
need to create unit tests for your controllers (for instance, using Mockito),
you can use constructor injection to initialize bean fields at runtime.
Listing 4-15 shows a basic unit test structure for the SignupManager using
Mockito.
122
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-15. Unit test of SignupManager
@ExtendWith(MockitoExtension.class)
class SignupManagerTest {
@Mock
private Conversation conversationMock;
private SignupManager signupManager;
@BeforeEach
void setUp() {
signupManager = new SignupManager(conversationMock);
}
@Test
void beginSignup_whenConversationIsTransient_
shouldBeginConversation() {
// Arrange
when(conversationMock.isTransient()).thenReturn(true);
// Act
signupManager.beginSignup();
// Assert
verify(conversationMock).begin();
}
}
Using constructor injection, the Conversation dependency mock is
passed to the instance of the SignupManager class under test. Constructor
injection makes for easy and clean code.
123
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Method Injection
A method injection point is when a method is annotated with @Inject.
Similar to constructor injection, all the parameters of the method must
be CDI beans or at least the container must know how to initialize
them. Method injections are called initializer methods. The container
will automatically call these methods, similar to constructor injections.
Listing 4-16 shows an example of such an initializer method in the
MeteredWalletService.
Listing 4-16. CDI method injection point in MeteredWalletService
public class MeteredWalletService implements WalletService {
Meter meter;
@Inject
public void initializeMeter(Meter meter) {
this.meter = meter;
}
}
The initializeMeter method is annotated @Inject, and the sole
parameter is of type io.opentelemetry.api.metrics.Meter. The injected
instance is used to initialize the meter dependency of the class. This
method will be called by the container automatically with the relevant
contextual instance.
These are the three main injection points in CDI. In addition to these,
however, there are two other points where the parameters passed are CDI
instantiated without the need for an explicit @Inject annotation. These
are producer and observer methods. We cover both constructs in later
sections. Bean discussions to this point have focused on pure CDI beans
or plain old Java objects. However, the other type of valid CDI beans are
enterprise beans or EJBs.
124
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Jakarta Enterprise Beans
The Jakarta Enterprise Beans, previously Enterprise JavaBeans or EJBs, is a
specification that precedes the CDI specification. It is a componentoriented specification for creating beans that implement business logic.
It had its own dependency resolution mechanism. Annotating a Java
class with any of @Stateless, @Stateful, and @Singleton made that class a
component that was transactional, pooled, and secured by default.
The advent of CDI and the need to have a core Inversion of Control
implementation on the Jakarta EE platform meant CDI had to reimplement
a number of the features in EJBs. However, these two specifications have
been harmonized such that CDI is the single entry point for creating
business layer components. Even though CDI is the preferred way to create
business services, Jakarta Enterprise Beans still remains widely in use and
will be for the foreseeable future.
All Jakarta Enterprise Beans are automatically CDI beans. Annotating
a bean with a Jakarta Enterprise Bean-defining annotation makes
that bean both a CDI and Jakarta Enterprise Bean with the features of
both specifications available to the bean. From the perspective of CDI,
Jakarta Enterprise Beans are called session beans. Listing 4-17 shows the
SecurityManager with two new annotations.
Listing 4-17. The SecurityManager with EJB annotations
@Singleton
@Startup
public class SecurityManager {
@Inject
UserService userService;
public void saveUser(final CreateUserRequest request) {
userService.createUser(request);
}
}
125
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-17 shows the SecurityManager annotated with two Jakarta
Enterprise Beans annotations—@Singleton and @Startup.
The @Singleton annotation makes this bean a singleton Jakarta
Enterprise Bean. The @Singleton annotation is not much different from
the @ApplicationScoped annotation in the sense that both result in having
just a single instance of the bean throughout the life of the application
runtime.
The @Startup annotation marks the SecurityManager for eager
instantiation. What this implies is that an instance of the bean will be
created as part of the application startup sequence. The @Singleton
annotation also makes each method invoked on the SecurityManager
contextual instance transactional by default. The container will join or
create transactions if none exists for each method invocation.
You can use eagerly instantiated Jakarta Enterprise Beans singletons to
do some form of ahead-of-time housekeeping before all other components
of your application are ready. For instance, you need to have some form
of data ready when the application starts, but you need to load this
application from an external service. In such a case, you can eagerly
instantiate a singleton and make that call.
Metadata from both API specifications are perfectly compatible with
each other. In greenfield applications however, you should use CDI almost
exclusively. But there is still a significant body of code out there that uses
Jakarta Enterprise Beans. Maintaining or migrating such code to CDI
should be quite straightforward since both specs play nicely with each
other. We will get back to Jakarta Enterprise Beans in Chapter 5 when we
talk extensively about transactions and transactional boundaries. For now,
let us continue with qualifiers.
126
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Qualifiers
Qualifiers are annotations that help the CDI container decide which
specific implementation of an interface or class to inject when there
are multiple options available. Think of qualifiers as labels that help the
container match the right implementation to each injection point.
Listing 4-18 shows the RateResource interface.
Listing 4-18. The RateResource interface
@RegisterRestClient(baseUri = BASE_URI)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("rates")
public interface RateResource {
String BASE_URI = "http://rate:3002/rate/api";
}
The RateResource interface is a REST endpoint declaration that uses
the @RegisterRestClient() from the Eclipse MicroProfile REST Client API
(there’s a full chapter on this later in the book) to automatically create a
REST client for this Jakarta REST resource.
Injecting by this interface type will cause a validation error at boot
time because there will be two implementations in the application. One
is the RateResourceImpl that is part of the application code. The other is
the REST Client that is automatically generated by the Eclipse MicroProfile
REST Client.
Because there is more than one possible implementation of the
interface, the CDI container will need to know exactly which concrete
implementation to use at runtime to satisfy the injection point declared
in HelloResourceImpl. And since no qualifiers were declared, the
default qualifier @Default is not enough to tell the container which
127
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
implementation to use, and thus during application startup, CDI validates
and throws an error, truncating the application boot. An example of the
error message is shown in Listing 4-19.
Listing 4-19. CDI boot validation error message
Ambiguous dependencies for type RateResource with qualifiers
@Default
To fix this, use the @RestClient qualifier on the RateResource field as
shown in Listing 4-20.
Listing 4-20. The @RestClient qualifier usage
@ApplicationScoped
public class SimpleRateService implements RateService {
@Inject
@RestClient
RateResource rateResource;
}
The @RestClient is a qualifier from the MicroProfile Rest Client API
that tells the CDI runtime to inject the Rest Client-specific implementation
of the RateResource into the rateResource field. The application can boot
up fully now because there is no ambiguity about which instance to inject
into the rateResource field.
Custom Qualifiers
The @RestClient is an example of a built-in qualifier. You can also create
custom qualifiers easily. An example of a need for custom qualifiers
is in messaging. There are different events that warrant the firing of
128
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
different notification messages to users of an application. A new account
registration, for instance, would normally send a new account notification
via email.
An account transaction, however, will send both SMS and email
notifications. Using CDI events (covered a little later in this chapter),
different notification events can be fired. However, there needs to be a way
to tell the CDI runtime to which event listener a given notification should
be sent. One way to do that is through qualifiers. Rather than create SMS
and email qualifiers, it is more succinct to create a single qualifier that
takes parameters as done in Listing 4-21.
Listing 4-21. The MessageOption custom qualifier
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD, PARAMETER})
public @interface MessageOption {
MessageType value();
enum MessageType {
SMS,
EMAIL
}
}
The MessageOption qualifier is a custom qualifier that can take a
parameter of type MessageType. To determine which event listener will
receive a given type of notification, the listener will qualify its payload
with the requisite qualifier. Listing 4-22 shows the MessageCenter bean
with two methods respectively annotated with the two MessageOption
parameter values.
129
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-22. The MessageCenter with MessageOption qualified
listeners
@RequestScoped
public class MessageCenter {
public void sendUserSmsAsync(@ObservesAsync
@MessageOption(MessageOption.MessageType.SMS) UserResponse
userResponse) {
// TODO --> Send SMS through gateway... Async
}
public void sendEmail(@ObservesAsync
@MessageOption(MessageOption.MessageType.EMAIL) UserResponse
userResponse) {
// TODO --> send email asynchronously
}
}
The MessageCenter has two event listener methods. Each of these
listeners caters to a specific event messaging option. Don’t worry much
about the rest of constructs used as they are from the CDI event feature.
However, notice the use of the @MessageOption qualifier on both method
parameters. With this use of the qualifier, an email notification event will
be routed to the sendEmail method. Likewise, an SMS notification event
will be routed to the sendUserSmsAsync event listener.
Built-In Qualifiers
Jakarta EE and MicroProfile come with a number of built-in qualifiers, the
@RestClient annotation discussed above being one of them. Other built-in
qualifiers are the @Default, @Named, and @Any qualifiers.
130
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
@Default Qualifier
The @Default qualifier is implicitly present on all beans that don’t
explicitly declare another qualifier (except @Named). It serves as the basic
qualifier when none other is specified.
@Any Qualifier
The @Any qualifier is a special built-in qualifier that is automatically
present on every bean and event, regardless of other qualifiers. It provides
a way to interact with all beans or events of a certain type.
Its characteristics include the following:
•
Present on all beans automatically
•
Present on all events automatically
•
Allows access to all implementations of a type
The MessageCenter bean shown in Listing 4-22 can be expanded to
have a catch-all method that listens for all notification types. Listing 4-23
shows the newly expanded MessageCenter bean.
Listing 4-23. The expanded MessageCenter bean
@RequestScoped
public class MessageCenter {
public void sendUserSmsAsync(@ObservesAsync
@MessageOption(MessageOption.MessageType.SMS) UserResponse
userResponse) {
// TODO --> Send SMS through gateway... Async
}
public void sendEmail(@ObservesAsync
@MessageOption(MessageOption.MessageType.EMAIL) UserResponse
userResponse) {
131
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
// TODO --> send email asynchronously
}
public void sendMessage(@ObservesAsync UserResponse
userResponse) {
// TODO
}
}
The sendMessage method is a listener that implicitly has the @
Any qualifier. This makes it a catch-all listener that will be called for all
notification types—email or SMS.
The @Any qualifier is particularly useful when you need to
•
Programmatically select beans at runtime.
•
Work with multiple implementations of an interface.
•
Handle all events of a particular type.
@Named Qualifier
The @Named qualifier provides a string-based way to identify beans. It’s
commonly used in conjunction with expression languages and when you
need to distinguish beans by name rather than type.
These are the fundamental built-in qualifiers that come with Jakarta
CDI. Use
132
•
@Default for standard injection scenarios
•
@Any when you need access to all implementations
•
@Named when you need string-based identification
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
In practice however, @Default is seldom used explicitly as it is implied
in the absence of any explicit qualifiers. @Any is used in advanced and
corner-case scenarios. @Named is in Jakarta Server Faces, mostly.
Listing 4-24 shows an example of the @Named qualifier used to create
a custom name for a component accessed in a view layer in Jakarta
Server Faces.
Listing 4-24. An example of a custom bean name via @Named
@ConversationScoped
@Stateful
@Named("newAccountManager")
public class SignupManager implements Serializable {
Conversation conversation;
@Inject
public SignupManager(final Conversation conversation) {
this.conversation = conversation;
}
public void beginSignup() {
beginConversation();
}
public void submit() {
endConversation();
}
private void beginConversation() {
if (conversation.isTransient()) {
conversation.begin();
}
}
133
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
private void endConversation() {
if (!conversation.isTransient()) {
conversation.end();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core ">
<f:view>
<h:form>
<h:inputText id="email" label="Email" required="true"/>
<h:commandButton action="#{newAccountManager.
beginSignup()}"/>
</h:form>
</f:view>
</html>
The SignupManager is a CDI component that is annotated @Named,
with the value newAccountManager. This custom value becomes the
custom identifier of the SignupManager bean instance in the presentation
layer, as shown in the JSF fragment.
The qualifier construct in CDI is a deceptively simple yet powerful
mechanism that helps in the writing of clean, readable, and testable
code. All the beans discussed so far are beans that have been declared
from scratch in one way or another—either as interfaces or concrete Java
134
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
classes. However, sometimes there is the need to transform beans that are
not part of your application code into CDI beans. That is where the CDI
producer feature comes in.
Jakarta CDI Producers
The producer construct in CDI is a way to transform beans or Java types
that are not part of application code into CDI, injectable beans to be used
in the application. Remember a CDI bean is any Java class with a no­
arg constructor or one that has at least one constructor annotated with
@Inject.
All non-trivial applications have dependencies on external libraries
that, ideally, would contain valid CDI beans. However, not every
component in these external libraries meets the requirements of a bean.
For example, Listing 4-25 shows a snippet of the OpenAiChatModel class
from the LangChain4J Java library.
Listing 4-25. OpenAiChatModel
public class OpenAiChatModel implements ChatLanguageModel,
TokenCountEstimator {
public OpenAiChatModel(String baseUrl,
String apiKey,
String organizationId,
String modelName,
Double temperature,
Double topP,
List<String> stop,
Integer maxTokens,
Integer maxCompletionTokens,
Double presencePenalty,
Double frequencyPenalty,
135
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Map<String, Integer> logitBias,
String responseFormat,
Boolean strictJsonSchema,
Integer seed,
String user,
Boolean strictTools,
Boolean parallelToolCalls,
Duration timeout,
Integer maxRetries,
Proxy proxy,
Boolean logRequests,
Boolean logResponses,
Tokenizer tokenizer,
Map<String, String> customHeaders,
List<ChatModelListener> listeners) {
}
}
The OpenAiChatModel is a class with an all-arg constructor. It does
not have a zero-arg constructor. This makes it ineligible for CDI injection.
However, as the application is a Jakarta EE application with dependency
injection managed by Jakarta CDI, it would be ideal to transform
this component into a valid CDI bean such that instead of manually
instantiating the class, dependent components can @Inject it.
Producer Methods
A straightforward way to convert the OpenAiChatModel into a Jakarta CDI
bean is through a producer method as shown in Listing 4-26.
136
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-26. OpenAiChatModel producer method
@Produces
@ApplicationScoped
public OpenAiChatModel produceModel() {
return OpenAiChatModel.builder()
.apiKey(apiKey)
.responseFormat("json_object")
.modelName(gptModel)
.temperature(temperature)
.timeout(ofSeconds(60))
.logRequests(true)
.logResponses(true)
.build();
}
The produceModel method shown above initializes and returns the
OpenAiChatModel bean contextual instance. The method is annotated
with the @jakarta.enterprise.inject.Produces and @jakarta.enterprise.
context.ApplicationScoped annotations. The first one marks the method
as a producer method. The second one scopes the returned type to an
application-scoped bean. Being a producer method means that CDI
will call this method when it encounters an injection point of type
OpenAiChatModel anywhere in the application. This is all that it takes
to transform the external component into a CDI bean in the application.
Or is it?
When this application is run however, there is a validation error
thrown by CDI with the message shown in Listing 4-27.
137
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-27. CDI validation error of the producer method
WELD-001435: Normal scoped bean class dev.langchain4j.model.
openai.OpenAiChatModel is not proxyable because it has no
no-args constructor - Producer Method [OpenAiChatModel] with
qualifiers [@Any @Default] declared as [[BackedAnnotatedMethod]
@Produces @ApplicationScoped public com.pentacode.
ai.OpenAIFactory.produceModel()].
CDI complains of its inability to create a proxy of the
OpenAiChatModel bean because it has a no-arg constructor. Remember in
the “Why Proxies?” section, the CDI runtime uses proxies to circumvent a
number of technical challenges in application dependency management.
However, creating a proxy requires a no-arg constructor or one annotated
with @Inject. The OpenAiChatModel class does not have any of those. And
as the producer method has scoped the returned bean to
@ApplicationScoped, CDI needs to create a proxy.
The workaround to this problem is to transform the OpenAiChatModel
class into a CDI unproxyable bean. It becomes a CDI bean that can
participate in @Inject but will not have a proxy. The implication of this
is that method invocation on an instance of the bean produced from this
method will be directly on the returned instance and not on the proxy.
Listing 4-28 shows the fixed producer method.
Listing 4-28. The fixed producer method for the OpenAiChatModel
@Produces
@Singleton
public OpenAiChatModel produceModel() {
return OpenAiChatModel.builder()
.apiKey(apiKey)
.modelName(gptModel)
.temperature(temperature)
.timeout(ofSeconds(60))
138
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
.logRequests(true)
.logResponses(true)
.build();
}
The fix to the CDI validation error of unproxyable OpenAiChatModel
is the use of the @jakarta.inject.Singleton annotation. This annotation
identifies a type that the injector only instantiated once. The method, then,
produces a singleton OpenAiChatModel that is unproxyable but still a CDI
bean nonetheless. The bean can now be injected into dependents with @
Inject as shown in Listing 4-29.
Listing 4-29. The produced OpenAiChatModel being used
@ApplicationScoped
public class LangChainChatService {
@Inject
OpenAiChatModel model;
}
The LangChainChatService declares a dependency on the
OpenAiChatModel through the model field. The field is annotated with @
Inject. The produced singleton instance from the produceModel method
will be injected into this field. Every other field of this type will have the
same singleton injected into it.
Injection Point Information
Sometimes a component needs to know some information about where it
is being injected. Take the example of a logger. A logger needs to know at
least the name of the class for which it is logging information. Jakarta EE
does not come with a built-in logger that is a CDI bean out of the box. To
keep application code clean and devoid of scattered logger instantiations,
Listing 4-30 shows a producer method that produces a logger.
139
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-30. A logger producer method
public class LoggerProducer {
@Produces
public Logger getLog(final InjectionPoint injectionPoint) {
Return Logger.getLogger(injectionPoint.getMember().
getDeclaringClass().getName());
}
}
The LoggerProducer is an unscoped bean with a single method,
getLog. The method takes a jakarta.enterprise.inject.spi.InjectionPoint
parameter. All parameters of a producer method are CDI injection points.
The InjectionPoint bean provides access to metadata about an injection
point. The method uses it to get the name of the class into which any given
instance of the returned java.util.logging.Logger instance is injected. As the
method does not explicitly declare a scope for the return type, all produced
instances will be in the @Dependent pseudo-scope.
The CDI producer mechanism is a powerful way of instantiating,
customizing, and converting non-CDI beans to managed beans. However,
for some components that do not require any initialization or complex
setup, a producer field is easier and straightforward.
Producer Fields
Producer fields serve as an alternative mechanism for creating injectable
beans in CDI. Like producer methods, they act as factories for CDI beans,
but with a more concise syntax. A producer field creates beans directly
from a field declaration in another bean, making it particularly useful for
simple cases where no complex initialization logic is required.
140
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The main difference between producer fields and producer methods
lies in their initialization timing and complexity. While producer methods
can contain sophisticated logic for creating and configuring objects,
producer fields provide their values immediately upon injection. This
makes producer fields ideal for straightforward value exposures, especially
when dealing with types that can be instantiated in a straightforward
way. Listing 4-31 shows a producer field for the jakarta.persistence.
EntityManager interface.
Listing 4-31. EntityManager producer field
@Produces
@PersistenceContext
EntityManager entityManager;
This field is a producer field that will be called to fulfil any injection
point of type EntityManager. The @PersistenceContext is the standard way
of injecting Jakarta Persistence (JPA) managed EntityManager instances in
an application. Rather than duplicate the same construct everywhere, the
producer field in Listing 4-31 centralizes the production of EntityManager
instances. Not explicitly annotating the field with any scope places it
in the @Dependent pseudo-scope. With this field in place, rather than
dependent beans instantiating the EntityManager on their own, they can
request for it from CDI with @Inject as shown in Listing 4-32.
Listing 4-32. Injecting the EntityManager
@Stateless
public class DBService {
@Inject
EntityManager entityManager;
}
141
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The DBService class declares a dependency on the EntityManager
through the entityManager injection field. CDI will invoke the field
producer in Listing 4-31 for the instance to inject into the field. Clean
and simple.
Producer methods and fields are two mechanisms for transforming
arbitrary Java types to CDI beans. They can, however, be further enhanced
to be even more powerful through qualifiers.
Qualifying Producers
Qualifiers, as defined earlier in this chapter, are a way to label beans for
targeted injection by the Jakarta CDI container. Producer methods and
fields also support CDI qualifiers. Qualified producer methods and fields
will only be invoked when an injection point has the same bean type of the
producer method or field and matching set of qualifiers. Listing 4-33 shows
two qualifiers for GPT-4 and GPT-3.5 OpenAI models.
Listing 4-33. GPT-4 and GPT-3.5 qualifiers
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Gpt4 {}
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Gpt35Turbo {}
The objective of the qualifiers in Listing 4-33 is to allow a client
to select which model to be injected. With the qualifiers defined,
the OpenAiChatModel producer in Listing 4-28 can be expanded to
accommodate the qualifiers. This is done in Listing 4-34.
142
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-34. Qualified OpenAiChatModel producer methods
@Produces
@Singleton
@Gpt4
public OpenAiChatModel produceModelGpt4Model() {
return builder().modelName(OpenAiChatModelName.GPT_4_O).
build();
}
@Produces
@Singleton
@Gpt35Turbo
public OpenAiChatModel produceGpt35Model() {
return builder().modelName(OpenAiChatModelName.GPT_3_5_TURBO).
build();
}
private OpenAiChatModel.OpenAiChatModelBuilder builder() {
return OpenAiChatModel.builder()
.apiKey(apiKey)
.temperature(temperature)
.timeout(ofSeconds(60))
.logRequests(true)
.logResponses(true);
}
The producer methods are qualified with the respective models they
produce. A client can declare a dependency on the cheaper GPT-3.5-turbo
model through the @Gpt35Turbo qualifier as shown in Listing 4-35.
143
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-35. GPT-3.5-turbo dependency declaration
@Inject
@Gpt35Turbo
OpenAiChatModel gpt35TurboModel;
The CDI container will correctly call the produceGpt35Model method
for an instance to satisfy the gpt35TurboModel field. While qualified
producers offer flexible dependency injection options, as shown in our
OpenAI model example, they come with specific restrictions and rules that
must be followed to ensure proper CDI functionality. Let’s examine these
important limitations.
CDI Producers: Caveats
There are a few things you need to be aware of when using CDI producers.
The following will result in CDI definition errors at application boot time.
No @Inject on Producers
The prohibition against using @Inject on producer methods or fields
stems from the fundamental role of producers in CDI. Producers serve as
sources of objects for injection, not as injection targets themselves. This
distinction is for maintaining clear dependency chains and preventing
circular dependencies. While producers cannot be annotated with @
Inject, they can still access dependencies through constructor injection or
field injection in their containing bean class.
Producer Parameter Annotation Restrictions
@Observes and @ObservesAsync annotations are prohibited on producer
method parameters because event observation and object production
serve distinct purposes in CDI. Event observation handles system events
and triggers responses, while producers create objects for injection.
144
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Combining these responsibilities would create ambiguity about execution
order and make the system’s behavior less predictable. All producer
method parameters must be CDI beans that the container can inject.
Interceptor Producer Prohibition
Interceptors in CDI are designed to handle cross-cutting concerns by
intercepting business logic execution. Their role is fundamentally different
from producers, which create objects for injection. The prohibition against
producers in interceptors maintains a clear separation of concerns—
interceptors focus on modifying or enhancing behavior, while producers
focus on object creation and lifecycle management. This separation
improves code maintainability by keeping interceptor logic focused on its
primary responsibility of handling cross-cutting concerns. When object
creation is needed in conjunction with interception, it should be handled
by separate producer beans, maintaining a clean architectural separation.
These restrictions are aimed at creating more maintainable
and understandable applications by enforcing clear separations
between different CDI concerns. They encourage proper separation of
responsibilities between components and help prevent architectural
antipatterns that could lead to complex, difficult-to-maintain systems.
With these CDI producer restrictions in mind, let’s explore
stereotypes—a powerful feature that helps reduce annotation complexity
and enforce consistent behavior across multiple components.
Stereotypes
In enterprise applications, multiple beans often require the same set of
annotations and metadata configurations. For example, many service
components might share common annotations like @ApplicationScoped,
@Transactional, and @Logged. Manually applying these annotations
to each bean becomes repetitive and difficult to maintain, especially
145
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
when new cross-cutting requirements come up. Stereotypes solve this
problem by grouping commonly used annotations into a single, reusable
annotation.
For instance, Listings 4-36 and 4-37 show the WalletService and
UserService beans with their CDI metadata.
Listing 4-36. The WalletService bean with its metadata
@RequestScoped
@Transactional
public class SimpleWalletService {
}
Listing 4-37. The UserService bean with its metadata
@RequestScoped
@Transactional
public class SimpleUserService {
}
Listings 4-36 and 4-37 show two CDI beans that have identical
metadata requirements—both are request-scoped and transactional.
While these beans perform different business functions, they need the
same CDI services. Adding new cross-cutting concerns (like interceptors,
which we’ll cover in the next section) would require duplicating these
annotations across both beans.
To eliminate this repetition, CDI provides stereotypes—a mechanism
for bundling commonly used annotations into a single, reusable
annotation. For two example beans, instead of repeating @RequestScoped
and @Transactional, we can create an @Action stereotype that
encapsulates both annotations, as shown in Listing 4-38.
146
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-38. The Action stereotype
@Stereotype
@RequestScoped
@Transactional
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Action {
}
A CDI stereotype is created by annotating a Java annotation with
@Stereotype. The @Action stereotype is declared as @RequestScoped and
@Transactional, with the @Target set to TYPE since this stereotype should
only be applied to beans, not methods, fields, or parameters. Any bean
annotated with this stereotype automatically inherits these configurations,
as if the bean were explicitly annotated with each one individually.
With the @Action stereotype defined, we can refactor our
SimpleUserService and SimpleWalletService beans to use it, as shown in
Listings 4-39 and 4-40.
Listing 4-39. The WalletService using the @Action stereotype
@Action
public class WalletService {
}
Listing 4-40. The UserService using the @Action stereotype
@Action
public class UserService {
}
147
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Both beans remain request-scoped and transactional, but this
metadata is now abstracted into the stereotype. If a need comes up to add
an interceptor to all the controller beans, we can simply associate it with
the stereotype, and all beans using the stereotype will automatically be
intercepted.
A bean can override its stereotype’s scope by explicitly declaring
its own scope—the bean’s declared scope takes precedence over the
stereotype’s scope. For example, if SimpleWalletService declares a different
scope along with the stereotype, its declared scope will override the
stereotype’s @RequestScoped setting.
Stereotypes have some important restrictions: they cannot be
associated with qualifiers except for the built-in @Named qualifier.
Attempting to use any other qualifier with a stereotype results in a CDI
definition error. However, stereotypes can be associated with other
stereotypes, in which case the second stereotype inherits all metadata
from the first.
With stereotypes providing a way to group and manage bean metadata,
let’s examine how CDI handles the lifecycle of these beans through
callback methods. These callbacks give you control over critical moments
in a bean’s existence.
Lifecycle Callbacks
While CDI manages the complete lifecycle of contextual bean instances,
there are times when you need to execute custom logic during critical
moments in a bean’s life—specifically after creation or before destruction.
CDI provides lifecycle callbacks that the container automatically invokes at
these crucial points.
148
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
@PostConstruct
The @PostConstruct annotation allows you to perform initialization work
immediately after a bean is instantiated. When you annotate a method with
@PostConstruct, the container will invoke it after the bean is created and all
its dependencies are initialized, but before the bean is put into service.
The method must follow these rules:
•
Must return void
•
Cannot take parameters (except for interceptors)
•
Can have any access modifier (public, private, or
package-private)
•
Must not be static
Listing 4-41. A @PostConstruct callback in the
SecurityManager bean
@ApplicationScoped
@Singleton
@Startup
public class SecurityManager {
@Inject
UserService userService;
@Inject
UserSession userSession;
@PostConstruct
private void init() {
// Do prep work.
}
}
149
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
In this example, the container calls init() only after both userService
and userSession are fully initialized. Since SecurityManager is applicationscoped, the init() method is called exactly once—when the first proxy
method is delegated to the singleton instance.
@PreDestroy
The @PreDestroy annotation serves as the counterpart to @PostConstruct.
The container invokes a @PreDestroy-annotated method just before
destroying the bean instance. This callback is typically used to clean up
resources, such as closing file handles or database connections that the
bean may have acquired during its lifetime.
@PreDestroy methods must follow the same rules as @PostConstruct
methods:
•
Must return void.
•
No parameters (except for interceptors).
•
Any access modifier is allowed.
•
Cannot be static.
Having explored how to control bean initialization and cleanup
through lifecycle callbacks, let’s examine CDI interceptors—a mechanism
for implementing cross-cutting concerns like logging, security, and
transaction management across your application’s beans.
Jakarta CDI Interceptors
In enterprise applications, certain functionalities like logging, security
checks, or performance monitoring often need to be applied across
multiple components. These cross-cutting concerns aren’t part of the core
business logic but are essential for the application’s operation.
150
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Consider logging—implementing detailed logging in every method
quickly becomes repetitive and clutters the business logic. The same
logging code, perhaps varying only in method names, gets duplicated
across multiple beans. This approach is neither maintainable nor elegant.
Aspect-Oriented Programming (AOP) addresses this challenge by
allowing the separation of these cross-cutting concerns into reusable
components that can be applied declaratively. CDI implements AOP
through interceptors, building upon the Jakarta Interceptors specification.
You’ve already encountered an interceptor with the @Transactional
annotation in the @Action stereotype (Listing 4-38). This built-in JTA
interceptor manages transaction boundaries for annotated beans and
methods.
Implementing a CDI interceptor requires two components:
1. An interceptor binding annotation that clients will
use to mark methods or beans for interception
2. An interceptor class that implements the actual
cross-cutting behavior
The Interceptor Annotation
An interceptor binding annotation declaration is shown in Listing 4-42.
Listing 4-42. The logging interceptor binding annotation
@Inherited
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@InterceptorBinding
public @interface Logged {
}
151
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The @Logged annotation marks methods for logging. It’s a standard
Java annotation with the @InterceptorBinding annotation from Jakarta
Interceptors.
It needs an implementing bean that will carry out the task to be
performed by the interceptor. This bean is defined in Listing 4-43.
The Interceptor Bean
The LoggingBean class performs the actual logging. It’s annotated with
@Interceptor and @Logged to link it with the annotation. The @Priority
annotation ensures this interceptor is invoked with the correct precedence
(APPLICATION priority).
Listing 4-43. The LoggingBean interceptor class
@Interceptor
@Logged
@Priority(Interceptor.Priority.APPLICATION)
public class LoggingBean {
@Inject
Logger logger;
@AroundInvoke
public Object log(final InvocationContext invocationContext)
throws Exception {
logger.log(Level.FINE,
() -> String.format("Method %s invoked at
%s",
invocationContext.getMethod().getName(),
LocalDateTime.now(ZoneOffset.UTC)));
return invocationContext.proceed();
}
}
152
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The LoggingBean interceptor class is annotated @Interceptor and
@Logged. These two annotations make this class an interceptor bean
and link the @Logged annotation with it, respectively. Whenever the
@Logged annotation is used anywhere, the actual work to be done during
interception will be done by a method in the LoggingBean class. It is also
annotated with @Priority(Interceptor.Priority.APPLICATION). This is how
interceptors are activated and ordered in Jakarta EE. The @Priority takes
an int value; the lower the int value, the higher priority the annotation has.
The Interceptor.Priority.APPLICATION is a constant for the int value
of 2000. If another interceptor sets its @Priority value to a lower int, that
interceptor will take precedence in terms of invocation sequence over the
@Logged interceptor. In the past, interceptors needed to be registered in
an XML config file. But that changed in Java EE 7. The @Priority annotation
is the preferred way to activate and order interceptors.
The LoggingBean injects the Logger class the log method, which takes
a single parameter—InvocationContext. This parameter will be injected by
the CDI container when it invokes the method to carry out an interception.
The InvocationContext bean provides contextual information about the
intercepted invocation and also has methods to control the behavior of the
invocation chain. For the log, the InvocationContext#getMethod#getName
method is called to get the name of the method being intercepted.
The @AroundInvoke annotation tells the container at what point the
interceptor should be put to work. @AroundInvoke, as the name implies,
means that the interceptor should be dispatched just before an annotated
method is invoked. So just before any method annotated with @Logged
is invoked by the container, the log method will be automatically invoked
to carry out the function of the interception. The method can invoke any
service that the target method it is interposing on can invoke.
Another annotation that can be used to intercept beans is
@AroundConstruct. This annotation will cause the container to invoke
the annotated method just before the construct method of a target bean is
invoked. Generally you would want to be careful with @AroundConstruct
153
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
because the InvocationContext bean passed to the interceptor method
has access to all the parameters of the constructor. So you should exercise
caution when using it.
A method annotated @AroundInvoke must return an Object. As
shown in Listing 4-43, the log method returns Object from calling the
InvocationContext#proceed() method. This call signals to the container
that this method is done and execution should proceed to the next
interceptor in the chain, if any, or else proceed to call the target method.
An @AroundConstruct-annotated method returning an Object will cause
execution to move to the next interceptor in the chain or else proceed to
instantiate the interposed bean.
With the interceptor declared, it can be used by annotating classes or
methods with it. Listing 4-44 shows the @Logged interceptor applied to the
WalletService.
Listing 4-44. The @Logged annotation applied to WalletService
@Action
@Logged
public class WalletService {
}
Listing 4-44 shows the @Logged interceptor applied to WalletService.
Similarly, Listing 4-45 shows the @Logged annotation applied to the
UserService.
Listing 4-45. The @Logged interceptor applied to the UserService
@Action
@Logged
public class UserService {
}
154
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-45 shows the @Logged interceptor applied to the
UserService. Because the interceptor is applied to the beans at the class
level, all methods invoked on either class instances will be intercepted.
The @Logged interceptor can also be selectively annotated to methods
in the classes since the @Target of the @Logged interceptor is both TYPE
and METHOD.
Using Stereotypes with Interceptors
You may have noticed that both intercepted beans have the exact same
set of annotations: one a stereotype and the other an interceptor. As
discussed in the “Stereotypes” section, their whole point is to abstract away
common metadata and patterns into a single annotation. Therefore, the
@Logged interceptor can be added to the @Action stereotype. This way,
the interceptor automatically gets applied to all beans that are annotated
with the stereotype. The interceptor can still be used separately. Listing 4-46
shows the @Logged interceptor annotation added to the @Action
stereotype.
Listing 4-46. The @Action annotation being associated
with @Logged
@Stereotype
@RequestScoped
@Transactional
@Logged
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Action {
}
155
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-46 shows the @Action stereotype annotated with the
@Logged interceptor. This now associates the interceptor with the
stereotype such that any bean that is annotated with the stereotype is also
automatically intercepted. Consequently, the @Logged annotation can
be removed from the WalletService and UserService beans. Interceptors
are a straightforward way of implementing cross-cutting concerns in an
application. However, to extend or to override a bean method, CDI has
another construct that can be used for that.
CDI Decorators
CDI decorators follow the decorator design pattern, allowing you to modify
or enhance the behavior of individual beans. Unlike interceptors (which
handle cross-cutting concerns across multiple beans), decorators are
specifically tied to individual beans and can alter their business methods.
Think of a decorator as a wrapper that goes around an existing component
(called a bean) in your application. This wrapper can modify how the
original component works without changing its source code. It’s similar to
how you might wrap a gift—the original item stays the same, but you can
add layers around it that change its appearance or protection.
Why Decorators?
Decorators serve a different purpose than interceptors:
156
•
Interceptors are like security checkpoints that handle
common tasks across many components (like logging
or security checks).
•
Decorators are like specialized modifications for
specific components, changing how their business
logic works.
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
For example, you might use a decorator when you need to
•
Modify how a third-party component works without
changing its code.
•
Add new business requirements to existing
components.
•
Implement region-specific behavior for certain
operations.
Let’s walk through a practical example of using a decorator to handle
EU data privacy requirements, starting with the basic contract in the form
of the UserService interface in Listing 4-47.
Listing 4-47. The UserService interface
public interface UserService {
UserResponse createUser(final CreateUserRequest
createUserRequest);
UserResponse getUser(final Long id);
}
The UserService interface has two methods—createUser and getUser.
This interface is implemented by the SimpleUserService.
Listing 4-48. The SimpleUserService implementation of the
UserService interface
@Action
public class SimpleUserService implements UserService {
@Inject
UserRepository userRepository;
157
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
@Override
public UserResponse createUser(final CreateUserRequest
createUserRequest) {
User user = fromUserWrapper(createUserRequest);
user = userRepository.save(user);
UserResponse userResponse = getUser(user.getId());
return userResponse;
}
@Override
public UserResponse getUser(final Long userId) {
final User user = userRepository.findById(userId);
return toUserResponse(user);
}
}
Right to this point, there is nothing special about the
SimpleUserService. Now create a decorator that adds special handling for
EU users.
Listing 4-49. The UserServiceDecorator
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class UserServiceDecorator implements
UserService {
@PersistenceContext(unitName = "jwallet-postgres-eu")
private EntityManager entityManager;
@Inject
@Delegate
private UserService userService;
158
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
@Override
public UserResponse createUser(final CreateUserRequest
createUserRequest) {
// Check if the user is from the EU
if (request.getUserRegion() == UserRegion.EU) {
// Special handling for EU users
User user = UserService.fromUserWrapper(request);
entityManager.persist(user);
return getUser(user.getId());
}
// Normal handling for non-EU users
return userService.createUser(request);
}
}
The UserServiceDecorator class is marked with two annotations:
@Decorator, which identifies it as a decorator class, and @Priority, which
determines its position in the decorator chain. The class is declared as
abstract because it selectively implements methods from the UserService
interface, focusing specifically on the createUser method.
The decorator relies on two dependencies. First, an EntityManager that
uses a data source that connects to an EU-based Postgres instance. This
handles data storage specifically for EU users. Second is the UserService
itself, marked with the @Delegate annotation. This delegate injection
is important as it identifies the bean being decorated and enables the
decorator to invoke the original service’s methods when needed.
In terms of business logic, the decorator implements special handling
for EU users. When the createUser method is called, it first checks if the
user is in the EU region. For EU users, it stores data using the injected
EntityManager, ensuring compliance with regional requirements. For
non-EU users, it simply delegates to the original UserService
implementation, maintaining standard behavior.
159
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
The decorator pattern comes in handy when you need to add
functionality to existing beans without modifying their code, implement
region-specific requirements, or extend third-party components through
CDI beans. However, decorators must operate within certain constraints.
Most notably, they can only use the @Dependent pseudo-scope—
attempting to use any other scope will result in startup errors.
While decorators help modify bean behavior, sometimes there is the
need for components to communicate with each other more loosely.
This is where CDI events come in, offering a powerful mechanism for
decoupled communication between beans.
Jakarta CDI Events
The CDI event mechanism is a way to allow application components to
emit events of any type and have one or more event observers or listeners
of those events notified in a type-safe, completely decoupled way. There
is no compile-time dependency between the source of the event and any
observers or listeners. The publisher-subscriber paradigm of the observer
design pattern is at the core of CDI events, which comprises two parts—the
event object and event observers.
The Event Object
The event object is the payload of the event to be fired. Think of the
payload as the data that will be passed to listeners of the event. It can be
any valid Java type. In the sample code, we want to send an SMS to users
who successfully sign up to the application. This requirement could be
hardcoded into the SimpleUserService bean. However, that would mean
getting tied to a single implementation of the process of sending an SMS.
160
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
A much cleaner way would be to fire an event of the type of user
representation in the application. This way, the SMS implementation
will be fully decoupled from the process of persisting users in the system.
Message sending implementations can be added and removed at any
time without breaking or refactoring the SimpleUserService bean. Other
messaging options like email could also be added, all as event listeners, or
observers, still completely decoupled from the event source.
To achieve this, an event object needs to be defined first. This object
will be passed to observers as the payload when the event is fired. The
CDI container will map event observers to fired events based on the type
of payload that the observers are observing or listening for. Listing 4-50
shows the Event interface with a payload in the UserServiceDecorator.
Listing 4-50. An injection of the Event object in the
UserServiceDecorator
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class UserServiceDecorator implements
UserService {
@Inject
Event<UserResponse> userResponseEvent;
}
Listing 4-50 shows the UserServiceDecorator with a new injection
point—Event<UserResponse>. The entry point to the CDI event
mechanism is the Event<T> interface. This interface takes a type, which
will be the event payload. It has methods to fire different types of events.
You inject an instance of the Event interface, passing in a payload type.
This type is called the event type and will be used in resolving which
observers are interested in this event. Listing 4-51 shows the use of the
injected Event object.
161
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-51. The actual process of firing the UserResponse event
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class UserServiceDecorator implements
UserService {
@Inject
Event<UserResponse> userResponseEvent;
@PersistenceContext(unitName = "jwallet-postgres-eu")
private EntityManager entityManager;
@Inject
@Delegate
private UserService userService;
@Override
public UserResponse createUser(final CreateUserRequest
createUserRequest) {
// Check if the user is from the EU
if (request.getUserRegion() == UserRegion.EU) {
// Special handling for EU users
User user = UserService.fromUserWrapper(request);
entityManager.persist(user);
userResponseEvent.fire(userResponse);
return getUser(user.getId());
}
// Normal handling for non-EU users
return userService.createUser(request);
}
}
162
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-51 shows the amended createUser method in the
UserServiceDecorator bean. The method, after persisting the User object
into the database, calls the fire method on the injected event object,
passing in the newly persisted User through the UserResponse object.
This passed UserResponse object will be the payload of the fired event.
Firing an event is as simple as calling the fire method, passing in the type
of the Event interface. This simple call will cause an event to be fired that
any component can subscribe to, or observe. The UserResponse instance
passed to the fire method of the Event bean will be passed to all event
observers of the UserResponse type.
The Event Observer
The second part of the CDI event mechanism is the event observer. The
observer is a subscriber to a particular event. The observers are paired
to events by the container based on the types they observe. An observer
that wants to be notified of the UserResponse event will have to observe a
UserResponse event. Listing 4-52 shows the UserResponse event observer
in the MessageCenter bean.
Listing 4-52. The UserResponse event observer as the
MessageCenter bean
public class MessageCenter {
public void sendUserSms(@Observes UserResponse
userResponse) {
//TODO --> Send SMS through gateway... Blocking task
}
}
163
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-52 shows the MessageCenter bean with a sendUserSms
method. This method takes a single parameter of type UserResponse. This
parameter determines the type of events that this observer will be notified
of. The parameter is annotated with the @Observes annotation, telling the
CDI runtime that this method observes events of the annotated type.
When the UserResponse event is fired in the UserServiceDecorator
bean, this method will be automatically called by the container and
passed the UserResponse instance that was passed to the fire method
of the Event interface in the UserServiceDecorator bean. Even though
there is absolutely no compile-time dependency between the bean that
fires the event and the one that observes it, at runtime, these beans will
communicate with each other through the fired event.
Asynchronous Events
The UserResponse event in Listing 4-51 is a synchronous blocking event.
When fired, the observer method will block execution until it’s completed.
As shown in Listing 4-52, execution will be blocked until the sendUserSms
returns because the event observer method will be called in the same
thread in which it was fired. However, sending an SMS most likely will
require communication with an external SMS provider, over the network.
This could take time, depending on the latency of the network. To prevent
blocking the current thread, the event mechanism supports the firing of
asynchronous events.
With async events, the observers will be invoked asynchronously,
executing in a separate thread from the one in which the event was
fired. This way, the sending of the SMS will be in a separate thread, with
execution returning immediately to the point the event was fired.
Listing 4-53 shows the firing of async events in the UserService
Decorator bean.
164
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-53. The firing of an async event
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class UserServiceDecorator implements
UserFacade {
@Inject
Event<UserResponse> userResponseEvent;
@PersistenceContext(unitName = "jwallet-postgres-eu")
private EntityManager entityManager;
@Inject
@Delegate
private UserService userService;
@Override
public UserResponse createUser(final CreateUserRequest
createUserRequest) {
// Check if the user is from the EU
if (request.getUserRegion() == UserRegion.EU) {
// Special handling for EU users
User user = UserService.fromUserWrapper(request);
entityManager.persist(user);
userResponseEvent.fireAsync(userResponse);
return getUser(user.getId());
}
// Normal handling for non-EU users
return userService.createUser(request);
}
}
165
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-53 shows the UserServiceDecorator bean with its createUser
method. This time, the event object fires an async event through the
call to the fireAsync method. This method will fire an async event that
only async observers will be notified of. It returns a java.util.concurrent.
CompletionStage object for optional further pipeline composition on the
async operation. The UserResponse observer shown in Listing 4-52 will not
be called for this event because that observer is synchronous. Listing 4-54
shows the MessageCenter bean with an async UserResponse observer.
Listing 4-54. An async UserResponse observer
public class MessageCenter {
public void sendUserSmsAsync(@ObservesAsync UserResponse
userResponse) {
//TODO --> Send SMS through gateway... Async
}
}
Listing 4-54 shows the MessageCenter bean with a new method,
sendUserSmsAsync. This method has almost the same signature as the
synchronous one in Listing 4-52, with the only difference being the
@Observes annotation replaced with @ObservesAsync. This annotation
tells the container that this method observes an async event of type
UserResponse. So when the UserResponse event shown in Listing 4-53
gets fired, the sendUserSmsAsync method will be called.
Transactional Observers
The UserResponse event discussed so far should work fine. However,
there is a problem. The requirement is to send a message to a user that
successfully gets persisted to the database. However, so far there has
been no confirmation of whether the user persistence succeeded or not.
The async event fired in Listing 4-53 is fired after calling persist on the
166
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
EntityManager instance. The problem is that up to the point the event is
fired, the transaction in which the method is being executed has still not
been committed. And until the transaction commits successfully, we can’t
be certain that the act of persisting the user has succeeded or not.
Transactional observers help get around this problem. A transactional
observer is one that specifies at which phase of a transaction it should be
invoked. With our requirement, we want the observer to be invoked only
after the transaction in which the event is fired completes successfully,
meaning the transaction was committed successfully and we are certain
the data is in the database. Listing 4-55 shows the MessageCenter bean
with a transactional observer for sending SMS.
Listing 4-55. A transactional observer
public class MessageCenter {
public void sendUserSms(@Observes(during = TransactionPhase.
AFTER_SUCCESS) UserResponse userResponse) {
//TODO --> Send SMS through gateway... Blocking task
}
}
Listing 4-55 shows the sendUserSms method of the MessageCenter
bean. This time around, the @Observes method is passed a parameter—
during = TransactionPhase.AFTER_SUCCESS. This signals to the container
that this observer should be called in the after-success phase of any
transaction in which the event was fired. Because the UserResponse was
fired in a transactional context, the sendUserSms observer is going to be
notified only after the transaction commits successfully.
You may have noted that the sendUserSms observer is observing a
synchronous event because it uses the @Observes annotation. This is
because transactional observers are not supported for async events. So the
event that is fired will be a synchronous event as shown in Listing 4-51 in
the UserServiceDecorator.
167
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
There are a number of transactional phases available for observer
methods. These are defined in the TransactionPhase enum type in the
jakarta.enterprise.event package. They are
•
IN_PROGRESS: The observer is called when the event
is fired. This is the default.
•
BEFORE_COMPLETION: The observer is called during
the before-completion phase of the transaction.
•
AFTER_COMPLETION: The observer is called during
the after-completion phase of the transaction.
•
AFTER_FAILURE: The observer is called during the
after-completion phase of the transaction, only when
the transaction fails.
•
AFTER_SUCCESS: The observer is called during the
after-completion phase of the transaction, only when
the transaction succeeds.
Qualifying Events
Events in CDI become even more powerful when combined with
qualifiers, which let you control which observers receive specific event
notifications. Consider our earlier EU user example: beyond storing EU
user data in EU-based servers, we might want to send them emails instead
of SMS notifications. Qualifiers make this kind of selective notification
possible.
To implement this requirement, we’ll create a MessageOption qualifier
that specifies the type of message to be sent as shown in Listing 4-56.
168
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-56. The new MessageOption parameter
@Qualifier
@Retention(RUNTIME)
@Target({ FIELD, TYPE, METHOD, PARAMETER })
public @interface MessageOption {
MessageType value();
enum MessageType { SMS, EMAIL }
}
Listing 4-56 shows the MessageOption qualifier. With this,
event observers can be selectively notified. This annotation can be
used in two ways. First, we could inject two Event objects into the
UserServiceDecorator, qualifying each with a separate MessageOption, as
shown in Listing 4-57.
Listing 4-57. Two qualified Event objects for each
MessageOption type
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class UserServiceDecorator implements
UserFacade {
@Inject
@MessageOption(MessageOption.MessageType.SMS)
Event<UserResponse> smsEvent;
@Inject
@MessageOption(MessageOption.MessageType.EMAIL)
Event<UserResponse> emailEvent;
}
169
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-57 shows the UserServiceDecorator bean with two Event
injection points, each qualified with a MessageOption. The corresponding
observers interested in each event will also need to be qualified.
Listing 4-58 shows two observers in the MessageCenter bean observing
these events.
Listing 4-58. The MessageCenter bean with two event observers
public class MessageCenter {
public void sendUserSmsAsync(
@ObservesAsync @MessageOption(MessageOption.
MessageType.SMS) UserResponse userResponse) {
//TODO --> Send SMS through gateway... Async
}
public void sendEmail(
@ObservesAsync @MessageOption(MessageOption.
MessageType.EMAIL) UserResponse userResponse) {
//TODO --> send email asynchronously
}
}
Each observes the same event type but differently qualified. During
observer resolution, the container will match each observer to the fired
event based on type and qualifiers. The sendUserSmsAsync observer will
be mapped to the async event fired from the smsEvent object and the
sendEmail observer mapped to the emailEvent object. This should work
as expected. However, the moment there are more MessageType options
in the MessageOption qualifier, a lot more event objects will need to be
injected.
CDI allows the dynamic selection of event qualifiers based on runtime
conditions. Let’s enhance the UserServiceDecorator to send different types
of notifications based on a user’s region.
170
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Listing 4-59. Our refactored UserServiceDecorator with dynamic
qualifier selection
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class UserServiceDecorator implements
UserFacade {
@Inject
Event<UserResponse> userResponseEvent;
@PersistenceContext(unitName = "jwallet-postgres-eu")
private EntityManager entityManager;
@Inject
@Delegate
private UserService userService;
@Override
public UserResponse createUser(CreateUserRequest
createUserRequest) {
User user = UserService.fromUserWrapper(createUser
Request);
if (createUserRequest.getUserRegion() ==
UserRegion.EU) {
// Handle EU users
entityManager.persist(user);
UserResponse userResponse =
userService.
getUser(user.getId());
userResponseEvent.select(getAnnotation
(UserRegion.EU)).fireAsync(userResponse);
return UserService.toUserResponse(user);
} else {
171
MANAGING DEPENDENCIES WITH CDI
CHAPTER 4
// Handle non-EU users
UserResponse userResponse = userService.
createUser(createUserRequest);
userResponseEvent.select(getAnnotation(UserRegion.
OTHERS)).fireAsync(userResponse);
return userResponse;
}
}
private MessageOption getAnnotation(UserRegion
userRegion) {
return new MessageOption() {
@Override
public MessageType value() {
return userRegion == UserRegion.EU
? MessageType.EMAIL
: MessageType.SMS;
}
@Override
public Class<? extends Annotation>
annotationType() {
return MessageOption.class;
}
};
}
}
In the createUser method, we determine the appropriate notification
type based on the user’s region. For EU users, we select the EMAIL
message type, while other users receive SMS notifications. The selection
172
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
happens through the getAnnotation method, which returns the
appropriate MessageOption qualifier. The Event#select method then uses
this qualifier to determine which observers should receive the event.
To handle these qualified events, Listing 4-60 reproduces the full
MessageCenter bean with all the event observers, including a catch-all
observer.
Listing 4-60. A catch-all event observer in MessageCenter
public class MessageCenter {
public void sendUserSms(
@Observes(during = TransactionPhase.AFTER_SUCCESS)
@MessageOption(MessageOption.MessageType.SMS)
UserResponse userResponse) {
// Send SMS through gateway
}
public void sendUserSmsAsync(
@ObservesAsync
@MessageOption(MessageOption.MessageType.SMS)
UserResponse userResponse) {
// Send SMS through gateway asynchronously
}
public void sendEmail(
@ObservesAsync
@MessageOption(MessageType.EMAIL)
UserResponse userResponse) {
// Send email asynchronously
}
173
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
public void sendMessage(@ObservesAsync UserResponse
userResponse) {
// Handle any UserResponse event
}
}
An important detail to understand is the behavior of the sendMessage
method in the MessageCenter in Listing 4-60. Without explicit qualifiers,
this method receives all UserResponse events, regardless of their qualifiers.
This happens because CDI implicitly applies the built-in @Any qualifier
to unqualified observers. The @Any qualifier acts as a wildcard, matching
any event of the specified type.
This default behavior can be both powerful and potentially
problematic. When you need precise control over which observers
receive specific events, you must explicitly qualify your observer methods.
Otherwise, you might find your catch-all observers processing events
they weren’t intended to handle. Keeping this subtle aspect of qualifier
behavior in mind helps prevent unexpected event processing in your
application.
While qualifiers help control event routing, sometimes there is a
need for additional information about the event itself. This is where event
metadata comes in, providing rich contextual information about events as
they flow through an application.
Event Metadata
When working with events, you might need access to additional
information about the event being fired. CDI provides this capability
through the EventMetadata interface. While the previous observer
methods took a single parameter representing the event payload,
observer methods can accept additional parameters that the container
174
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
will automatically resolve. Consider the refactored version of the
MessageCenter’s SMS observer shown in Listing 4-61.
Listing 4-61. The passing of a second parameter to an
observer method
public class MessageCenter {
public void sendUserSms(@Observes(during = TransactionPhase.
AFTER_SUCCESS)
@MessageOption(MessageOption.
MessageType.SMS) UserResponse userResponse, EventMetadata
eventMetadata) {
//TODO --> Send SMS through gateway... Blocking task
}
}
Listing 4-61 shows the injection of the EventMetadata bean as the
second parameter to the sendUserSms synchronous observer method. The
EventMetadata parameter, automatically provided by the CDI runtime,
provides information about the event: its qualifiers, the injection point
bean, and the type of the event object. This additional context enables
more sophisticated decision-making within observer methods. Beyond
examining event details through metadata, CDI also lets us control when
observers are notified through conditional observation.
Conditional Observer Methods
Beyond metadata, CDI also allows us to control when observer methods
should be invoked through conditional observation. By default, when
an event is fired, CDI creates a new instance of the bean containing the
observer method if one doesn’t already exist. However, we can modify this
behavior to only invoke observers when their containing bean is already
present in the current scope.
175
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
To implement conditional observation, we first need to give an explicit
scope to the bean containing the observers. To conditionally ask that the
sendUserSms synchronous observer be called only if an instance of the
MessageCenter bean exists, pass in a second parameter to the @Observes
annotation as shown in Listing 4-62.
Listing 4-62. The sendUserSms set to conditional
@RequestScoped
public class MessageCenter {
public void sendUserSms(@Observes(during = TransactionPhase.
AFTER_SUCCESS, notifyObserver = Reception.IF_EXISTS)
@MessageOption(MessageOption.MessageType.SMS)
final UserResponse userResponse, final
EventMetadata eventMetadata) {
//TODO --> Send SMS through gateway... Blocking task
}
}
Listing 4-62 shows the MessageCenter bean, this time around with
its scope set to @RequestScoped. The sendUserSms observer passes the
notifyObserver parameter value of Reception.IF_EXISTS to the @Observes
annotation. With this construct, this observer will only be called for any
fired synchronous UserResponse event if an instance of the MessageCenter
bean exists within the current request scope. In the absence of an instance
of the bean, the observer will not be called.
The notifyObserver takes either of the two options—Reception.
IF_EXISTS or Reception.ALWAYS. The default is Reception.ALWAYS. So,
by default, an observer method will always be called for the event it is
observing unless explicitly turned off.
176
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
Summary
This chapter explored Jakarta Contexts and Dependency Injection (CDI),
a core specification that simplifies dependency management in Jakarta
EE applications. CDI implements the Inversion of Control pattern, where
a container manages object creation, lifecycle, and dependencies rather
than individual components managing these aspects themselves.
The chapter showed how CDI helps build maintainable enterprise
applications through its key features: bean management, scopes,
qualifiers, producers, events, interceptors, and decorators. It explored how
these features work together to create loosely coupled systems that can
adapt to changing requirements.
Through practical examples, the chapter illustrated how to use CDI
to handle common enterprise scenarios like transaction management,
logging, and messaging. It emphasized CDI’s role in separating business
logic from technical concerns, making applications easier to maintain
and test.
Key Takeaways
1. CDI beans form the foundation of enterprise
applications, with the container managing their
lifecycle from creation to destruction. The container
automatically handles dependency injection and
provides different scopes to control how long
beans live.
2. The specification provides type-safe dependency
injection through qualifiers, enabling precise
control over which implementation to use
when multiple options exist. This creates clear,
maintainable code that’s easy to test and modify.
177
CHAPTER 4
MANAGING DEPENDENCIES WITH CDI
3. Cross-cutting concerns like logging, security, and
transactions can be handled through interceptors
and decorators, keeping the main business logic
clean and focused. Stereotypes help reduce
annotation complexity by grouping common
metadata.
4. The event system enables loose coupling between
components through type-safe communication.
It supports both synchronous and asynchronous
operations, with special handling for
transactional events.
5. CDI’s producer methods and fields allow integration
of external classes into the CDI ecosystem, making
them available for dependency injection without
modifying their source code.
While CDI provides the foundation for managing dependencies
and component lifecycle, enterprise applications need data persistence
capabilities to store and retrieve information. The next chapter explores
Jakarta Data, a modern specification that simplifies database operations
through type-safe queries and intuitive mapping between Java objects
and database tables. We’ll see how Jakarta Data works with CDI to create
efficient, maintainable data access layers in enterprise Java applications.
178
CHAPTER 5
Persistence
with Jakarta EE
Persistence
Every application needs to store data during its execution in a durable
data store. This store could be as simple as a flat file or as complex as a
full-fledged database management system. The data store acts as the
single source of truth for the application. For instance, your bank account
balance is stored in some form of data store—this single data point is
the only source of truth for the bank regarding how much money they’re
keeping for you.
In enterprise Java, data persistence typically spans three broad
categories: data modeling, data persistence, and data retrieval. Jakarta EE
provides several specifications to address these needs, primarily Jakarta
Persistence (JPA), Jakarta NoSQL (a standalone specification), and the
newer Jakarta Data.
This chapter explores the persistence options available in Jakarta EE,
focusing on
•
Jakarta Persistence (JPA) for relational database access
•
Jakarta NoSQL for non-relational database access
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_5
179
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
•
The new Jakarta Data specification for simplified,
unified data access
•
Repository patterns and how they enhance productivity
•
Guidelines for choosing the right persistence approach
Jakarta Persistence (JPA)
The Jakarta Persistence API, popularly known as JPA, is the Jakarta
EE specification that defines how applications can model, store into,
and retrieve data from relational databases. JPA makes heavy use of
annotations to prevent your Java artifacts from having to extend or
implement interfaces from the API. JPA helps you solve the objectrelational impedance mismatch by giving you the constructs to map plain
Java classes to relational database tables.
As a Java developer, you are very familiar with object-oriented
programming and design. However, this paradigm does not translate very
well when it comes to database management. The JPA API allows you to
model and query your data in a familiar Java context without having to dive
deep into the technical aspect of relational database management systems.
It also abstracts from the underlying database, leaving the handling of the
different databases to the runtime. Except in very advanced cases, you
as a developer will not have to know much about the database that the
application uses.
It is important to note that JPA does not replace SQL or database
systems knowledge. What JPA does is to make it easy for Java developers to
be able to model, persist, and query data in a much more “Java way” than
otherwise. That notwithstanding, some knowledge of SQL is required to be
able to make full use of the JPA API.
180
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
All the examples in this chapter use the Postgres database as the
underlying database. However, the same principles should apply to
all database engines out there as long as you use the JPA constructs.
By the end of this chapter, you should be comfortable in using the JPA
specification to persist your application data to a relational database.
The JPA Runtime
Throughout this chapter, there will be references to the JPA runtime.
The runtime is the actual implementation of the Jakarta Persistence
specification that carries out your JPA “instructions” issued through the
various API constructs. It translates the high-level JPA constructs to lowlevel, database-specific schemas and queries. As discussed in the early
chapters, Jakarta EE is made up of individual specifications, with each
specification having different implementations. The JPA specification also
has implementations that ship with the different Jakarta EE containers.
Some of the popular implementations are Hibernate and EclipseLink.
Data Modeling
The modeling aspect of JPA is handled almost entirely by annotations
found in the jakarta.persistence package. These annotations
transform POJOs into JPA entities that can be modeled based on their
interrelationships and hierarchies and subsequently mapped to relational
database tables. For instance, one entity might extend another, contain a
list of another type, and itself be contained in a collection in yet another
class. All these can be mapped to relational database entity relations using
the annotations found in the jakarta.persistence package.
181
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Data Persistence
The central artifact for persisting, updating, and querying data in JPA is
the EntityManager interface. This interface has all the methods needed to
get data into the database, update, and query the data. As is the norm on
the Jakarta EE platform, the underlying JPA specification implementation
provides an implementation for the EntityManager interface at runtime.
Querying
Querying data is equally as important as persisting the data. JPA has two
APIs for querying data, namely, the Java Persistence Query Language and
the Criteria API. These two constructs allow you to write queries that are
known ahead of time and much more dynamic, search-type queries that
come up at runtime. The EntityManager interface has methods for creating
queries using these two API constructs.
With the Jakarta Persistence API, you can create applications with
complex data hierarchies and relationships, mapped to relational
databases all through the much familiar Java language. This makes using
the JPA API a critical toolset in the toolbox of every Jakarta EE developer.
The rest of this chapter discusses the trio itemized above.
Data Modeling with JPA
The Simplest Unit
The simplest unit of a JPA artifact is a plain old Java object, or POJO.
Listing 5-1 shows a User POJO that will be transformed into an entity.
182
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-1. The User POJO
public class User {
private String firstName;
private String lastName;
private String username;
}
Listing 5-1 shows a very basic User Java class. To map this class to a
relational database table, such that each field is mapped to a table column,
we need to transform it into a JPA entity. The primary annotation for
transforming a Java class to a JPA entity is the @Entity annotation. Listing 5-2
shows the User class now transformed into a JPA entity.
Listing 5-2. The User entity
@Entity
public class User {
private String firstName;
private String lastName;
private String username;
}
Listing 5-2 shows the User entity. With this, the User class is now a JPA
entity that will be mapped to a database table. The name of the database
table to which this class will be mapped is by default the name of the
entity class, in this case User. To customize the table name, the @Table
annotation can be used as shown in Listing 5-3.
183
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-3. The User entity with a customized table name
@Entity
@Table(name = "WALLET_USER")
public class User {
private String firstName;
private String lastName;
private String username;
}
Listing 5-3 shows the use of the @Table annotation to customize the
relational database table name to which this entity will be mapped. With
these annotations, the User class is now a JPA entity that will be mapped
to the relational database table wallet_user, with its instances mapped to
rows in the table.
Primary Key Generation
Even though the User entity shown in Listing 5-3 will be mapped to the
relational database table wallet_user, it does not have a primary key. In
relational databases, the primary key is the technical unique identifier of
each row in the table. The User entity, however, has not declared a primary
key. To fix this, Listing 5-4 shows an updated version of the User class with
a primary key field.
Listing 5-4. The updated User entity
@Entity
@Table(name = "WALLET_USER")
public class User {
184
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
private String firstName;
private String lastName;
private String username;
}
Listing 5-4 shows the User entity, now with a field of type Long
named id. This field is annotated with @Id and @GeneratedValue(strat
egy=GenerationType.AUTO). The @Id annotation tells the runtime that
the primary key of the User table should be mapped to this field. The
allowed field types for the @Id annotation are Java primitive types or their
corresponding wrappers, String, java.util.Date, java.sql.Date, java.math.
BigDecimal, and java.math.BigInteger. The runtime takes care of mapping
the annotated field to the requisite, corresponding type of the underlying
database used.
ID Generation
The second annotation on the id field is the @GeneratedValue annotation.
This annotation is used to tell the runtime how the primary key values
should be generated through the strategy parameter. The strategy
parameter is of type GenerationType and defaults to AUTO. The possible
values for the GenerationType are TABLE, SEQUENCE, IDENTITY, and
AUTO. With a default of AUTO, the User entity shown in Listing 5-4 can be
simplified to what is shown in Listing 5-5.
185
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-5. A simplified ID generation for the User entity
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@GeneratedValue
protected Long id;
private String firstName;
private String lastName;
private String username;
}
Listing 5-5 shows the primary key generation set to AUTO, the default
for the @GeneratedValue annotation. Listing 5-6 declares the resulting
database schema diagram for the User entity shown in Figure 5-1.
Figure 5-1. Wallet entity schema
186
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-6. The corresponding data definition language (DDL) for
the entity
create table wallet_user
(
id
bigint not null primary key,
firstname varchar(255),
lastname varchar(255),
username varchar(255)
);
AUTO
The AUTO primary key generation strategy delegates the decision of how
primary keys should be generated to the underlying runtime. What this
implies is that the application is asking the JPA runtime to select the best
primary key generation strategy based on the field type and underlying
database engine used.
In cases where the primary key is only used as a technical database
unique row identifier, then the AUTO strategy should suffice. It also is an
ideal choice for development and quick prototyping. AUTO also works
best when schema generation is done by the runtime (we talk about
schema generation later in the chapter). AUTO will work only for integral
field types.
TABLE
The TABLE generation strategy is the most flexible and extensible
generation strategy. Listing 5-7 shows the User entity using the TABLE
generation strategy for the primary key generation.
187
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-7. The User entity using TABLE primary key generation
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
protected Long id;
private String firstName;
private String lastName;
private String username;
}
Listing 5-7 shows the User entity with the TABLE primary key
generation strategy. As is, the runtime will take care of creating the ID table
(if schema generation is used). In the absence of schema generation by the
runtime, the declared ID table should exist before the application starts.
The ID table is a table with two fields—a string and an integral type.
The first column is the primary identifier for all generators in the table.
The second integral column stores the actual ID sequence being
generated. A much more elaborate example of TABLE generation is shown
in Listing 5-8 where we explicitly define the ID generation table through
the @TableGenerator annotation.
Listing 5-8. The User entity with explicit table generation
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@TableGenerator(name = "ID_Gen",
188
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
table = "ID_GEN_TABLE",
pkColumnName = "GENERATOR_NAME",
pkColumnValue = "GENERATED_VALUE",
valueColumnName = "GEN_VAL")
@GeneratedValue(strategy = GenerationType.TABLE,
generator = "ID_Gen")
protected Long id;
private String firstName;
private String lastName;
private String username;
}
Listing 5-8 shows the use of the @TableGenerator annotation to
explicitly specify the ID table generation. The first parameter of the
annotation specifies the name of the generator. This name is then passed
to the generator parameter of the @GeneratedValue annotation. The other
parameters of the @TableGenerator annotation are
•
table: This specifies the name of the database table for
this generator.
•
pkColumnName: This specifies the column name for
the unique identifier for this table.
•
pkColumnValue: This specifies the actual value of the
pkColumnName in the table.
•
valueColumnName: This specifies the column name of
the column for storing the ID sequence.
This TABLE ID generation will result in the following DB schema
shown in Listing 5-9.
189
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-9. The resulting ID generation table for the User entity
create table id_gen_table
(
generator_name varchar(50) not null primary key,
gen_val
numeric(38)
);
Figure 5-2 shows the resulting schema diagram for the ID
generation table.
H id_gen_table
IS gen_val
numeric(38)
J=| generator_name varchar(50)
Figure 5-2. ID generation table schema
At application runtime, the JPA provider (runtime, implementation)
will allocate a block of identifiers for this table. The default allocation block
is 50. The runtime will then allocate IDs from this block from memory until
it hits the size of the allocation; a request for an ID causes another round of
preallocation, which will then be used in memory for assigning IDs; and so
on. The allocation size can be customized through the @TableGenerator.
You can also set the initial value of the gen_val column, which defaults to 0
for integral types.
190
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
SEQUENCE
The SEQUENCE identity generation strategy is similar to the TABLE
strategy and is used where the underlying database supports the sequence
ID generation mechanism. Setting the strategy of the @GeneratedValue
to SEQUENCE will cause the underlying runtime to create the requisite
sequence generator on your behalf. The @SequenceGenerator can be used
to explicitly create sequences, much similar to what we discussed in the
TABLE strategy using @TableGenerator.
IDENTITY
The IDENTITY sequence-generating strategy is used when the underlying
database supports the autonumber feature. When a row is inserted into
the database, the engine automatically assigns a value to the primary key
column. IDENTITY is very much database dependent and thus isn’t used
commonly in JPA applications.
Customizing Columns
The User entity shown in Listing 5-5 will default to using the field names
as database columns. However, you can customize these columns using
the @Column annotation. This is very important when the application you
are working on will be used with an existing schema, mostly from legacy
applications. The @Column annotation can also be used to set some
constraints and properties on the column in the database. Listing 5-10
shows the User entity, with @Column used to customize some fields.
191
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-10. The use of the @Column annotation to customize
entity fields
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
}
Listing 5-10 shows an updated User entity, with @Column
customizations and constraints on some fields. The first and last names
are constrained to not be null. This means the database will enforce non­
null checks for every insertion into the wallet_user table. The username
column is set to not be nullable and to be unique. Its length is also set to 30
variable characters. The totalConversions field, which is a numeric field,
is set to a precision of 19 and a scale of 2. The updated schema diagram of
the User entity is shown in Figure 5-3.
192
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Figure 5-3. The updated User schema diagram
The corresponding DDL from the new User entity is also shown in
Listing 5-11.
Listing 5-11. The updated User entity DDL
create table if not exists wallet_user
(
id
bigint
not null primary key,
firstname
varchar(255) not null,
lastname
varchar(255) not null,
totalconversions numeric(19, 2),
username
varchar(30)
not
null unique
);
193
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Mapping Temporal Types
Mapping date types to database columns is a straightforward task using
the Java 8 java.time packages. Listing 5-12 shows the User entity with three
new java.time types.
Listing 5-12. Temporal mapping using java.time types in the
User entity
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
private LocalDateTime created;
private LocalDateTime updated;
}
194
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-12 shows three new fields in the User entity. The birthDay
field is typed to java.time.LocalDate and the created and updated fields
to java.time.LocalDateTime types. The LocalDate type will be mapped to
the SQL date type, and the LocalDateTime type to the timestamp type in
the database. The updated schema diagram of the User entity is shown in
Figure 5-4.
Figure 5-4. Updated User entity schema
195
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The much older java.util.Date and java.util.Calendar types can also
be used for temporal type fields. However, for these, the @Temporal type
annotation will need to be used to pick which JDBC java.sql types to map
the field to. The java.sql.Date, java.sql.Time, and java.sql.Timestamp can
also be used. These map directly to the respective underlying database
type without any hint to the runtime.
Mapping Large Objects
Oftentimes applications need to map byte-based objects to the database.
These objects can be large, depending on their type. Large objects,
otherwise known as LOBs, require separate JDBC calls to the database for
loading them in Java. As such, when used as field types, we need to signal
the runtime to use these special calls. The way to signal the runtime about
LOBs is through the use of the @Lob annotation on a large object field.
There are two types of large objects that can be mapped to the
database. Character large objects or CLOBs, represented in Java as char[]
or Character[] and long String objects, are mapped to the CLOB column
type in the database. Binary large objects, or BLOBs, represented in Java
by byte[], Byte[], and Serializable types, are mapped to BLOB database
columns. Listing 5-13 shows the User entity with a BLOB field for the
picture of the account holder.
Listing 5-13. The User entity with a BLOB field
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@Column(nullable = false)
196
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
private LocalDateTime created;
private LocalDateTime updated;
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
}
Listing 5-13 shows the picture field of type byte[] annotated with @Lob.
This will be mapped to the underlying database’s binary large object type.
Simple Field Types
The @Basic annotation on the picture explicitly marks the field as a basic
or simple type. All the fields in the User entity are called simple types in
JPA parlance. Simple fields are fields that can be mapped directly to a
single database column. The @Basic annotation is used to denote simple
field types. However, they can be fully omitted as has been the case with all
the fields in the User entity except for the picture field.
197
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Lazy Fetching
When a row is loaded from the table to which the User entity is mapped, all
the columns mapped to simple types are loaded. By default, simple types in
an entity are loaded or fetched when an instance is loaded from the database.
However, there are times when fetching a simple type is not very efficient.
In the case of the User entity, we really do not want to fetch a user’s
picture every time an instance is loaded. To signal the runtime to not fetch
the binary field by default, the FetchType.LAZY type is passed to the fetch
parameter of the @Basic field.
Mapping Enums
Adding an enum field type in an entity is enough to map it to a database
column. By default, the enum type will be mapped to a column of an
integral type in the database. This is because by default, JPA uses the ordinal
of the enum to map to the database. Listing 5-14 shows the User entity with
a UserType field. Figure 5-5 shows the generated schema diagram.
Listing 5-14. The User entity with an enum field
@Entity
@Table(name = "WALLET_USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
198
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
private LocalDateTime created;
private LocalDateTime updated;
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
private UserType userType;
}
Figure 5-5. The schema diagram of the User entity with the enum
field type
199
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The userType is mapped to an integer for this particular underlying
database. This means the ordinal position of the UserType value passed
to the userType field at runtime is what will persist. The problem with this
approach is that the existing ordinals could easily change with the addition
of new entries in the enum. To prevent already persisted enum fields being
mapped to the wrong enum value because of changes in the ordinals, the
@Enumerated annotation can be used to change the mapped field type to
a string. Listing 5-15 shows the userType field mapped to String.
Listing 5-15. The mapping of the enum to String
@Entity
@Table(name = "WALLET_USER")
@Getter
@Setter
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
private LocalDateTime created;
private LocalDateTime updated;
@Lob
200
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
@Enumerated(EnumType.STRING)
private UserType userType;
}
The @Enumerated annotation takes either EnumType.STRING or
EnumType.ORDINAL. The ORDINAL value is the default, and as such
when omitted as was done in Listing 5-14, the field is mapped to the
ordinal. Figure 5-6 shows the updated schema diagram.
® wallet_user
IS birthday
date
IS created
timestamp
JSfirstname
varchar(255}
■S lastname
varchar(255)
IS picture
bytea
IS totalconversions numeric(19r2}
IS updated
timestamp
IS usertype
varchar(255}
fS username
varchar(30}
!3id
bigint
Figure 5-6. Mapping an enum to String
The userType enum field is now mapped to varchar, which represents
the String type that we aim to map it to.
201
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Transient Fields
Transient fields in an entity are fields that are not mapped to a database
column. To signal the runtime that a given field should not be persistent,
the transient modifier or @Transient annotation can be used on a field
type. The modified or annotated field will not be mapped to a database
column, nor can it be queried during data retrieval. For example, the User
entity shown in Listing 5-16 has an age field with the transient modifier
that is computed at runtime. This field should not be persistent.
Listing 5-16. The use of the transient modifier
@Entity
@Table(name = "WALLET_USER")
@Getter
@Setter
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
private LocalDateTime created;
private LocalDateTime updated;
202
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
@Enumerated(EnumType.STRING)
private UserType userType;
private transient int age;
}
The age field could equally be annotated @Transient, and the effect
would be the same.
Field and Property Access
The mappings discussed so far in the User entity have all had their
respective JPA annotations on the field. What this means is that the JPA
runtime will directly access these fields at runtime. This is called field
access. The other access type is property access, where the getter method
of the fields is annotated with the JPA annotations. You will not see
much property access in the wild as much as field access. As such, all the
examples in this chapter, and the rest of the book, use field access.
Organizing withInheritance
The User entity discussed so far is the only entity we have looked at.
However, an application will seldom consist of a single entity. No matter
the number of entities, a lot of the time, there will be fields that are
common to a set of the entities. It is very tedious to repeat these fields
for each entity. In any case, the whole point of the use of an abstraction
like JPA is to use the full object-oriented feature of the Java language in a
database context.
203
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
As such, common entity fields can be abstracted into a common
super class that all other types that need such fields can inherit from. The
id, created, and updated fields of the User entity are good candidates
for abstraction into a super class. These fields naturally would be found
in other entities. To simplify the domain models, let us abstract these
and more other common fields into a super class. Listing 5-17 shows an
AbstractEntity class with some common fields.
Listing 5-17. The AbstractEntity class
@MappedSuperclass
public abstract class AbstractEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
protected LocalDateTime created;
protected LocalDateTime updated;
protected String createdBy;
protected String editedBy;
}
Listing 5-17 shows the AbstractEntity. This class is an abstract
class annotated @MappedSuperclass. It’s abstract because its sole
purpose is to be extended by other classes. We do not want to have
any concrete initialization of this class. It has five fields that all bear
the protected modifier, making them available to its subclasses.
The @MappedSuperclass annotation designates this class as one whose
mapping information is applied to entities that extend it. It will not have a
separate table of its own.
204
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The User entity can now extend the AbstractEntity, and in the
database, all the fields of the AbstractEntity class will be mapped to the
wallet_user table. Listing 5-18 shows the updated User entity.
Listing 5-18. The User entity extending AbstractEntity
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
@Enumerated(EnumType.STRING)
private UserType userType;
private transient int age;
}
The User entity now takes the common fields from the AbstractEntity it
extends. The updated database diagram of the wallet_user table is shown
in Figure 5-7.
205
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
H wallet_user
IS birthday
date
IS created
timestamp
IS created by
varchar(255}
IS edited by
varchar(255}
JSfirstname
varchar(255)
JS lastname
varchar(255)
IS picture
bytea
IS totalconversions numeric(19,2)
IS updated
timestamp
IS usertype
varchar(255)
JS username
varchar(30)
J^id
bigint
Figure 5-7. The updated wallet_user diagram
The structure of the wallet_user table only changed because of the
addition of the two new createdBy and editedBy fields. It still looks
exactly like it was in Figure 5-6. Though from the database perspective the
structure remains the same, from the Java perspective, the code is better
organized and easy to read and maintain.
Embeddables
An embeddable is an object that derives its identity from an enclosing
object. In JPA, an embeddable is a Java class whose fields are mapped to
its enclosing entity’s table. Listing 5-19 shows an Address embeddable that
can be used by other entities.
206
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-19. An Address embeddable
@Embeddable
public class Address {
protected String apartment;
protected String street;
protected String city;
protected String state;
protected String zip;
private PhoneType phoneType;
protected String phone;
public enum PhoneType {
MOBILE,
FIXED,
VOIP
}
}
The Address embeddable is a POJO with no special annotation or
mapping other than the @Embeddable annotation. This annotation
signals the runtime that this class will not have an identity of its own, but
rather derive such from its embedding entity. Any entity that embeds this
Address object will have all its fields mapped to the table of the embedding
class. Listing 5-20 shows the User entity embedding the Address class.
Listing 5-20. User embedding Address
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
207
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(unique = true, length = 30, nullable = false)
private String username;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
private LocalDate birthDay;
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
@Enumerated(EnumType.STRING)
private UserType userType;
private transient int age;
@Embedded
private Address address;
}
The User entity embeds the Address through the use of the
@Embedded annotation. The wallet_user table will have all the fields of
the Address class mapped to it. Figure 5-8 shows the updated
wallet_user table.
208
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
H wallet_user
IS birthday
date
IS created
timestamp
IS createdby
varchar(255)
IS edited by
varchar(255)
JSfirstname
varchar(255)
JS lastname
varchar(255)
IS picture
byte a
IS totalconversions numeric(19r2)
IS updated
timestamp
IS usertype
varchar(255)
*S username
varchar(SO)
IS apartment
varchar(255)
IS city
varchar(255)
IS phone
varchar(255)
IS phonetype
integer
IS state
varchar(255)
IS street
varchar(255)
IS zip
varchar(255)
Kid
Figure 5-8. The updated wallet_user table
All the Address fields are mapped to the User entity table. Embeddables
are another way of organizing code to make it much clearer and easy to read
and maintain while taking advantage of SQL’s ability to have a lot of columns
in a database.
209
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Relationships
JPA is an object-relational mapper. The relation in that name refers to the
ability of entities to have some form of relationship with each other. The
kinds of relationships or associations that entities can have with each other
are generally grouped into four types, namely:
•
Many-to-one
•
One-to-one
•
One-to-many
•
Many-to-many
There are two broad types of entity relationships in JPA, namely, single­
valued relationships and collection-valued relationships.
Single-Valued Relationships
A single-valued relationship or association is one in which an entity has an
association to another entity instance where the cardinality1 of the target is
one. In Java, this association means that one entity has a field of the target
entity as one of its properties. In the database, the primary key of the target
entity will become a foreign key column in the originating entity table.
Many-to-One
The many-to-one relationship is an association where N number of
entities are associated with one of a given target entity. There is always a
single target entity from the perspective of the originating entities.
Listing 5-21 shows a new entity, TransactionHistory, that saves the
transaction history of a User.
1 https://vertabelo.com/blog/cardinality-in-data-modeling/
210
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-21. TransactionHistory entity
@Entity
public class TransactionHistory extends AbstractEntity {
private String sourceCurrency;
private String targetCurrency;
private String amount;
private LocalDateTime transactionDate;
@ManyToOne
private User accountOwner;
}
The TransactionHistory entity has an association with the User entity.
This association is a many-to-one in that many transactions can belong to
the same user. The @ManyToOne annotation is used to denote this kind
of association. From the perspective of every TransactionHistory instance,
there is always a single user. In the database, a foreign key column will be
created in the TransactionHistory table that points to the wallet_user table.
Listing 5-22 shows the generated DDL for the TransactionHistory entity
when mapped to the database.
Listing 5-22. The TransactionHistory schema
create table if not exists transactionhistory (
id
bigint not null primary key,
amount
varchar(255),
created
timestamp,
createdby
varchar(255),
editedby
varchar(255),
sourcecurrency varchar(255),
targetcurrency varchar(255),
transactiondate timestamp,
211
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
updated
timestamp,
accountowner_id bigint
constraint fk_transactionhistory_accountowner_id
references wallet_user
);
The accountOwner_id field is the foreign key column in the
TransactionHistory table that references the User entity table. In JPA, the
foreign key column is referred to as a join column. Because we did not
explicitly specify any name for the join column, the default is the field
name followed by an underscore and the name of the primary key column,
in this case id. This column can be customized through the use of the
@JoinColumn annotation.
In the association shown in Listing 5-21, the TransactionHistory is said
to be the owning side of the relationship because the foreign key column
is found in its table. Thus, the owning side of an association is one that has
the primary key of the target entity as a foreign key column. The
@JoinColumn annotation is used on the owning side of the association to
customize the foreign key column.
By default, a single-valued relationship is loaded when the originating
entity is loaded. This means when an instance of TransactionHistory is
fetched from the database, its accountOwner field will be fetched as part
of it. This behavior can be customized by passing a FetchType value to the
fetch parameter of the @ManyToOne annotation.
The directionality of this example association is unidirectional,
meaning only one side knows about the association. The
TransactionHistory knows it has a relationship with the User entity. But the
User entity is oblivious of any such association. From the perspective of the
User entity, it is “single.” The other kind of directionality is bidirectional,
where both entities know about each other through associations.
212
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
One-to-One
A one-to-one association is one in which one entity has an association
with another entity. In this case there is only a single entity from the
perspective of either side of the relationship. Listing 5-23 shows a new
entity, UserCredentials, with an association to the User entity.
Listing 5-23. UserCredentials
@Entity
public class UserCredentials extends AbstractEntity {
@Column(unique = true, length = 30, nullable = false)
private String email;
@Column(nullable = false)
private String password;
private String salt;
@OneToOne
@JoinColumn(name = "wallet_user_id")
private User user;
}
UserCredentials is an entity that contains login credentials for a User.
It has a one-to-one association with the User, denoted by the @OnetoOne
annotation. It also bears the @JoinColumn annotation to set a custom
name for the foreign key column. This implies the UserCredentials is the
owning side of the relationship. Listing 5-24 shows the updated User entity
(showing only new parts for brevity).
213
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-24. The updated User entity
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
@OneToOne(mappedBy = "user")
private UserCredentials userCredentials;
}
The User entity also declares an association with the UserCredentials
entity, denoted by the @OnetoOne annotation. This annotation here is
passed the mappedBy parameter, set to the name of the field of the User
type in the target entity, in this case user. This denotes that UserCredentials
is the owning side of the association. The kind of association between
User and UserCredentials is a bidirectional one-to-one mapping or
association. Figure 5-9 shows the updated schema diagram for the User
and UserCredentials classes.
214
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
H wallet_user
15 birthday
date
15 created
timestamp
15 createdby
varchar(255)
I5editedby
varchar(255)
J5firstname
varchar(255)
H usercredentials
J5 lastname
varchar(2bb)
15 created
timestamp
15 picture
bytea
15 createdby varchar(255)
15 totalconversions numeric(19,2)
I5editedby varchar(255)
wallet_user_id:ifi|
15 updated
timestamp
J5 email
varchar(30)
15 usertype
varchar(255)
J5 password varchar(255)
15 apartment
varchar(255)
15 salt
varchar(255)
15 city
varchar(255)
15 updated
timestamp
15 phone
varchar(255)
wallet_user_id bigint
15 phonetype
integer
S3 id
bigint
15 state
varchar(255)
15 street
varchar(255)
15 zip
varchar(255)
23 id
bigint
Figure 5-9. The updated diagrams for User and UserCredentials
Collection-Valued Relationships
A collection-valued relationship or association is where a source
entity references one or more instances of the target entity. Unlike the
association shown in Listings 5-23 and 5-24 where the source entity targets
a single instance of the target entity, collection-valued relationships are
modeled with a collection type to represent the N number of target entity
instances. The one-to-many and many-to-many are the association types
that use collection-valued fields.
215
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
One-to-Many
An entity has a one-to-many association with a target entity when it has a
collection of the target entity as a field. Listing 5-25 shows the User entity
declaring a one-to-many association to transaction history.
Listing 5-25. User entity with a one-to-many relationship
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
@OneToMany
private List<TransactionHistory> transactionHistory;
}
A User can have one or more transactions. This is denoted by the
one-to-many relationship between the User and TransactionHistory
entities. This association, as shown in Listing 5-25, is declared by the use
of the @OneToMany annotation. The current state of the relationship is
bidirectional, because the TransactionHistory also declares an association
back to the User entity.
In every one-to-many relationship, the owning side of the association
is always the many side. In the case of the User and TransactionHistory,
the latter will be the owning side of the relationship because the primary
key of the User entity will be placed as a foreign key column in the
TransactionHistory table. To declare the many side of the association
as the owning side, the mappedBy parameter of the @OneToMany
annotation should be set to the name of the field in the TransactionHistory
entity, as shown in Listing 5-26.
216
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-26. Updated User entity
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
@OneToMany(mappedBy = "accountOwner")
private List<TransactionHistory> transactionHistory;
}
In the TransactionHistory table, a foreign key column will contain
the primary key of the target entity to which the TransactionHistory
history has an association with. The TransactionHistory table will remain
unchanged from what it was as shown in Figure 5-9.
A one-to-many association can also be unidirectional from the
perspective of the one side of the association. In this case, the target entity
type in the collection field of the one side of the association is oblivious to
the relationship. In a unidirectional one-to-many relationship, there is only
one side, which is also automatically the owning side of the association.
Since the association field is a collection type, a join table is used to map
the relationship. A join table is a simple table that contains two primary
key fields—one to the primary key of the owning or source entity of the
association and the other to the target entity.
Many-to-Many
A many-to-many association is one in which both the source and target
of the relationship have a collection of each other. The @ManyToMany
annotation can be used to express such an association. Many-to-many
relationships can also be bi- or unidirectional. Getting this type of
relationship right can be tricky, and so except in very complex cases, a
one-/many-to-one relationship should suffice.
217
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Lazy Fetching
Collection-valued associations are lazily loaded or fetched by default.
What this means is that when an instance of the User entity is loaded, its
collection field of type TransactionHistory will not be loaded unless it is
traversed or accessed in the same transaction. You can change the default
loading strategy by setting the fetch parameter of the @OneToMany or
@ManyToMany to FetchType.EAGER.
Collections of Simple Types
The collection-valued associations discussed so far have all been between
entities. JPA also has support for mapping a collection of simple types.
Remember simple types refer to the basic Java types that are not entities,
for example, String, Integer, and embeddables. Listing 5-27 shows the
UserCredentials entity with a collection of Strings to represent the email
history of a user.
Listing 5-27. UserCredentials with a collection of simple types
@Entity
public class UserCredentials extends AbstractEntity {
@ElementCollection
private Set<String> emailHistory;
}
The emailHistory field is a set of Strings annotated @ElementCollection.
This is a simple type that has no existence of its own. As such, in the
database, a table will be created with two fields. One field will be a foreign
key column that points to the primary key column of the UserCredentials
table, and another field contains the value of each element in the set.
218
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The name of this table, by default, is the name of the declaring entity
class, underscore, and then the name of the field. So for the field shown
in Listing 5-27, the resulting table will be userCredentials_emailHistory.
Element collections can also be eagerly fetched. By default, they are lazily
fetched. You can set them to be eagerly fetched by passing FetchType.
EAGER to the fetch parameter.
Maps
JPA supports declaring entity associations through the use of the java.
util.Map construct. A map is a collection that associates a key to any
arbitrary object type. There can be any number of combination types
of declaring associations using maps based on the key-value type
permutation. The value type of a map determines the type of association
that is being created. If the value type of the map is an entity, then
either a @OneToMany or @ManyToMany association annotation
should be used. However, if the value is a simple or embeddable type,
then @ElementCollection must be declared.
If the key of the map is a simple or embeddable type, the
@MapKeyColumn can be used to customize the key column in the
database. If the value of the map is an entity and the key is to be mapped
to an attribute of that entity, then the @MapKey annotation can be used
to tell the runtime which field in the target value entity the key should be
mapped to.
Given the very flexible nature of modeling associations using maps, it
can be very hard to get right. A lot of the time the use of java.util.Collection
types should suffice. Unless in very rare and extreme cases where you need
the flexibility offered by maps, we do not recommend its use.
219
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Data Persistence
The second of the trio of using JPA involves persisting the data. This
is where instances of the entities you modeled get persisted to their
respective database tables. The central artifact responsible for taking your
entity instances and persisting them to the database is the EntityManager.
There are four components to data persistence with JPA that you
should understand. These are the persistence unit, persistence context,
transactions, and the EntityManager interface.
Persistence Unit
A persistence unit is a logical grouping of a set of entities that share the
same configuration. This configuration includes the data source and other
persistence properties such as schema creation. A data source is simply
a connection to a database that can be used by JPA. The persistence unit
declares the data source and the transaction type, along with a set of
entities that belong to that persistence unit.
The data source in Jakarta EE is a managed resource that is mostly
defined as part of the server and passed to the persistence unit as a JNDI
resource. If schema generation is enabled, then the database user used
to create the data source should have the requisite permissions to create
tables in the database. Listing 5-28 shows the persistence unit declaration
for the account module of the jwallet application.
Listing 5-28. A sample persistence unit
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
220
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
xsi:schemaLocation="https://jakarta.ee/xml/ns/
persistence https://jakarta.ee/xml/ns/persistence/
persistence_3_0.xsd"
version="3.0">
<persistence-unit name="jwallet" transaction-type="JTA">
<jta-data-source>jdbc/jwallet</jta-data-source>
<properties>
<property name="jakarta.persistence.schemageneration.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
The persistence unit is named jwallet and declares the transaction
type as JTA. The declared data source is created in the application server.
This is one of the flexibilities of JPA. The underlying database could be
anywhere in the world; as long as there is a valid data source that JPA can
connect to, it will work. The declared property tells the runtime to “create”
the database tables when the application starts; other available options
are drop-and-create, create, drop, or none. There are also other properties
that can be used to load SQL scripts to populate the database when an
application starts. As is, the persistence unit does not explicitly add any
entities. This means all entities found in the module will be bound to this
persistence unit. This file is put in the resource/META-INF folder of the
application.
Persistence Context
A persistence context is akin to an instance of a persistence unit. It is a
managed set of entity instances belonging to a given persistence unit.
The persistence context is similar to a giant cache of all the entities that
221
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
are bound to the persistence unit from which the persistence context is
created. The persistence context is critical to understanding how JPA works
with regard to persisting and loading data. We will look at this shortly when
we talk about the entity manager.
Transactions
Methods called on the EntityManager that alter the state of an entity, or
the set of entities in the database, require a transaction. In Jakarta EE,
transactions are managed on your behalf by the application server. You
generally would not worry about transactional boundaries. The container
will automatically spawn or join a transaction and commit it when the
operation ends.
EntityManager
The EntityManager is an interface that has methods for carrying out create,
read, update, and delete operations on JPA entities. It is a managed object
in Jakarta EE, meaning you do not explicitly create it. Rather, you request
an instance from the JPA runtime, which should inject one for you. You can
leverage the CDI runtime to inject the EntityManager object as long as you
have a producer for it. This construct is discussed in Chapter 4.
Requesting for an EntityManager instance entails you telling the JPA
runtime which persistence unit to associate the given EntityManager
with. The returned instance is then bound to that persistence unit, from
which a persistence context is created. This persistence context is what the
EntityManager will use to manage the CRUD of the entities bound to the
persistence unit.
222
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Persisting Entities
Injecting theEntityManager
To persist an entity, we need to first get an instance of the EntityManager.
Listing 5-29 shows the BaseRepository class injecting a database-qualified
EntityManager (for details of this construct, please refer to Chapter 4).
Listing 5-29. Injected EntityManager
public abstract class BaseRepository<E, K> {
@Inject
@Database(POSTGRES)
EntityManager em;
}
The @Inject annotation is a CDI annotation for requesting contextual
instances. There is a place where the EntityManager instances are
“produced” as shown in Listing 5-30.
Listing 5-30. EntityManager production
public class ProducerFactory {
@Produces
@Database(DB.POSTGRES)
@PersistenceContext(unitName = "jwallet")
EntityManager postgres;
}
The @PersistenceContext annotation is a JPA construct for requesting
EntityManagers. The postgres field will be populated by the JPA runtime
with an instance of the EntityManager scoped to the persistence
unit. Injection is the recommended way of getting an instance of the
EntityManager on the Jakarta EE platform.
223
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Persisting Data
Once you have an entity manager instance, you can invoke methods on it
to persist data. The EntityManager#persist method is the primary means
of persisting entity instances. It takes an entity instance and persists it in
the database. Listing 5-31 shows the save method in BaseRepository for
persisting entities.
Listing 5-31. BaseRepository
public abstract class BaseRepository<E, K> {
@Inject
@Database(POSTGRES)
EntityManager em;
public E save(E entity) {
em.persist(entity);
return entity;
}
}
The BaseRepository is a generic class that takes an entity type and its
corresponding primary key type. It contains common CRUD methods
to avoid repeating the same for all entities. The em.persist call will cause
the entity manager to put the passed entity instance into the persistence
context. For simplicity, the persistence context is created when a
transactional method starts. Remember the persistence context is sort of
an instance of the persistence unit. The BaseRepository is extended by the
UserRepository, as shown in Listing 5-32.
224
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-32. The UserRepository
public class UserRepository extends
BaseRepository<User, Long> {
public UserRepository() {
super(User.class);
}
}
The UserRepository is then injected into the UserService to be
used for persisting users. The createUser method of this class takes a
CreateUserRequest and delegates it to the userRepository as shown in
Listing 5-33.
Listing 5-33. The UserService persisting users
@Action
public class UserService implements UserFacade {
@Inject
UserRepository userRepository;
@Override
public UserResponse createUser(CreateUserRequest
createUserRequest) {
User user = fromUserWrapper(createUserRequest);
user = userRepository.save(user);
UserResponse userResponse = getUser(user.getId());
return userResponse;
}
}
225
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The UserService uses the @Action stereotype to declare a requestscoped transactional bean. Please refer to Chapter 4 for detailed CDI
discussion. The @Transactional annotation is a CDI interceptor that
will cause a transaction to be created for every method invoked on the
UserService. When the save method is called on the userRepository
contextual object, the entity manager will persist the passed entity to the
persistence context created when the method execution started.
At this point, the entity instance would have its primary key field
set, but the instance would still not be in the database. The persistence
context contains the instance and all other instances that have any kind
of operation performed on them through a method invocation on the
entity manager. When the method returns successfully, the container
will automatically commit the transaction, and it is at this point that the
persistence context will get flushed to the database.
Transaction Rollback
During entity manager operations, errors can occur. A typical example is
constraint violation. The User entity we have seen so far has no validation.
However, every entity in any application will have some form of validation
constraints on its fields based on the business context. On the Jakarta EE
platform, the Jakarta Bean Validation specification2 is the default means
of declaring constraints on artifacts. Listing 5-34 shows the updated User
entity with validation constraints on its fields.
Listing 5-34. Constrained User entity
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
2 https://jakarta.ee/specifications/bean-validation/3.0/
226
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Column(nullable = false)
@NotEmpty
private String firstName;
@Column(nullable = false)
@NotEmpty
private String lastName;
@Column(precision = 19, scale = 2)
private BigDecimal totalConversions;
@NotNull
@Past
private LocalDate birthDay;
@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] picture;
@Enumerated(EnumType.STRING)
private UserType userType;
@Embedded
@Valid
private Address address;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
@Valid
private UserCredentials userCredentials;
@OneToMany(mappedBy = "accountOwner", cascade =
CascadeType.ALL)
227
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
private List<TransactionHistory> transactionHistory =
new ArrayList<>();
private transient int age;
}
A number of the validation constraints are self-explanatory, for
instance, @NotNull means the field should not be null. The @Past
annotation on the birthDay field requires the set value to be in the past.
The @Valid annotation on the Address and UserCredentials tells the
runtime to cascade validation to the annotated field type. So when the
User entity is being validated, the validation will be cascaded to the two
@Valid annotated fields, and their respective fields will also be validated if
they have constraint annotations. The constrained UserCredentials entity
is shown in Listing 5-35.
Listing 5-35. The constrained UserCredentials entity
@Entity
public class UserCredentials extends AbstractEntity {
@Column(unique = true, length = 30, nullable = false)
@NotEmpty
@Email
private String email;
@Column(nullable = false)
@NotEmpty
@Size(min = 8, max = 30)
private String password;
private String salt;
228
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@OneToOne
@JoinColumn(name = "wallet_user_id")
private User user;
@ElementCollection
private Set<String> emailHistory;
}
The @Email annotation on the email field will enforce a valid email
constraint for any passed email. The @Size annotation sets the minimum
character length of the password to 8 and maximum to 30.
When the persist method is called on an EntityManager instance,
in this case the save method on the userRepository contextual instance,
just before the entity is persisted, the runtime will automatically validate
the constraints. This validation is enabled automatically when a bean
validation provider is found on the classpath.
If any validation constraint fails, a ConstraintViolationException will
be thrown by the bean validation runtime, which will result in a rollback
of the transaction. In this case, the transaction will not be committed and
will be rolled back. All of this is done by default without you needing to set
anything. If there is no exception thrown, the entity gets merged into the
persistent context, and when the method exits successfully, the transaction
gets committed with it being flushed to the database.
Updating and Removing Data
Persisting entities is done with the persist method on the EntityManager.
Updating is equally done with the merge method. Listing 5-36 shows the
merge method of the BaseRepository class.
229
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-36. The merge method in BaseRepository
public abstract class BaseRepository<E, K> {
@Inject
@Database(POSTGRES)
EntityManager em;
public E merge(E entity) {
return em.merge(entity);
}
}
The merge method similarly takes an entity and merges the state of the
entity into the currently active persistence context. Similar to persisting,
validations will be performed, and if everything works correctly, the
persistence context gets flushed when the transaction is committed.
Deleting an entity is done with the remove method of the
EntityManager. This method takes an entity instance and removes the
entity first from the persistence context. And when the persistence context
is merged, the row gets removed.
Cascading Operations
The various association annotations, @OneToOne, @ManyToOne,
@OneToMany, and @ManyToMany, have the cascade parameter that
can be set to any of the CascadeType enum types. The User entity
shown in Listing 5-34 shows the CascadeType.ALL value passed to the
@OneToMany association for the TransactionHistory. This means that the
persistence runtime should cascade operations on the parent entity, in this
case the User entity, to the child entity, in this case TransactionHistory.
230
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
So when persisting a user instance, if there are any TransactionHistory
instances in the list, these will also get persisted. Effectively all operations
on the parent entity will be cascaded to the child. A lot of the time, the
decision to cascade will depend on the business domain.
For instance, a rule of thumb is the direction an association can be
traversed. In the User entity, it is natural to traverse from a user to its
transaction history. It really would be weird to traverse a history back to
its user. For such, it makes sense to cascade operations from the User to its
TransactionHistory.
Callback Methods
JPA has callback methods that entities can implement to carry out
operations just before a checkpoint operation is executed. The
@PrePersist, @PreUpdate, @PostLoad, and @PostRemove are annotations
that can be placed on a method either in the entity or in an entity listener
to mark as a callback. As the names of the annotations imply, annotating a
method with any of them results in the method being called just before or
after the event for which it’s listening occurs. Listing 5-37 shows the User
entity with a @PostLoad callback method to compute the age of the user.
Listing 5-37. @PostLoad callback
@Entity
@Table(name = "WALLET_USER")
public class User extends AbstractEntity {
private transient int age;
@PostLoad
private void computeAge() {
age = (int) ChronoUnit.YEARS
231
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
.between(birthDay, LocalDate.
now(ZoneOffset.UTC));
}
}
The computeAge method is annotated with @PostLoad, the
implementation of which simply calculates the years between today’s
date and the birthday of the user, setting the transient age field to the
result. This method will be called right after the entity is loaded from
the database. When a callback method is created within the entity as we
have it, the method has access to the fields of the entity. The signature of
the callback method within the entity is that it returns void and takes no
parameter. The caveat with a callback method within the entity is that you
cannot inject any dependency into it.
Entity Listeners
Another way to attach callbacks to entities in JPA is through the use of
entity listeners. An entity listener is a class that declares one or more
callback methods. This class can then be registered with an entity, and
every callback method in the listening class will be called when the
listening event occurs for the entity. Listing 5-38 shows an entity listener
with two callback methods.
Listing 5-38. An entity listener
@ApplicationScoped
public class AbstractEntityEntityListener {
@PrePersist
void init(final Object entity) {
final AbstractEntity abstractEntity =
(AbstractEntity) entity;
232
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
abstractEntity.setCreated(LocalDateTime.
now(ZoneOffset.UTC));
abstractEntity.setCreatedBy("Dummy User");
}
@PreUpdate
void update(final Object entity) {
final AbstractEntity abstractEntity =
(AbstractEntity) entity;
abstractEntity.setUpdated(LocalDateTime.
now(ZoneOffset.UTC));
abstractEntity.setEditedBy("Dummy User");
}
}
The AbstractEntityEntityListener is an application-scoped CDI bean
that declares two methods annotated @PrePersist and @PreUpdate,
respectively. A callback method in an entity listener takes a single
parameter of type java.lang.Object. This is because within the entity, the
instance is known to be the instance of the declaring entity. But a listener is
a separate class, and as such, there needs to be a way to pass the instance
on which the event occurred to the method. This is why the method takes
an Object.
Within the method implementations, the passed Object type is cast
to the AbstractEntity type and some fields are set on it. An entity listener
is also a CDI bean as shown by the @ApplicationScoped annotation. This
means we can inject dependencies into it and then carry operations on
the entity.
Once an entity listener is declared as done in Listing 5-38,
it has to be registered with an entity. Listing 5-39 shows the
AbstractEntityEntityListener registered with the AbstractEntity.
233
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-39. Registering an entity listener
@MappedSuperclass
@EntityListeners({AbstractEntityEntityListener.class})
public abstract class AbstractEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
protected LocalDateTime created;
protected LocalDateTime updated;
protected String createdBy;
protected String editedBy;
}
Registering an entity listener on an entity is done through the
@EntityListeners annotation. As shown in Listing 5-39, this annotation
takes an array of entity listeners and calls them for each registered event.
Since the AbstractEntity is just a mapped super class, this declaration
is equivalent to registering the entity listener with each child of the
AbstractEntity.
Querying Data
There are two primary ways of querying for data in JPA, namely, the Jakarta
Persistence Query Language (JPQL) and the Criteria API. In between these
two are a number of overridden find methods on the EntityManager that
can be used to directly find an entity based on its primary key.
234
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Finding by Primary Key
The EntityManager has the find method for finding an entity by primary
key. This is the simplest way of loading an entity instance if the primary
key is known. Listing 5-40 shows the BaseRepository’s implementation of
finding an entity by its ID in the find method.
Listing 5-40. BaseRepository’s find method
public abstract class BaseRepository<E, K> {
@Inject
@Database(POSTGRES)
EntityManager em;
public E findById(K id) {
return em.find(clazz, id);
}
}
The find method returns the entity instance if found or null. You
should keep this in mind when using the find method to load an entity.
You should null-check the returned value.
Jakarta Persistence Query Language (JPQL)
The Jakarta Persistence Query Language, otherwise known as JPQL, is a
string-based, SQL-lookalike language for querying entities. JPQL is very
similar to SQL, except instead of querying across database tables and rows,
you query across your persistent entities and objects. The JPA runtime
takes care of translating the JPQL to the requisite SQL dialect of the
underlying database.
235
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
JPQL is not a SQL alternative. It is a query language you can use in
addition to SQL. It’s important to not get bogged down by dogma about
which is better. JPQL is well-suited to Java developers. Knowing JPQL does
not negate the need to know SQL. Both languages complement each other
and help you write very sophisticated applications.
The Structure of JPQL
A typical JPQL query is made up of at least a select and from clause, with
optional where and order by clauses. Listing 5-41 shows the simplest JPQL
for querying a User entity.
Listing 5-41. Simple JPQL query
select u from User u
The first difference between this query and its SQL counterpart is
that the JPQL is querying an entity and not a database table. The User
in the query refers to the User entity. This name is the unqualified class
name of the User entity. This name can be customized by passing a name
parameter to the @Entity annotation, though this is rare in practice. The
entity is then aliased to the u variable. The variable u is arbitrary. It could
equally have been foo or bazz. In JPQL, an alias variable is mandatory
while it’s optional in SQL. The u alias variable can then be used in the rest
of the query to reference each entity instance in the database row.
The query also makes a select clause for the User entity. This means
the full User entity instance will be returned for each row of the User table.
In SQL, you would enumerate the columns of the table you want to query.
The runtime takes care of translating this query to the most optimal SQL
dialect of the underlying database.
236
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Selecting withselect
The JPQL select clause can take more than an entity. It can take path
expressions as well. The final returned type is dependent upon the
type passed to the select clause. In the query shown in Listing 5-41, the
returned type of the query will be a list of User instances. It is possible to
also traverse an entity to one of its properties or even to a different entity.
Listing 5-42 shows traversing the User entity to its UserCredentials entity.
Listing 5-42. Path property traversal
select u.userCredentials from User u
The path traversal to the UserCredentials field of the User entity will
cause the result list returned from the query to be of type UserCredentials,
even though the query started from the User table. It is possible to also
traverse simple fields of the entity. Listing 5-43 shows traversing simple
properties.
Listing 5-43. Traversing simple properties
select u.lastName, u.lastName, u.userCredentials.email
from User u
This query traverses to simple types in the User and UserCredentials
entities. The returned type of this query will be zero or more instances of
object arrays. This is because for such expressions, the final property could
be any type, and as such, the runtime returns everything as an array of
objects.
At its core, this is very much how the JPQL select clause works. You can
select an entity or traverse to a property in that entity or even the property
of an entity in the primary entity. The return type of the result will depend
on what the type or types passed to the select clause resolve to. If it resolves
to a single type, the returned result will be of that type. If it resolves to more
than one type, then you get an array of objects.
237
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The fromClause
The from clause defines the entity or entities across which the query
should span. The queries shown in Listings 5-41 to 43 all had the from
clause declaring the query domain entity and aliasing it to a variable.
The from clause, however, can also declare more than one entity to query
across through joins.
The query shown in Listing 5-42 will create an implicit inner join from
the User to the UserCredentials table. The query can be rewritten as shown
in Listing 5-44.
Listing 5-44. Explicit join
select u.userCredentials from User u join u.userCredentials c
The query now joins the User to the UserCredentials table and aliases
the latter to the c variable. These aliased variables can then be used in the
where clause. As used, the type of join created is the inner join. The join
type can be explicitly declared, but in its absence, defaults to inner join.
You can declare multiple joins and alias them all to variables that will be
available in the rest of the query context. An outer join can also be created
using the left join syntax instead of just join.
Fetch joins can also be used to create joins, but unlike traditional
joins, a fetch join does not return the joined entity. A fetch join signals the
runtime to eagerly load the fetched entity so when it is accessed from the
primary entity, there is no extra database call. Listing 5-45 shows the User
entity with a fetch join query for its transaction history.
Listing 5-45. User entity with a fetch join
select u from User u join fetch u.transactionHistory
The fetch join query for the transaction history of the user tells
the runtime to prefetch the transaction history of each user row. The
transactionHistory is declared to be lazily fetched. Within the transaction,
238
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
with the join fetch in place, when this query is executed, the runtime will
not make a second call to the database. The fetch join effectively eagerly
fetches the joined entity.
The where Clause
The where clause of a JPQL query is where the results are filtered to only
those matching the where criteria. The where clause in JPQL is very similar
to the SQL where clause. Listing 5-46 shows the User query restricting the
result set to only users with a certain total conversion threshold.
Listing 5-46. where for the User query
select u.userCredentials from User u
where u.totalConversions >= :totalConversions
The where clause uses the aliased variable in the from clause to set
a condition. The aliased variable, being an instance of the User entity,
can be traversed with the . operator. The where clause traverses the
totalConversions field and uses the >= operator to restrict the result.
The variable on the right-hand side of the operator is called a named
parameter. This is the recommended way to pass variables to JPQL queries.
The value will be escaped by the runtime on your behalf for security
reasons.
The where clause supports a number of the Java operators like >, <, <=,
and >= and the keywords LIKE, IN, IS, EMPTY, BETWEEN, and the NOT
for inverting any of the keywords. It also has support for the logical AND
and OR that you can use to create logically related conditions. The JPA
specification has much more details about using the where3 clause in your
queries.
3 https://jakarta.ee/specifications/persistence/3.1/jakarta-
persistence-spec-3.1.html#a4985
239
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Aggregate Queries
JPQL also has support for aggregate queries. There are five aggregate
queries that can be used to create summaries of data. These are AVG,
COUNT, MAX, MIN, and SUM. Listing 5-47 shows the count of all Users
with total conversions exceeding a passed amount.
Listing 5-47. The use of the COUNT aggregate query
select COUNT(u) from User u
where u.totalConversions >= :totalConversions
The COUNT aggregate function is used in the select clause to count
the number of users with total conversions exceeding a passed value. This
query will return an integral type denoting the total count.
Executing Queries
After creating queries, they need to be executed. The way to execute JPQL
queries is through the EntityManager interface. There are two kinds of
JPQL, namely, dynamic and named queries.
Dynamic Queries
Dynamic queries are JPQL queries created directly in a method. These
are said to be created on the fly or dynamically because they will be
constructed for each call of the method. Listing 5-48 shows the query for
loading all Users executed dynamically.
240
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-48. Dynamic query execution
public List<User> loadAllUsers() {
return em.createQuery("select u from User u",
User.class)
.getResultList();
}
The createQuery method is an overloaded method on the entity
manager that takes a query, and optionally a type, to which the results
should be cast to, and then returns a TypedQuery<T> where T is the type
passed to the method. If no type is specified in the createQuery method,
then a Query is returned. In this case, the result will be untyped. Generally
we do not recommend the use of the raw Query type. You should pass in a
type as long as you know it beforehand.
The returned TypedQuery interface has a number of methods that you
can call to get the result of the query. The getResultList, getResultStream,
and getSingleResult methods return a typed list of the query result, a
typed java.util.stream.Stream interface, or a single result. We recommend
avoiding the use of the getSingleResult because it is a little quirky.
Named Queries
The example shown in Listing 5-48 can be transformed into a named
query by moving the JPQL to an element on the entity class as shown in
Listing 5-49.
Listing 5-49. Named query
@Entity
@Table(name = "WALLET_USER")
@NamedQuery(name = User.LOAD_ALL_USERS, query = "select u from
User u")
241
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
public class User extends AbstractEntity {
public static final String LOAD_ALL_USERS = "User.
loadAllUsers";
}
Creating a named query entails annotating an entity class with the
@NamedQuery annotation. This annotation takes the name of the query
and the actual JPQL. The example shown in Listing 5-49 shows the User.
loadAllUsers query that selects all users from the User entity. Using a
named query is just a matter of passing the name of the query to the
EntityManager as shown in Listing 5-50.
Listing 5-50. Executing a named query
public List<User> loadAllUsers() {
return em.createNamedQuery(User.LOAD_ALL_USERS, User.
class).getResultList();
}
The createNamedQuery method of the EntityManager interface takes
the name of the query and optionally the type. This is practically the only
difference between executing a named and dynamic query. The jury is still
out on which is much more efficient. Our general recommendation is to
use named queries as much as possible because they are easier to read and
can be found at one central place, mostly on the entity being queried.
Passing Parameters
The TypedQuery interface has methods to set the parameters of JPQL
queries. Listing 5-51 shows the execution of the query that was shown in
Listing 5-46.
242
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-51. Passing parameters to queries
public List<User> loadUsersByTotalConversion(final BigDecimal
totalConversion) {
return em.createNamedQuery(LOAD_USERS_BY_CONVERSIONS,
User.class)
.setParameter("totalConversions", totalConversion)
.getResultList();
}
The setParameter method on the returned TypedQuery takes a String
representing the named parameter and the value. The passed value will be
automatically escaped by the JPA runtime.
JPQL is a powerful but simple query language that complements the
use of SQL for application development. The question of when to use JPQL
is something we do not have any strong opinions about. In the end, a lot
of things come down to technical decisions of the particular domain. A
general rule of thumb is to use what is available on the platform as much
as possible because doing so makes your application portable across
different providers.
Criteria API
The Criteria API is another API for querying entities in JPA. Unlike JPQL,
the Criteria API is type-safe but much more verbose. It lends itself better to
creating search-type queries in applications. JPQL, on the other hand, is much
more suited to creating queries that are known beforehand. Listing 5-52 shows
the Criteria API equivalent of the JPQL shown in Listing 5-42.
243
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-52. The Criteria API for getting users
public List<User> loadAllUsersCriteria() {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<User> query = criteriaBuilder.
createQuery(User.class);
Root<User> from = query.from(User.class);
return em.createQuery(query.select(from)).getResultList();
}
The Criteria API starts with a call to the getCriteriaBuilder method
on the EntityManager. This returns a CriteriaBuilder that is used to build
the query. The CriteriaBuilder creates a typed CriteriaQuery with a call to
the createQuery method that takes a class. The query then uses the from
method to create a typed Root<T> object that acts as the root entity of the
query. The query is finally executed by passing the query.select(from)
to the createQuery method of the EntityManager. The CriteriaQuery.
select method returns yet another CriteriaQuery that is passed to the
EntityManager.
As you can see, the Criteria API can be very verbose. A one-line JPQL
translated to the Criteria API takes about three. There is also support
for passing parameters to the query. The query shown in Listing 5-46 is
rewritten using the Criteria API in Listing 5-53.
Listing 5-53. Passing parameters with Criteria API
public List<User> loadUsersByConversionCriteria(final
BigDecimal totalConversion) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<User> query = criteriaBuilder.
createQuery(User.class);
Root<User> from = query.from(User.class);
244
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
CriteriaQuery<User> where =
query.select(from).where(
criteriaBuilder.greaterThanOrEqualTo(
from.get("totalConversions"),totalConversion));
return em.createQuery(where).getResultList();
}
The Criteria API has methods for all the keywords we saw with JPQL
such as the where clause. The query.select method returns a CriteriaQuery
on which the where method is called to set the predicate for the query. The
CriteriaBuilder has methods representing the various operators available
in JPQL such as greaterThanOrEqualTo as used above. To access a field of
the entity, the get method is called on the Root object and passed the name
of the field.
The Criteria API lends itself much better to creating search-type
queries. Listing 5-54 shows a simple search for a user based on the passed
search object.
Listing 5-54. Criteria API search
public List<User> searchUsers(final UserSearchRequest
searchRequest) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<User> query = criteriaBuilder.
createQuery(User.class);
Root<User> from = query.from(User.class);
final Set<Predicate> predicateSet = new HashSet<>();
if (searchRequest.getFirstName() != null) {
Predicate firstName = criteriaBuilder
.like(from.get("firstName"),
"%" + searchRequest.
getFirstName() + "%");
245
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
predicateSet.add(firstName);
}
if (searchRequest.getLastName() != null) {
Predicate lastName = criteriaBuilder
.like(from.get("lastName"),
"%" + searchRequest.
getLastName() + "%");
predicateSet.add(lastName);
}
if (searchRequest.getTotalConversions() != null) {
Predicate totalConversions = criteriaBuilder
.greaterThanOrEqualTo(from.get("totalConversions"),
searchRequest.getTotalConversions());
predicateSet.add(totalConversions);
}
if (searchRequest.getUserType() != null) {
Predicate userType = criteriaBuilder
.equal(from.get("userType"), searchRequest.
getUserType());
predicateSet.add(userType);
}
CriteriaQuery<User> where = query
.select(from).where(predicateSet.toArray(new
Predicate[] {}));
return em.createQuery(where).getResultList();
}
The method takes a UserSearchRequest object that contains some
fields of the User entity. It then traverses each field, checking if it’s not null
and then creating a jakarta.persistence.criteria.Predicate object from it.
246
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
These predicates are added to a set that is then converted to an array and
passed to the where method on the CriteriaQuery. This is a very simple
search implementation using the Criteria API. Because of its dynamic nature,
it is well-suited to this kind of use. The Jakarta Persistence specification has
much more details on the Criteria API in the relevant section.
From Object-Relational to NoSQL Models
While Jakarta Persistence has matured into a solution for relational
databases, modern applications increasingly need to work with non­
relational data models. The rise of big data, real-time analytics, and
microservices has driven the adoption of NoSQL databases, which excel at
handling unstructured data, high write volumes, and horizontal scaling.
Jakarta Persistence was designed with the relational paradigm in mind,
where data follows a structured schema and transactional integrity is
paramount. However, this approach can become limiting when working
with the diverse data models offered by NoSQL databases. Each NoSQL
category—key-value, document, column-family, and graph—represents
data in fundamentally different ways than relational tables.
This is where Jakarta NoSQL comes in. As a complementary
specification to Jakarta Persistence, Jakarta NoSQL provides a standardized
Java API for interacting with various NoSQL database technologies. It
maintains the familiar annotation-based approach of JPA but adapts it to
the schema-flexible, distributed nature of NoSQL stores.
Jakarta NoSQL
Jakarta NoSQL addresses the growing need for standardized access to non­
relational databases. Just as JPA abstracts the details of JDBC and relational
databases, Jakarta NoSQL creates a consistent programming model across
different NoSQL technologies.
247
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Goals of Jakarta NoSQL
1. Enhanced Productivity: Jakarta NoSQL simplifies
the integration of Java applications with NoSQL
databases, reducing the learning curve and enabling
developers to focus on core application logic rather
than database-specific intricacies.
2. Rich Object Mapping: By supporting rich object
mapping, Jakarta NoSQL eliminates the need for
manual data transformation, allowing developers to
work with NoSQL databases using familiar objectoriented paradigms.
3. Flexibility and Adaptability: Jakarta NoSQL is
designed to be flexible and adaptable, supporting a
wide range of NoSQL database types. Its extensible
architecture ensures compatibility with both
established and emerging database technologies.
Non-goals of Jakarta NoSQL
While Jakarta NoSQL aims to streamline NoSQL database integration,
it does not aim to replicate all features of traditional object-relational
mapping (ORM) frameworks or provide full compatibility with every
NoSQL database. Instead, it focuses on offering a standardized approach
that balances generality with practicality.
NoSQL Database Categories
Jakarta NoSQL provides support for four primary categories of NoSQL
databases:
248
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
1. Key-Value Databases
These databases offer a straightforward storage
mechanism where keys are paired with values, akin
to Java’s HashMap. They are well-suited for use
cases that require simple data storage and retrieval.
Some prominent examples of key-value databases
include Redis and Amazon DynamoDB.
2. Document Databases
These databases are designed to store and query
intricate, hierarchical document structures, typically
represented in formats like JSON or XML. They offer
flexibility in data modeling and are commonly used
in applications that deal with semi-structured data.
Notable examples of document databases include
MongoDB and CouchDB.
3. Column-Family Databases
These databases organize data into column families
instead of traditional tables. This structure allows for
efficient storage and retrieval of data with high write
throughput and scalability. Apache Cassandra and
HBase are well-known examples of column-family
databases.
4. Graph Databases
These databases are purpose-built for managing
data with intricate relationships and connections.
They excel in scenarios where the focus is on
traversing and analyzing connections between
data points. Neo4j and JanusGraph are prominent
examples of graph databases.
249
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Programming Model for Entity Classes
Jakarta NoSQL defines a programming model for entity classes that
specifies restrictions and annotations for integrating Java classes with
NoSQL databases, much similar to JPA.
Persistent Fields
Persistent fields in entity classes represent data that is stored in the
database. These fields can be categorized into
•
Basic Fields: Represent fundamental data types such as
integers, strings, and dates
•
Embedded Fields: Allow the inclusion of complex,
nested Java objects within the entity
•
Association Fields: Implement relationships between
entity types
Basic Types
Jakarta NoSQL mandates support for the following basic types:
250
•
Primitive Types and Wrapper Classes: Include
int, double, boolean, and their corresponding
wrapper classes
•
Strings: Represent textual data
•
Date and Time Types: Such as LocalDate,
LocalDateTime, and Instant
•
UUID: Universally Unique Identifiers for entity
identification
•
BigInteger and BigDecimal: For large numeric values
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
•
Byte Arrays: For binary data
•
Enums: Custom enumerated types
Modeling with Jakarta NoSQL
Jakarta NoSQL uses annotations similar to JPA but tailored for NoSQL
structures. Listing 5-55 shows an example of User entity mapping.
Listing 5-55. User entity mapping
@Entity
public class User {
@Id
private String id;
@Column
private String name;
@Column
private List<String> phones;
private Address address;
}
The @Entity, @Id, and @Column annotations in Jakarta NoSQL serve
similar purposes to their JPA counterparts but adapt to the schema-flexible
nature of NoSQL databases. However, unlike in JPA where all entity
fields are mapped by default to a table unless otherwise stated with the
@Transient annotation, Jakarta NoSQL uses the @Column annotation to
explicitly denote fields that should be mapped to the underlying NoSQL
database.
Given the User entity class shown in Listing 5-55, the address field
of type Address will be ignored by the runtime because it has no explicit
@Column annotation. This is an important distinction between the two
specifications that should be kept in mind when modeling data for NoSQL
databases with Jakarta NoSQL.
251
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Core Annotations
Unlike JPA, Jakarta NoSQL only comes with a handful of annotations.
These annotations map to the same semantics as those of JPA, but tailored
to NoSQL databases. Let’s explore these annotations.
@Entity
The @Entity annotation signifies that a Java class represents a persistent
entity with a lifecycle managed by the underlying data store. This
annotation not only defines the entity’s structure but also denotes its
existence beyond the scope of a single Java application instance. In
essence, the @Entity annotation encapsulates the notion of a domain
object that persists beyond the lifetime of a Java process, ensuring
consistency and durability in data management. The @Entity annotation is
functionally identical to its counterpart in JPA.
@Id
Central to the entity model is the @Id annotation, which designates a field
as the primary key. Similar to JPA and relational databases, the ID denotes
a field in the entity class that acts as the technical identity of each row
inserted into the database. Note, however, that given the diversity of the
different NoSQL databases out there, the behavior of the ID field in Jakarta
NoSQL is heavily dependent on the type of underlying NoSQL database
being mapped to. The spec states that the @Id annotation supports custom
names, but that some NoSQL databases reserve certain keywords for keys.
If the custom name conflicts with a reserved keyword, the database may
ignore it.
Jakarta NoSQL also does not offer an auto-increment strategy for @Id
fields left empty. Behavior depends on the NoSQL database: a key-value
database may throw a NullPointerException for a null ID, while others
might generate a value or return an error.
252
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Column
The @Column annotation provides fine-grained control over mapping
entity properties to database fields. As shown in Listing 5-55, this
annotation explicitly marks properties of entity classes that should be
mapped to columns in the underlying NoSQL database. Properties of
entity classes that are not marked @Column will be ignored.
@Embeddable
In Jakarta NoSQL, the @Embeddable annotation marks a class that can be
included within another entity. This annotation is functionally identical to
how embedding works in JPA and discussed in the section “Data Modeling.”
By default, when an embeddable class is included, its fields are directly
added as columns to the entity’s table. This is called “FLAT” embedding.
For instance, Listing 5-56 reproduces the User and Address entities
with their new relationships.
Listing 5-56. The User and Address entities
@Entity
public class User {
@Id
private String id;
@Column
private String name;
@Column
private List<String> phones;
@Column
private Address address;
}
@Embeddable
253
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
public class Address {
@Column
private String street;
@Column
private String city;
@Column
private String postalCode;
}
The Address class is marked @Embeddable, and the User entity has
an Address field. The Address fields (street, city, postal code) would
become columns in the User table. The JSON representation of a “FLAT”
embedded address would show the address fields as direct key-value pairs
at the user object level, with prefixes to indicate the address.
Alternatively, you can use “GROUPING” embedding, specified
with @Embeddable(GROUPING). This strategy groups the fields of the
embeddable class into a nested structure within the entity’s data. So, in the
previous example, the Address fields would be stored as a nested object
within the User data. The JSON representation of a “GROUPING” embedded
address will show the address fields grouped in an address object.
@Convert
The @Convert annotation in Jakarta NoSQL allows you to transform a
field’s data between its Java representation and its database storage format.
This is helpful when you need to store complex or non-standard Java
objects in a way that the database can understand.
To use @Convert, you must create a converter class that handles the
transformation. This converter class must follow the AttributeConverter
interface, which requires you to define two methods: one to convert the
Java object to its database representation and another to convert the
database data back to the Java object. This is the same construct works for
JPA as well.
254
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
For example, if you have an Employee entity with a MonetaryAmount
field for salary, you can create a MoneyConverter to transform the
MonetaryAmount object into a simple string for database storage.
The @Convert annotation on the salary field would specify that the
MoneyConverter should be used.
The MoneyConverter would then have methods to convert a
MonetaryAmount to a string (e.g., “USD 5000.00”) and vice versa. This
allows you to store and retrieve the salary data correctly, even though the
database only stores it as a string.
The JSON representation of the Employee entity would then reflect
the converted data, showing the salary as a string that is a database­
compatible format.
There are other annotations that help model entity inheritance
relationships like @MappedSuperclass, @Inheritance,
@DiscrimanatorColumn, and @DiscriminatorValue. Please refer to
the (relatively very short) Jakarta NoSQL annotation for full coverage of
all the supported annotations. Remember that understanding the JPA
annotation concepts will be enough for you to understand how they map
to Jakarta NoSQL.
Data Access Layer in Jakarta NoSQL
While Jakarta Persistence relies on the EntityManager as its central API,
Jakarta NoSQL takes a different approach with its Template pattern. This
pattern provides a higher-level abstraction for database operations that
simplifies development and promotes clean separation between business
logic and data access code.
255
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The Template Pattern
The Template pattern in Jakarta NoSQL serves as the foundation for
implementing data access objects (DAOs). It offers a predefined set of
methods for common database operations while hiding the low-level
details of database interactions. Listing 5-57 shows a simple insert and find
operation for the User entity.
Listing 5-57. Use of Template
@Inject
Template template;
// Create and insert an entity
User user = User.builder()
.id(id)
.name("John Doe")
.phones(List.of("+1-555-123-4567", "+1-555-987-6543"))
.address(new Address("123 Main St", "Springfield", "12345"))
.build();
template.insert(user);
// Retrieve an entity by ID
Optional<User> found = template.find(User.class, id);
// Delete an entity
template.delete(User.class, id);
The above code snippet shows basic CRUD (create, read, update,
delete) operations using the Template pattern:
•
256
Create: A new User object is constructed with specified
attributes (id, name, phones, address). The template.
insert(user) line persists this user data into the
underlying NoSQL database.
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
•
Read: The template.find(User.class, id) line retrieves
a User object based on the provided id. The result is
wrapped in an Optional to handle potential absence.
•
Delete: The template.delete(User.class, id) line removes
the User data associated with the given id from the
underlying database.
The Template class also provides a fluent API for more complex
queries, enabling the construction of expressive and readable database
operations. Listing 5-58 shows an example of a more elaborate query using
Template.
Listing 5-58. A complex Template query
// Query with multiple conditions
List<User> users = template.select(User.class)
.where("name")
.eq("John Doe")
.and("phones")
.contains("+1-555-123-4567")
.result();
// Delete with conditions
template.delete(User.class)
.where("name")
.eq("John Doe")
.and("address.city")
.eq("Springfield")
.execute();
257
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Navigation Through Entity Relationships
The Template pattern supports navigating through entity relationships
using dot notation, similar to how path expressions work in JPQL. Listing 5-59
shows an example traversing the embedded entity.
Listing 5-59. Path traversal query
// Query through embedded objects
List<User> users = template.select(User.class)
.where("address.postalCode")
.eq("12345")
.orderBy("address.city")
.asc()
.result();
This code shows how to use the Template pattern and dot notation to
query via embedded objects within an entity. In this example, it retrieves a
list of users based on their postal code and orders them by city.
Database-Specific Considerations
While the Template API aims to provide a consistent interface
across NoSQL databases, some features may not be available in all
database types:
258
•
Key-Value Databases: May only support operations
by key, with limited or no support for condition-based
queries.
•
Document Databases: Generally support most query
operations and filtering capabilities.
•
Column-Family Databases: Support varies by specific
database implementation.
CHAPTER 5
•
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Time-To-Live (TTL) Support: Available in some NoSQL
databases, allowing data to expire after a specified
duration.
When a database doesn’t support certain operations, Jakarta NoSQL
raises an UnsupportedOperationException, allowing applications to
gracefully handle these limitations. The Template pattern in Jakarta NoSQL
provides a balance between the simplicity of standard CRUD operations
and the flexibility needed for specialized database queries, making it a
powerful tool for working with non-relational data stores.
The Bridge: Jakarta Data
While Jakarta Persistence and Jakarta NoSQL provide excellent solutions
for their respective database paradigms, applications increasingly need
to work with multiple data storage technologies. Enterprise architects
and developers face a familiar challenge: how to maintain consistent data
access patterns when using both relational and non-relational databases
side by side.
Jakarta Data, released in September 2024 as part of Jakarta EE
11, addresses this challenge by providing a unified, repository-based
abstraction layer that works with both Jakarta Persistence and Jakarta
NoSQL. It represents a significant evolution in Jakarta EE’s approach to
data access, focusing on simplicity, consistency, and productivity.
From Template Pattern to Repository Pattern
Jakarta Data builds on the DAO/repository concepts found in Jakarta
NoSQL’s Template pattern but takes them a step further. Instead of working
with implementation classes, Jakarta Data allows you to declare repository
interfaces with method signatures that express your intent. The framework
then automatically implements these interfaces at runtime.
259
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
This declarative approach reduces boilerplate code even further
than the Template pattern and creates a consistent programming model
regardless of the underlying database technology. The same repository
interface can be used whether your data lives in a relational database
through JPA, a document store via Jakarta NoSQL, or any other supported
database type.
Jakarta Data: Unifying Data Access
Jakarta Data 1.0, released in September 2024, represents a significant
evolution in how Jakarta EE applications interact with data stores. It
provides a higher-level, more streamlined way to define data access
operations using the repository pattern, unifying the approach across both
relational (JPA) and non-relational (NoSQL) databases.
Features of Jakarta Data
Designed with developer ergonomy in mind, Jakarta Data comes with the
following features:
1. Built-In Repository Interfaces: Jakarta Data provides
interfaces like DataRepository, BasicRepository, and
CrudRepository with common data access methods.
2. Query Methods: You can define query methods
using consistent naming patterns that Jakarta Data
will automatically implement.
3. Annotated Queries: For more complex queries, you
can use the @Query annotation with Jakarta Data
Query Language.
4. Pagination Support: Jakarta Data offers both offset­
based and cursor-based pagination strategies.
260
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
5. Persistence Agnostic: The same repository interfaces
can be implemented for different data stores,
including relational and NoSQL databases.
Repository Interfaces in Jakarta Data
Jakarta Data’s repository interfaces follow a flexible design that
accommodates different programming styles and preferences. You can
choose between using built-in repository supertypes or creating custom
repositories tailored to their domain language.
Built-In Repository Types
Jakarta Data provides a hierarchy of ready-to-use repository interfaces
that offer common data access patterns. These repository types can be
extended to significantly reduce the amount of boilerplate code you write.
These types are
•
DataRepository: The root interface providing minimal
functionality
•
BasicRepository: Offers fundamental operations like
finding, saving, and deleting entities
•
CrudRepository: Extends BasicRepository with explicit
create, read, update, and delete methods
Using the Built-In Repository Types
You can extend any of the three built-in repository types for your
application. Unless you have a very niche, custom application, you
generally will do fine by extending CrudRepository straightway as it’s the
most high-level and builds upon the other two. Listing 5-60 shows the
UserRepository extending CrudRepository.
261
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-60. UserRepository
@Repository(dataStore = "jdbc/jwallet-postgres")
public interface UserRepository extends
CrudRepository<User, Long> {
@Query(User.LOAD_ALL_USERS)
List<User> loadAllUsers();
List<User> findAllUsers();
User findUserByEmail(String email);
@Query(User.LOAD_USERS_BY_CONVERSIONS)
List<User> loadUsersByTotalConversion(BigDecimal
totalConversions);
List<User> finalAll();
}
The UserRepository extends CrudRepository, passing the entity type
and primary key type as the first and second arguments, respectively, to
the parameterized interface. The @Repository annotation marks the class
as a repository. The dataStore value is a way to tell the implementation
which data store to use. The above code passes a JNDI data source name as
the value. As this code is running in a Jakarta EE environment, the Jakarta
Data implementation is smart enough to know to use the given resource to
retrieve the needed connection to the underlying database.
The class has a number of methods with no implementation. The
Jakarta Data runtime will provide concrete implementations for these
methods at runtime. If you have used Spring Data JPA before, this is exactly
the same thing, but for Jakarta EE. Aside from the explicitly declared
methods, other methods from the super BasicRepository like save,
findById, deleteById, and findAll are also available.
262
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Keep in mind that your repository doesn’t have to have the word
repository in it. The UserRepository could be called UserController,
UserFacade, or UserService. The act of suffixing repository names with
repository is more a general convention than a rule. You’re free to use any
name with Jakarta Data.
Creating Custom Repositories
You do not have to extend from the built-in repositories. You can equally
create a custom repository that does not extend from any. This is useful
in projects where there are tighter restrictions on class inheritance.
Listing 5-61 shows an example custom UserController repository.
Listing 5-61. Custom UserController repository
@Repository(dataStore = "jdbc/jwallet-postgres")
public interface UserController {
@Insert
User createUser(User user);
@Update
User updateUser(User user);
@Save
void saveUser(User user);
@Delete
void removeUser(User user);
@Find
List<User> findUsersByAddress(Address address);
}
263
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The UserController is a custom repository that does not extend any of
the built-in repositories. Each of the methods is annotated with a lifecycle
annotation that denotes what the Jakarta Data implementation should
do with it. The @Insert annotation tells the implementation to insert the
given entity instance into the database; the @Update, to update; and the
@Save, to conditionally insert if the entity is not already in the database
and to update if it already is. The @Delete annotation deletes the given
entity from the database, and the @Find annotation creates a query
method that uses the passed parameter as the querying criteria.
As you can see, creating a custom repository is straightforward and
cleaner, with no need to extend any framework classes.
Querying in Jakarta Data
The Jakarta Data Query Language (JDQL) provides a streamlined
approach to querying data within Jakarta Data repositories via the @
Query annotation. It is a subset of JPQL, designed for broad compatibility
across different data storage technologies. A core principle is the single­
entity FROM clause, simplifying query structure. JDQL supports standard
Java types, ensuring portability. Expressions are evaluated with Java-like
semantics, though data store variations may occur.
Conditional expressions, including null checks, IN, BETWEEN, LIKE,
and comparison operators, enable reliable filtering. Logical operators
(AND, OR, NOT) allow complex condition construction. JDQL statements
are built with clauses like FROM, WHERE, SELECT, SET, and ORDER
BY. Built-in functions, and potential provider-specific ones, support data
manipulation.
JDQL offers SELECT, UPDATE, and DELETE statements, supporting
named and ordinal parameters for security and flexibility. The COUNT
aggregate function counts matching records, and ORDER BY sorts results.
Listing 5-62 shows the custom UserController repository with some JDQL
methods.
264
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Listing 5-62. JDQL in the custom UserController repository
@Repository(dataStore = "jdbc/jwallet-postgres")
public interface UserController {
@Insert
User createUser(User user);
@Update
User updateUser(User user);
@Save
void saveUser(User user);
@Delete
void removeUser(User user);
@Find
List<User> findUsersByAddress(Address address);
@Query("FROM User WHERE userName = :userName")
List<User> findUsersByName(String userName);
@Query("SELECT u.address.city FROM User u WHERE u.address.
zip = :postalCode")
List<String> findCitiesByPostalCode(String postalCode);
@Query("SELECT COUNT(this) FROM User WHERE address.city
= :city")
long countUsersInCity(String city);
@Query("FROM User WHERE :phoneNumber IN address.
phoneNumbers")
List<User> findUsersByPhoneNumber(String phoneNumber);
265
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
@Query("FROM User WHERE address.street LIKE
:streetPattern")
List<User> findUsersByStreetPattern(String streetPattern);
@Query("FROM User ORDER BY lastName ASC")
List<User> findAllUsersOrderedByName();
@Query("UPDATE User SET firstName = :newName WHERE id =
:userId")
long updateUserName(String userId, String newName);
@Query("DELETE FROM User WHERE id = :userId")
long deleteUserById(Long userId);
}
The @Query annotation is the entry point to creating queries with
JDQL. As stated above, JDQL is a subset of JPQL. The various queries in the
example above are very much self-explanatory as we have covered JPQL
earlier in this chapter.
Integration with Jakarta Persistence
and Jakarta NoSQL
Jakarta Data doesn’t replace Jakarta Persistence or Jakarta NoSQL—it
complements them by providing a unified API that can work with either.
The intention of Jakarta Data is to have a single set of interfaces and
methods that works regardless of whether the underlying implementation
uses JPA or Jakarta NoSQL. Thus, all the repositories discussed so far in the
previous section should work out of the box, irrespective of the underlying
database paradigm the application uses.
266
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Comparing Persistence Options
Table 5-1 shows a feature comparison matrix between the three
data-related specifications—Jakarta Persistence, Jakarta NoSQL, and
Jakarta Data.
Table 5-1. Feature Comparison
Feature
Jakarta
Jakarta NoSQL
Jakarta Data
Persistence
Database type
Relational
Non-relational
Both (via JPA/NoSQL)
Primary focus
ORM
NoSQL access
Repository pattern
Schema
Fixed schema
Schema-flexible
Depends on the
requirements
Query language
underlying store
JPQL, Criteria API
Native NoSQL
JDQL
queries
Transaction
Full
Varies by database
support
Inherits from the
underlying provider
Portability Considerations
Jakarta Data offers varying degrees of portability across different database
types, ensuring that you can use its features while working with your
preferred database technology. However, it’s essential to be aware of the
specific support levels for each database category:
•
Relational Databases: Jakarta Data provides
comprehensive support for relational databases,
encompassing all the fundamental CRUD (create,
read, update, delete) operations. Additionally, it
facilitates advanced features like pagination (handling
267
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
large datasets by dividing them into pages) and
sorting (ordering data based on specified criteria).
This comprehensive support makes Jakarta Data an
excellent choice for applications built on relational
database systems.
268
•
Document Databases: While not as extensive as
relational database support, Jakarta Data still offers
substantial compatibility with document databases.
Most query operations are supported, allowing you to
retrieve and manipulate data effectively. Furthermore,
Jakarta Data enables complex querying in document
databases, allowing for the crafting of sophisticated
queries to extract valuable insights.
•
Column-Family Databases: Jakarta Data provides
basic query support for column-family databases.
However, it’s important to acknowledge that certain
limitations exist. You might encounter restrictions
when performing specific query operations or using
advanced features. You should consult the Jakarta Data
documentation for detailed information on column­
family database support.
•
Key-Value Databases: Due to the inherent nature of
key-value databases, Jakarta Data’s support is limited
to key-based access operations. This means that data
retrieval and manipulation are primarily based on
keys. While this might restrict certain use cases, key­
value databases can still be used effectively for specific
scenarios within the Jakarta Data framework.
CHAPTER 5
•
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Graph Databases: Jakarta Data offers support for
graph databases through built-in repositories. These
repositories provide convenient mechanisms for
interacting with graph data. However, some query
method limitations exist. You might find that certain
graph-specific query operations are not directly
supported. It’s advisable to explore alternative
approaches or consider specialized graph database
libraries if advanced graph querying is required.
When to Use Different Jakarta
Database Technologies
The Jakarta data-related technologies aren’t mutually exclusive—they can
work together in the same application. Jakarta Data can serve as a higherlevel abstraction over both JPA and Jakarta NoSQL implementations,
providing a unified programming model while letting you harness the
specific strengths of each underlying technology.
Many enterprise applications benefit from this combined approach,
using JPA for transaction-heavy relational data operations while using
Jakarta NoSQL for high-throughput data streams or document storage
needs. Jakarta Data’s repository interfaces can integrate with both, creating
a cohesive data access layer across diverse persistence requirements.
The flexibility to mix these technologies will allow teams to select the
right tool for each specific data access pattern without committing to a
single approach throughout the application. This pragmatic strategy helps
optimize performance, maintainability, and developer productivity across
different parts of your system. Table 5-2 presents a matrix of when to pick
which database type.
269
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Table 5-2. When to Pick Which Data Technology
Technology
Best Used When
Key Advantages
Ideal Scenarios
Jakarta
• Working primarily
• Mature, well-
• Enterprise
Persistence
with relational
established
applications with
(JPA)
databases
standard
complex data
• Need fine-grained
• Rich relationship
control over entity
mapping
mappings
capabilities
• Handling complex
query requirements
• Building on existing
JPA entity models
models
• Systems with
strict data integrity
• Powerful JPQL
requirements
and Criteria API
• Applications
• Strong
transaction
needing detailed
query optimization
support
Jakarta
NoSQL
• Working primarily with • Native support
NoSQL databases
• Data models align
with document,
• High-volume
for multiple
applications
NoSQL
requiring
paradigms
horizontal scaling
key-value, column, or • Better schema
• Projects with
graph databases
flexibility
• Need to use specific
• Horizontal
models
NoSQL database
scaling
• Real-time
features
advantages
analytics or
• High scalability
• Optimized for
processing
requirements
non-relational
systems
data structures
• Document-
evolving data
oriented
applications
(continued)
270
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Table 5-2. (continued)
Technology
Best Used When
Jakarta Data • Need unified data
access across
Key Advantages
Ideal Scenarios
• Reduces
• Microservices with
boilerplate code
database technologies • Consistent API
• Want cleaner, more
declarative data
access code
• Value database
portability
across data
stores
• Declarative
query definition
• Easier
• Focus on rapid
testing and
development
maintenance
mixed database
needs
• Projects requiring
future database
flexibility
• Teams focused on
Domain-Driven
Design
• Rapid prototyping
and development
Summary
This chapter has provided a thorough exploration of data persistence
in Jakarta EE, exploring how enterprise applications can model, store,
and retrieve data using various specifications. We started with Jakarta
Persistence (JPA), which offers a standardized approach for mapping Java
objects to relational databases, solving the object-relational impedance
mismatch while abstracting database-specific details.
We saw how JPA’s annotation-based model transforms plain Java
objects into fully mapped database entities. The chapter showed entity
modeling with primary keys, custom columns, and data type mappings,
followed by establishing relationships between entities using associations
like one-to-one, one-to-many, and many-to-many.
271
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
The EntityManager, we saw, is the central component for persistence
operations, working within a persistence context to manage entity
lifecycles. We explored persistence operations, transaction handling,
cascading changes across relationships, and implementing callback
methods to handle entity lifecycle events.
Beyond basic persistence, the chapter examined two approaches
to data retrieval: Jakarta Persistence Query Language (JPQL) for string­
based queries and the Criteria API for type-safe, programmatic query
construction. Both approaches demonstrated how JPA provides Java­
friendly querying capabilities that get translated to the underlying
database’s SQL dialect.
The discussion expanded to non-relational databases with Jakarta
NoSQL, showcasing how it provides standardized access across key-value,
document, column-family, and graph databases. Finally, we explored
Jakarta Data, which unifies data access across both relational and non­
relational paradigms through a repository pattern that reduces boilerplate
code and increases productivity.
Key Takeaways
1. JPA Fundamentals: JPA uses annotations to map
Java classes to database tables, solving the objectrelational impedance mismatch while abstracting
database specifics.
2. Entity Modeling: The chapter explains how to create
entities with primary keys, customize columns,
map various data types, and establish relationships
between entities.
272
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
3. Entity Relationships: Four types of relationships are
covered: one-to-one, one-to-many, many-to-one,
and many-to-many, along with collection-valued
relationships.
4. Data Persistence: The EntityManager interface
manages the persistence context and handles
database operations within transactions.
5. Querying Options: Two main approaches for
retrieving data are presented—Jakarta Persistence
Query Language (JPQL) and the Criteria API.
6. Jakarta NoSQL: This specification offers a
standardized approach for interacting with NoSQL
databases across four categories: key-value,
document, column-family, and graph databases.
7. Jakarta Data: This newer specification provides a
unified repository pattern that works across both
relational and non-relational databases, simplifying
data access with declarative interfaces.
8. Technology Selection: The chapter concludes with
guidance on when to use each specification based
on project requirements—JPA for relational data
with complex models, Jakarta NoSQL for schema­
flexible non-relational data, and Jakarta Data for
unified access across database technologies.
273
CHAPTER 5
PERSISTENCE WITH JAKARTA EE PERSISTENCE
Having established how to persist and retrieve data, we’ll now focus on
exposing this data through standardized web APIs. Jakarta REST provides
an annotation-based model for creating RESTful services that integrate
with the persistence layer we’ve just examined. We’ll learn how to design
resource-oriented APIs, implement HTTP methods, and create both server
and client components—connecting our data layer to the outside world
through modern web interfaces.
274
CHAPTER 6
REST with Jakarta
REST
Jakarta REST (formerly JAX-RS) is the standard API for building RESTful
web services in the Jakarta EE platform. At its core, Jakarta REST
transforms plain Java classes into web resources through a powerful
but straightforward annotation-based programming model. This allows
developers to create maintainable, scalable HTTP-based services that
seamlessly integrate with the broader Jakarta EE ecosystem.
Modern enterprise applications demand flexible, interoperable APIs
that can serve diverse clients—from web browsers and mobile apps
to microservices and IoT devices. Jakarta REST meets these needs by
providing
•
Platform independence through standard HTTP
communication
•
Declarative resource definition using annotations
•
Automatic content negotiation and data binding
•
Native integration with Jakarta CDI, Security, and
Validation
•
Built-in support for common web service patterns
•
Type-safe client APIs for consuming REST services
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_6
275
CHAPTER 6
REST WITH JAKARTA REST
Standardizing REST development on the Jakarta EE platform allows
teams to focus on business logic rather than low-level HTTP handling and
data transformation.
By the end of this chapter, you will be able to
•
Design REST resources that follow standard
architectural principles and patterns.
•
Create resource classes using Jakarta REST annotations
to handle HTTP methods.
•
Implement content negotiation to support multiple
data formats.
•
Validate incoming requests using Jakarta Bean
Validation.
•
Handle exceptions and errors using ExceptionMappers.
•
Build type-safe REST clients using both Jakarta REST
Client and MicroProfile REST Client.
•
Test REST services using modern testing frameworks.
•
Deploy REST applications to Jakarta EE servers.
Modeling REST Services
A well-designed REST API starts with careful resource modeling. Before
writing any code, careful thought must be given to how domain objects
map to HTTP resources in order to design an API that is intuitive,
maintainable, and follows REST principles.
276
CHAPTER 6
REST WITH JAKARTA REST
Core REST Architectural Principles
REST architecture, as originally propounded by Dr. Roy Fielding, refined
over the years, builds on several key principles that guide how we expose
and interact with resources over the Internet. These principles include the
following.
Statelessness
Statelessness is perhaps the most fundamental principle. Each request to a
REST service must contain all information needed to process it—the server
should not rely on stored client context. This enables horizontal scaling,
as any server can handle any request. For example, instead of storing user
preferences in a server session, a REST service should require the client to
send preferences with each relevant request.
Resource-Based Design
Resource-based design treats everything as a named resource that can
be manipulated through standard HTTP methods. A resource could be
a physical object (a product), an abstract concept (a shopping cart), or
a calculation (currency conversion). The API reflects these resources
in its URLs—for example, /api/products/electronics rather than /api/
getElectronicProducts.
Cacheability
Cacheability requires responses to define themselves as cacheable or
non-cacheable. Using HTTP caching headers, REST services can improve
performance and reduce server load. Frequently accessed but rarely
changed resources like product catalogs are ideal candidates for caching.
Currency conversion rates, on the other hand, require new updates and
thus are not ideal candidates for caching.
277
CHAPTER 6
REST WITH JAKARTA REST
HATEOS
HATEOS (Hypermedia as the Engine of Application State) suggests that
responses include links to related resources. This allows clients to discover
API capabilities dynamically rather than having URL patterns hardcoded.
For example, an order response might include links to its associated
customer, line items, and available actions like cancel or ship.
With these architectural principles in mind, let’s examine how to name
and structure REST resources. Clear, consistent naming patterns help
create intuitive APIs that clients can easily understand and consume.
Resource Naming Patterns
Clear and consistent resource naming is important for API usability.
Adherence to established patterns promotes clarity and predictability,
making an API easier to understand and consume. The following
subsections contain guidelines to help you design consistent APIs that
adhere to well-established REST patterns in the industry.
Use Plural Nouns for Collections
This convention clearly distinguishes between individual resources and
collections of resources. For example, /customers refers to the collection
of all customers, while /customers/123 pinpoints a specific customer with
the ID 123 within the collection of customers. /customers/123/orders
then points to the orders of the customer with ID 123 within the customers
collection. This approach enhances readability and reduces ambiguity
when interacting with your API. This approach makes your API self­
documenting to other developers that interact with it.
278
CHAPTER 6
REST WITH JAKARTA REST
Use URL Paths
Express hierarchical relationships through URL paths by structuring your
URLs to reflect the relationships between resources. This hierarchical
approach enhances the intuitiveness of your API and allows developers
to easily grasp the connections between different entities. For instance,
/departments/5/employees clearly indicates a relationship between a
specific department (ID 5) and its employees.
Use Query Parameters for Metadata
Use query parameters for filtering, sorting, and pagination as they provide
a flexible mechanism for refining resource retrieval. They allow clients to
specify criteria for selecting, ordering, and paginating resources, enabling
efficient and targeted data retrieval. For example, /products?category=ele
ctronics&sort=price&page=2 retrieves the second page of products in the
“electronics” category, sorted by price.
Anti-patterns toAvoid
While established patterns guide toward clean API design, it’s equally
important to recognize common pitfalls. The following are some REST
anti-patterns that should be avoided.
Exposing Implementation Details
Resource URIs should represent resources, not underlying implementation
details. Avoid exposing database operations or internal technical
mechanisms within your URL structure. For example, GET /users/
delete?id=123 exposes the database operation “delete” directly in the
URL. A better approach would be an HTTP DELETE endpoint such as /
users/123.
279
CHAPTER 6
REST WITH JAKARTA REST
Inconsistent Resource Naming
Maintain consistency in your naming conventions. Inconsistencies, such
as mixing singular and plural forms, introduce confusion and erode
predictability. It can also make maintaining and evolving your APIs
difficult.
Deep Nesting
Avoid excessive nesting of resources within your URL structure. Deeply
nested URLs become unwieldy and difficult to read and tightly couple
resources. For example, an endpoint like /customers/123/orders/456/
items/789/variants should be broken down into two or more independent
resources.
Verb-Based Actions
HTTP methods (GET, POST, PUT, DELETE) already provide the verbs for
your API. Avoid redundancy by excluding verbs from your URL design.
Even with careful attention to resource modeling and anti-patterns,
your API will need to grow and adapt over time. New product requirements
emerge, business rules and objectives change, and established patterns
evolve. Let’s explore strategies for designing APIs that can accommodate
these inevitable changes.
Designing forEvolution
Your APIs will need to evolve over time to accommodate new
requirements, changing business needs, and technological advancements.
These changes should be anticipated by designing your APIs with
flexibility and extensibility in mind. This proactive approach will help you
avoid disrupting existing clients while providing a smooth path for future
enhancements.
280
CHAPTER 6
REST WITH JAKARTA REST
Versioning
Explicitly version your API to accommodate future modifications without
disrupting existing clients. Versioning allows you to introduce breaking
changes while maintaining backward compatibility for consumers relying
on older versions. A common approach is to include the version number in
the URL, for example, /api/v1/customers and /api/v2/customers.
Response Encapsulation
Use response wrappers to encapsulate data and provide a consistent
structure for future additions. This technique allows you to add new
attributes or metadata to your responses without altering the fundamental
structure that clients expect. This can be achieved with a generic type, as
shown in Listing 6-1.
Listing 6-1. An example of encapsulated API response
public class ApiResponse<T> {
private T data;
private MetaData metadata;
private List<Link> links;
}
The above example shows an ApiResponse class used to encapsulate
API responses. It includes fields for the response data (of generic type T),
metadata, and related links, providing a consistent structure for API
responses and allowing for future extensibility without breaking client
compatibility.
281
CHAPTER 6
REST WITH JAKARTA REST
Content Negotiation
Design your APIs to support multiple content types (e.g., JSON, XML)
to cater to different client needs and preferences. Content negotiation
allows clients to request the representation that best suits their processing
capabilities, enhancing interoperability. This is often achieved using the @
Produces annotation in Jakarta REST.
Having established principles for API design and evolution, let’s
apply these concepts to a practical example in the sample app for this
book, jwallet. We’ll model a User resource, expanding on the User entity
introduced in Chapter 5.
Modeling the User Resource
The User API needs to support standard operations like creation, updates,
and deletion, along with more specialized search capabilities. Following
the resource naming patterns and REST principles established in the
previous sections, these business requirements can be mapped to HTTP
endpoints as shown in Table 6-1.
Table 6-1. The Various Actions Mapped to HTTP Paths and Their
Corresponding HTTP Methods
Action
HTTP Path
Method
Return Type
Create user
/users
POST
Created user
Update user
/users
PUT
Updated user
Find by ID
/users/{userId}
GET
User or exception
List all users
/users
GET
List of users
Search users
/users/search
GET
List of users
Find by conversion threshold
/users/{threshold}
GET
List of users
Delete user
/users
DELETE
Void
282
CHAPTER 6
REST WITH JAKARTA REST
Notice how these endpoints align with the earlier design principles
discussed in the previous section:
•
Resource names use plural nouns (/users).
•
Path parameters capture variables ({userId},
{threshold}).
•
HTTP methods match their standard meanings.
•
Search operations use query parameters.
Resource Organization
In practice, REST resources should be organized hierarchically with
a common base path. This base path serves as the root for all related
endpoints. The users endpoint shown in Table 6-1, therefore, will be
accessible through the base path /api/v1/users. Of course the base path is
a project-specific value. Some projects use api/{versionNumber}, others
use the tenant, and still others use specific project values. Whatever the
base path, it should be a logical, hierarchical grouping of the resources in
the application.
This hierarchical organization
•
Groups related functionality
•
Enables versioning
•
Simplifies API gateway configuration
•
Makes the API more discoverable
In the next section, we’ll implement these endpoints using Jakarta
REST annotations, showing how the specification transforms these designs
into working code.
283
CHAPTER 6
REST WITH JAKARTA REST
The Root Resource
In Jakarta REST, the root resource, or base path, is defined as a subclass of
the jakarta.ws.rs.core.Application class. Listing 6-2 shows the root resource
declaration for the jwallet application.
Listing 6-2. Root resource declaration
@ApplicationPath("api/v1")
public class RestApplicationConfiguration extends Application {
}
The root resource class is declared as a subclass of the Application
class. This class contains three methods that can be overridden to
explicitly register resource classes, extensions, and properties.
The class is annotated @ApplicationPath and passed the value “api/v1”.
The value passed to annotation defines the root resource or base path for
the application. All resources in the application will be accessed through
the base or root path /api/v1.
API Versioning with getClasses
As stated in the “Design for Evolution” section, versioning of APIs is
important for maintainability and evolvability of the application. The
Application class’s getClasses method can be used to logically group
resource classes in a Jakarta REST application. This logical grouping can
act as the basis for API versioning. For example, the REST configuration
class shown in Listing 6-2 can group the v1 REST classes of the application
as shown in Listing 6-3.
284
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-3. REST config with specific resource classes
@ApplicationPath("api/v1")
public class RestApplicationConfiguration extends Application {
@Override
public Set<Class<?>> getClasses() {
return Set.of(UserResource.class);
}
}
The RestApplicationConfiguration overrides the getClasses method
to return the UserResource class. The UserResource class, then, will be
accessible via api/v1/users.
When requirements evolve and there is a need to have major breaking
changes in the REST contract, but still keep backward compatibility with
older versions—an occurrence much too common in non-trivial enterprise
applications—then a new REST configuration can be created to logically
group the newer resources, as shown in Listing 6-4.
Listing 6-4. The second version of the UserResource
@ApplicationPath("api/v2")
public class RestApplicationConfigurationV2 extends
Application {
@Override
public Set<Class<?>> getClasses() {
return Set.of(UserResourceV2.class);
}
}
285
CHAPTER 6
REST WITH JAKARTA REST
The RestApplicationConfigurationV2 sets the base path to api/v2,
overriding the getClasses method to return a set of resources that are part
of the new changes, in this example UserResourceV2. Thus, all resource
methods in UserResourceV2 will be accessible via the path api/v2/users/.
The versioning strategy using multiple Application classes provides a
clean separation between API versions. While this handles the high-level
organization of the API resources, we need to define the actual resource
classes that implement the business functionality. Let’s examine how to
create these resource classes using Jakarta REST annotations, starting
with the UserResource that implements the endpoints defined earlier in
Table 6-1.
A REST resource class serves as the bridge between HTTP requests
and your application’s business logic. Each resource class maps URLs to
specific methods that handle create, read, update, and delete operations.
The UserResource we’ll examine demonstrates these mappings
while adhering to the REST principles and resource naming patterns
established above.
A Jakarta REST Resource
In Jakarta REST, a REST resource is a Java class with a path corresponding
to an HTTP path. This class is then hosted at that path. Listing 6-5
introduces the UserResource class, which implements the resources
defined in Table 6-1.
Listing 6-5. The first UserResource class
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("users")
public class UserResource {
286
CHAPTER 6
REST WITH JAKARTA REST
@Inject
SimpleUserService userService;
}
Though the UserResource class doesn’t contain any resource methods
yet, it shows a number of key Jakarta REST annotations that transform a
standard Java class into a REST endpoint.
The @Path(“users”) annotation specifies where this resource will be
hosted in the URL hierarchy. Combined with the base path /api/v1 defined
in our RestApplicationConfiguration, this creates the full endpoint path /
api/v1/users.
The @Consumes and @Produces annotations declare that this
resource works with JSON data. Both are set to MediaType.APPLICATION_
JSON (which resolves to the MIME type application/json), indicating that
the methods in this class will accept and return JSON data. This aligns with
modern web and microservices architectures, where JSON has become the
standard data exchange format.
When a client makes a request to /api/v1/users, the Jakarta REST
runtime instantiates the UserResource class to handle the request. The
@Inject annotation shows that this resource integrates with Jakarta CDI
(covered in Chapter 4), allowing a clean separation of the REST interface
(or layer) from the business logic in SimpleUserService.
In the next section, we’ll add resource methods to handle specific
HTTP operations as mapped out in Table 6-1.
HTTP Methods
With the resource class in place, we can start implementing the HTTP
methods shown in Table 6-1. A resource method in Jakarta REST is a Java
method annotated with any of the requisite annotations denoting the
HTTP method the Java method responds to. There are seven annotations
287
CHAPTER 6
REST WITH JAKARTA REST
that map to the corresponding HTTP methods for creating resource
methods. These are @POST, @GET, @PUT, @DELETE, @PATCH, @HEAD,
and @OPTIONS.
@POST
The @POST annotation on a resource class method denotes the method
as responding to HTTP POST requests. Listing 6-6 shows the createUser
method in the UserResource class annotated @POST.
Listing 6-6. @POST method
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("users")
public class UserResource {
@Inject
SimpleUserService userService;
@POST
public UserResponse createUser(CreateUserRequest
createUserRequest) {
return userService.createUser(createUserRequest);
}
}
The @POST annotation marks this method as the handler for HTTP
POST requests. Since no method-level @Path is specified, this endpoint
maps to /api/users—inheriting the path from the class-level annotation.
The Jakarta REST runtime manages the complete request lifecycle.
When a client sends a POST request to /api/users, the runtime
288
CHAPTER 6
REST WITH JAKARTA REST
1. Receives the incoming JSON payload
2. Converts the JSON into a CreateUserRequest object
using its message body reader system
3. Invokes the createUser() method with the
converted object
4. Transforms the returned UserResponse back
into JSON
The class-level annotations @Consumes and @Produces declare that
the methods in this class work with JSON data. Clients send JSON in their
requests and receive JSON responses, while the code works with strongly
typed Java objects.
This clean separation between transport concerns (HTTP, JSON, etc.)
and business logic (Java code) is a core strength of Jakarta REST. It handles
all JSON conversion automatically, letting you focus on implementing the
actual resource creation logic. How, though, does it handle the conversion
from and to JSON?
Message Body Readers
A message body reader is an instance of the parameterized jakarta.ws.rs.
ext.MessageBodyReader<T> interface that takes the InputStream of a
MediaType and converts it to T, where T is some Java type. Each message
body reader is associated with a single MediaType whose InputStream
it can transform into a Java type. Jakarta REST ships with a number of
message body readers for the popular MediaTypes such as JSON and
XML. You do not need to provide an instance of the MessageBodyReader
for any of the ones that Jakarta REST ships by default, unless you want
to customize the conversion process or need to map from and to a
custom format, like YAML. Listing 6-7 shows a sample body reader
implementation that reads and converts from YAML to Java types.
289
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-7. A custom body reader for YAML
@Provider
@Consumes("application/x-yaml")
public class CustomYamlReader<T> implements
MessageBodyReader<T> {
@Inject
Yaml yaml;
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return "application/x-yaml".equalsIgnoreCase(mediaType.
toString());
}
@Override
public T readFrom(Class<T> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream
entityStream)
throws IOException, WebApplicationException {
var inputString = new String(entityStream.readAllBytes());
return yaml.loadAs(inputString, type);
}
}
CustomYamlReader implements the MessageBodyReader for YAML,
denoted by the @Consumes(“application/x-yaml”) annotation. The @
Provider annotation automatically registers this provider with the Jakarta
REST runtime. The isReadable method first checks if an incoming request
has the MIME type application/x-yaml. If this check passes, the readFrom
290
CHAPTER 6
REST WITH JAKARTA REST
method proceeds. It uses a custom YAML controller to convert the request
body’s input stream into the required Java object type. Message body
readers allow for fine-grained control over the entire unmarshalling
process. The counterpoint to the message body readers are message body
writers.
Message Body Writers
A message body writer is the opposite of a message body reader in that it
takes a Java type and converts it to the type represented by the MediaType
it is associated with. The message body writer takes the Java type instance
and writes it to the OutputStream that is returned to the client. Similar to
the body reader, you generally will only provide your own custom writer
implementation when you need to do some customization of the process
or return custom MIME types with no default writer. Listing 6-8 shows the
YAML message body writer.
Listing 6-8. A custom message body writer for YAML
@Provider
@Produces("application/x-yaml")
public class CustomYamlWriter<T> implements
MessageBodyWriter<T> {
@Inject
Yaml yaml;
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return "application/x-yaml".equalsIgnoreCase(mediaType.
toString());
}
291
CHAPTER 6
REST WITH JAKARTA REST
@Override
public void writeTo(T t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream
entityStream)
throws IOException, WebApplicationException {
var outputStreamWriter = new OutputStreamWriter(entityStream);
yaml.dump(t, outputStreamWriter);
outputStreamWriter.close();
}
}
Similar to the reader, the CustomYamlWriter is annotated
@Provider to register it with the Jakarta REST runtime automatically.
As a MessageBodyWriter implementation, it is annotated
@Produces(“application/x-yaml”) to associate it with the writing of the
passed MIME type, in this example, YAML. The isWriteable method,
similar to the isReadable of the reader implementation, checks if the
outgoing request MediaType is YAML. If yes, then the writeTo method
takes the Java type, converts it to YAML using the custom YAML controller,
and writes it to the passed OutputStream being sent to the client.
As stated, Jakarta REST provides default message body reader and
writer implementations for several media types. For the createUser
method in the UserResource class, the request body will be automatically
mapped from JSON to the CreateUserRequest Java type.
However, if the calling client does not pass any body in the request,
then the CreateUserRequest will resolve to null, as there’s no value to
instantiate it to. To prevent such occurrences and avoid unnecessary null
checks, Jakarta REST integrates with Jakarta Bean Validation to make the
validation of resource requests automatic.
292
CHAPTER 6
REST WITH JAKARTA REST
Validating Resources
As discussed in Chapter 5, the Bean Validation specification is a set of
annotations and interfaces that you can use to constrain values to only
what an application requires. To prevent the client from passing null or
invalid values for user creation, Listing 6-9 shows the createUser method
with validation constraints.
Listing 6-9. Bean validation
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("users")
public class UserResource {
@Inject
UserService userService;
@POST
public UserResponse createUser(@NotNull
@Valid CreateUserRequest createUserRequest) {
return userService.createUser(createUserRequest);
}
}
The two constraint annotations, @NotNull and @Valid, will cause
the method parameter to be validated. It first will validate that the
converted POST body is not null. Then it will cause a recursive validation
of the converted object. In this case, all constrained fields on the
CreateUserRequest will be validated. The method body will only be
executed when there is no validation exception. If there is a validation
293
CHAPTER 6
REST WITH JAKARTA REST
exception resulting from a constraint violation, the REST runtime will send
HTTP 400 (Bad Request) to the client. The CreateUserRequest is shown in
Listing 6-10 with validation constraints.
Listing 6-10. Updated CreateUserRequest
public class CreateUserRequest {
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
@NotEmpty
@Email
private String email;
@NotNull
@Past
private LocalDate birthDay;
private UserRegion userRegion;
@NotEmpty
@Size(min = 8, max = 30)
private String password;
}
Because the createUser method did not explicitly declare any
resource paths with the @Path annotation as done on its class, Jakarta
REST knows to call it when a POST request is made to the parent /users
path as declared by the @Path annotation on the class. Only one each of
the HTTP methods is allowed to be hosted in a class without an explicit
@Path annotation. If another @POST method is declared without a
@Path annotation in the same UserResource class, this will be an error.
294
CHAPTER 6
REST WITH JAKARTA REST
A sample POST request to the /users path with valid data as shown
returns the JSON data shown in Listing 6-11.
Listing 6-11. Successful call to the /users resource
http://localhost:3003/account/api/users
HTTP/1.1 200 OK
Content-Type: application/json
Content-Language: en-US
Content-Length: 114
Date: Fri, 26 Aug 2022 17:08:13 GMT
{
"data": {
"firstName": "John",
"lastName": "Jakes",
"userId": 5
},
"response": {
"responseCode": "0",
"responseMessage": "OK"
}
}
The response header generated by the Jakarta REST runtime contains
some metadata about the response. It shows the HTTP version used and
the response code, which in this successful invocation is 200. The returned
JSON in the response body is a representation of the UserResponse
object returned by the createUser method. Listing 6-12 shows the
UserResponse object.
295
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-12. The UserResponse class
public class UserResponse extends Response<UserResponse.
UserResponseData> {
public static UserResponse of(UserResponseData data) {
UserResponse userResponse = new UserResponse();
userResponse.setData(data);
return userResponse;
}
@Getter
@Setter
public static class UserResponseData {
private Long userId;
private String firstName;
private String lastName;
private String username;
}
}
The call to the /users resource method with the request shown in
Listing 6-13 will result in an HTTP response code 400 because the data is
not correct. As the request object is being validated with the @Valid and
@NotNull annotations, Jakarta REST will automatically validate the
request and return the appropriate response.
Listing 6-13. Calling /users with bad data
POST http://localhost:3003/account/api/users
Content-Type: application/json
{
296
CHAPTER 6
REST WITH JAKARTA REST
"firstName":"John",
"lastName":"Jakes",
"userRegion":"AFRICA",
"birthDay":"08-02-1975",
"password":"_myStrong_pswd& A_r'
}
The request data misses the email field, which is annotated @
NotEmpty in the CreateUserRequest. The above call results in the response
shown in Listing 6-14.
Listing 6-14. Response data
http://localhost:3003/account/api/users
HTTP/1.1 400 Bad Request
Content-Type: text/plain;charset=UTF-8
validation-exception: true
Content-Language: en-US
Content-Length: 60
Connection: Close
Date: Fri, 26 Aug 2022 17:35:41 GMT
This is automatic and only requires you to annotate your fields with
the relevant Jakarta Bean Validation annotations. A POST method does
not necessarily need to return data. The createUser method could as well
return void. What a resource method returns is a business domain decision
that will be made on a case-by-case basis.
@GET
Creating a method that responds to the HTTP GET request entails
annotating a Java method with the @GET annotation. There are four GET
requests in the list of resource methods shown in Table 6-1. Three of those
297
CHAPTER 6
REST WITH JAKARTA REST
return collections of users. When you have such similar return types for
different resource methods, it is an indicator to refactor the endpoints to
simplify them. This also helps in adhering to the resource naming patterns
of using query parameters.
Looking again at Table 6-1, the endpoint to search for users and to
filter users by total conversions can be combined into one. So the search
endpoint supports filtering or searching for users by total currency
conversions. This way, the search endpoint can be expanded such that you
can filter by conversions based on a predicate like greater than or equal to,
less than or equal to, and such. With this new approach, we end up with
three GET requests—one for getting a user by ID, one for getting all users,
and another for searching. Listing 6-15 shows the first attempt at crafting
the GET requests for the UserResource.
Listing 6-15. GET requests for users
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("users")
public class UserResource{
@Inject
UserService userService;
@GET
@Path("{userId}")
public UserResponse getUser(@PathParam("userId") Long
userId) {
return userService.getUser(userId);
}
@GET
@Path("search")
298
CHAPTER 6
REST WITH JAKARTA REST
public List<UserResponse> searchUsers(@NotNull @BeanParam
UserSearchRequest userSearchRequest) {
return userService.searchUsers(userSearchRequest);
}
@GET
public List<UserResponse> getAllUsers() {
return userService.getAllUsers();
}
}
@PathParam
The @PathParam annotation is used to capture variable parts of a resource
path in Jakarta REST. For example, in a method like getUser(Long userId),
the @PathParam annotation on the userId parameter corresponds to the
variable {userId} defined in the method’s @Path annotation (e.g., @Path
(“/api/v1/users/{userId}”)). When a request comes in for /api/v1/users/1,
the value 1 is extracted from the path and injected into the userId
parameter.
A resource path can include multiple path parameters (e.g., /{param1}/
{param2}/{param3}). However, if the same variable name is used multiple
times (e.g., /{same}/{same}), the last match will be the value injected for
all instances of @PathParam. For example, with the path /foo/bazz and the
variable {same}, the value “bazz” would be used.
The @Path annotation also allows the use of regular expressions to
constrain the characters allowed in the path. The method parameter can
be further constrained using annotations such as @NotNull.
Like the POST method, the return type of methods using @PathParam
will be automatically converted to its JSON representation due to the @
Produces(“application/json”) annotation on the class. This JSON is then
returned to the client.
299
CHAPTER 6
REST WITH JAKARTA REST
@BeanParam and@QueryParam
The /api/v1/users/search path hosts the searchUsers resource method.
This method accepts a UserSearchRequest object and returns a list of
UserResponses. The @BeanParam annotation, used for aggregating
resource parameters, annotates the method parameter. The annotated
UserSearchRequest class is shown in Listing 6-16.
Listing 6-16. UserSearchRequest
public class UserSearchRequest implements Serializable {
@QueryParam("firstName")
private String firstName;
@QueryParam("lastName")
private String lastName;
@QueryParam("totalConversions")
private BigDecimal totalConversions;
@QueryParam("conversionFilter")
private ConversionFilter conversionFilter = ConversionFilter.EQ;
@QueryParam("userType")
private UserType userType;
public enum ConversionFilter {
GT,
GTE,
LT,
LTE,
EQ,
NEQ
}
}
300
CHAPTER 6
REST WITH JAKARTA REST
The @QueryParam annotation binds HTTP query parameter values to
annotated fields in the UserSearchRequest class. This annotation can be
used on method parameters as well as fields, like @PathParam. When used
with @BeanParam on a method parameter (as in Listing 6-16), all query
parameters for the search resources are collected at runtime and injected
into an instance of this class, which is then passed to the method.
For instance, the HTTP GET request /api/users/search?firstName=Joe
&conversionFilter=GTE results in creating a UserSearchRequest instance
with firstName set to “Joe” and conversionFilter set to “GTE.” @BeanParam
allows you to abstract all possible query parameters into an object (as
done with the searchUsers method), which is very useful for creating
search-type resources, rather than using numerous method parameters.
While this is enough for simple cases, you might encounter large
datasets when returning a list. Returning everything at once is inefficient
for both client and server. Paging is more efficient in such cases. Pagination
would require the client to pass a limit (the maximum data per page) and
an offset. The returned data would also include metadata, such as the total
number of elements. Listing 6-17 shows how to update UserSearchRequest
to enable paging.
Listing 6-17. Updated UserSearchRequest
public class UserSearchRequest implements Serializable {
@QueryParam("firstName")
private String firstName;
@QueryParam("lastName")
private String lastName;
@QueryParam("totalConversions")
private BigDecimal totalConversions;
@QueryParam("conversionFilter")
301
CHAPTER 6
REST WITH JAKARTA REST
private ConversionFilter conversionFilter =
ConversionFilter.EQ;
@QueryParam("userType")
private UserType userType;
@QueryParam("limit")
@DefaultValue("150")
@Positive
private Integer limit;
@QueryParam("offset")
@DefaultValue("0")
private Integer offset;
public enum ConversionFilter {
GT,
GTE,
LT,
LTE,
EQ,
NEQ
}
}
@DefaultValue
The limit and offset fields, used for paging, are query parameters. The
@DefaultValue annotation sets default values if the client doesn’t provide
them: limit defaults to 150, and offset defaults to 0. The @Positive
annotation on the limit field ensures it’s a positive integer.
302
CHAPTER 6
REST WITH JAKARTA REST
Refactoring the UserSearchRequest didn’t require changes to the
resource method, highlighting the benefit of the @BeanParam annotation
for query parameters. To support client-side paging, a new parameterized
SearchResult class that includes relevant metadata is shown in
Listing 6-18.
Listing 6-18. SearchResult
public class SearchResult<T> implements Serializable {
private List<T> searchResult = new ArrayList<>();
private Long totalSize;
private Long offset;
private Long limit;
}
SearchResult takes a type and binds it to the searchResult list, which
holds the actual search results. totalSize indicates the total number
of matched search requests, while offset and limit reflect the client’s
input. Using this new construct, the searchUsers resource method can
be refactored to return a SearchResult object typed to UserResponse, as
shown in Listing 6-19.
Listing 6-19. Updated searchUsers resource method
@GET
@Path("search")
public SearchResult<UserResponse> searchUsers(@NotNull
@BeanParam UserSearchRequest userSearchRequest) {
return userService.searchUsers(userSearchRequest);
}
303
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-20 shows a complete search implementation in the
UserRepository, using the Jakarta Persistence specification’s Criteria
API. As explained in the preceding chapter, the Criteria API is more
appropriate for application search scenarios like this.
Listing 6-20. Search user implementation with Criteria API
public SearchResult<UserResponse> searchUsers(final
UserSearchRequest searchRequest) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<User> query = criteriaBuilder.
createQuery(User.class);
Root<User> from = query.from(User.class);
final Set<Predicate> predicateSet = new HashSet<>();
if (searchRequest.getFirstName() != null) {
Predicate firstName = criteriaBuilder.like(from.
get("firstName"), "%" + searchRequest.
getFirstName() + "%");
predicateSet.add(firstName);
}
if (searchRequest.getLastName() != null) {
Predicate lastName = criteriaBuilder.like(from.
get("lastName"), "%" + searchRequest.
getLastName() + "%");
predicateSet.add(lastName);
}
if (searchRequest.getTotalConversions() != null) {
if (searchRequest.getConversionFilter() ==
UserSearchRequest.ConversionFilter.EQ) {
predicateSet.add(criteriaBuilder.equal(from.
get("totalConversions"),
304
CHAPTER 6
REST WITH JAKARTA REST
searchRequest.getTotalConversions()));
}
if (searchRequest.getConversionFilter() ==
UserSearchRequest.ConversionFilter.GT) {
predicateSet.add(criteriaBuilder.greaterThan(from.
get("totalConversions"),
searchRequest.getTotalConversions()));
}
if (searchRequest.getConversionFilter() ==
UserSearchRequest.ConversionFilter.GTE) {
predicateSet.add(criteriaBuilder.
greaterThanOrEqualTo(from.get("totalConversions"),
searchRequest.getTotalConversions()));
}
if (searchRequest.getConversionFilter() ==
UserSearchRequest.ConversionFilter.LT) {
predicateSet.add(criteriaBuilder.lessThan(from.
get("totalConversions"),
searchRequest.getTotalConversions()));
}
if (searchRequest.getConversionFilter() ==
UserSearchRequest.ConversionFilter.LTE) {
predicateSet.add(criteriaBuilder.
lessThanOrEqualTo(from.get("totalConversions"),
searchRequest.getTotalConversions()));
}
if (searchRequest.getConversionFilter() ==
UserSearchRequest.ConversionFilter.NEQ) {
predicateSet.add(criteriaBuilder.notEqual(from.
get("totalConversions"),
305
CHAPTER 6
REST WITH JAKARTA REST
searchRequest.getTotalConversions()));
}
}
if (searchRequest.getUserType() != null) {
Predicate userType = criteriaBuilder.equal(from.
get("userType"), searchRequest.getUserType());
predicateSet.add(userType);
}
CriteriaQuery<User> where = query.select(from).
where(predicateSet.toArray(new Predicate[] {}));
TypedQuery<User> typedQuery = em.createQuery(where);
if (searchRequest.getOffset() != null) {
typedQuery = typedQuery.setFirstResult(searchRequest.
getOffset());
}
if (searchRequest.getLimit() != null) {
typedQuery = typedQuery.setMaxResults(searchRequest.
getLimit());
}
List<UserResponse> response =
typedQuery.getResultList().stream().map(UserService::to
UserResponse).collect(Collectors.toList());
SearchResult<UserResponse> searchResult = new
SearchResult<>();
searchResult.setSearchResult(response);
CriteriaQuery<Long> countQuery = criteriaBuilder.
createQuery(Long.class);
Root<User> userCountRoot = countQuery.from(User.class);
countQuery.select(criteriaBuilder.
countDistinct(userCountRoot.get("id")))
306
CHAPTER 6
REST WITH JAKARTA REST
.where(predicateSet.toArray(new Predicate[] {}));
Long count = em.createQuery(countQuery).getSingleResult();
searchResult.setTotalSize(count);
searchResult.setLimit(Long.valueOf(searchRequest.
getLimit()));
searchResult.setOffset(searchResult.getOffset());
return searchResult;
}
The Criteria API, although the best tool for these types of database
queries, can be verbose. To improve readability, a search implementation
query can be divided into smaller methods (presented here as one large
body for reference).
With a paginated search method, an architectural decision is needed
regarding the final GET method, which returns all users. Since the
search method returns similar results, this final GET method can be
removed for redundancy. A search for a user collection already returns
a list, and a dedicated endpoint for all users would also require paging
for performance. As paging is already implemented in the searchUsers
endpoint, the final GET method can be omitted architecturally.
@PUT
The @PUT method updates a resource. The convention is to use @POST
for creation and @PUT for updates. Following this, @PUT updates a user.
Listing 6-21 in the UserResource class shows the @PUT method.
307
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-21. @PUT method
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("users")
public class UserResource {
@Inject
UserService userService;
@PUT
public UserResponse updateUser(@NotNull UpdateUserRequest
updateUserRequest) {
return
userService.updateUser(updateUserRequest);
}
}
As this method does not explicitly declare any @Path param, it will
be hosted at the root /users path. An HTTP PUT request to /api/v1/users
will be matched to this method. The method parameter is annotated
@NotNull because the client must not pass a null value. But the actual
UpdateUserRequest does not declare any constraint validation. Listing
6-22 shows the UpdateUserRequest.
Listing 6-22. UpdateUserRequest
public class UpdateUserRequest implements Serializable {
private Long userId;
private String firstName;
private String lastName;
308
CHAPTER 6
REST WITH JAKARTA REST
@JsonbDateFormat("dd-MM-yyyy")
private LocalDate birthDay;
private CreateUserRequest.UserRegion userRegion;
}
This class allows updating only specific user fields. In application
development, some entity fields significantly impact other application
parts. For example, a user’s email might be linked to other user-owned
items. Allowing arbitrary updates to such fields could corrupt data. These
core fields are usually updated through more complex processes, like
business processes. This ensures all other places where the field is used are
updated simultaneously. Therefore, from both architectural and business
perspectives, the UpdateUserRequest allows updating only specific fields.
The @JsonbDateFormat annotation on the birthDay field sets the
format of the passed date value. This annotation is from the Jakarta JSON
Binding specification, an API for converting JSON to and from Java. This
specification is the default provider for converting response types to
JSON. The annotation uses the same date formats as DateTimeFormatter
in the java.time package.
@DELETE
The @DELETE method creates a resource method that responds to
the HTTP DELETE method. Like updating fields, deleting a resource
is a serious operation that must be carried out carefully. In enterprise
applications, deleting resources requires a business process that
ensures all uses of the resource to be deleted are handled. However, for
completeness, a @DELETE method is shown in Listing 6-23.
309
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-23. @DELETE method
@DELETE
public void deleteUser(@NotNull @Positive Long userId) {
userService.removeUser(userId);
}
The Response Object
The resource methods seen so far have all directly returned Java types,
which are then marshalled to JSON. The jakarta.ws.rs.core.Response
object can be used to provide custom metadata to the client. Listing 6-24
shows the createUser resource method refactored to return a custom
Response object containing the path to the newly created entity.
Listing 6-24. Returning a Response object
@POST
public Response createUser(@NotNull @Valid CreateUserRequest
createUserRequest, @Context UriInfo uriInfo) {
UserResponse user = userService.
createUser(createUserRequest);
URI uri = uriInfo.getAbsolutePathBuilder()
.path(user.getData().getUserId().
toString())
.build();
return Response.created(uri).entity(user).build();
}
The createUser method takes two parameters. The second is the
UriInfo, injected into the uriInfo variable using the @Context annotation.
This annotation injects Jakarta REST artifacts into fields and method
parameters. The UriInfo interface has methods to get information about
310
CHAPTER 6
REST WITH JAKARTA REST
the current request URI. The createUser implementation saves the passed
user and then builds a path to the location of the newly created user. This
is a key component of HATEOS (Hypermedia as the Engine of Application
State), as the server is providing the client with the URI to access the newly
created resource.
Remember in Table 6-1, the path to getting a user by ID was set to /
api/users/{userId}. The URI info instance calls the getAbsolutePathBuilder
method, which returns the full path to the current resource class, and
then appends the newly created user ID to it. This dynamic generation of
URIs is a fundamental aspect of HATEOS. Listing 6-25 shows the returned
response when a POST request is made. This response would include the
URI, allowing the client to immediately access the new resource, which
is a core principle of HATEOS, enabling client-side discovery of available
actions.
Listing 6-25. Returned custom Response object
http://localhost:3003/account/api/users
HTTP/1.1 201 Created
Content-Type: application/json
Location: http://localhost:3003/account/api/v1/users/1
Content-Language: en-US
Content-Length: 114
{
"data": {
"firstName": "John",
"lastName": "Jakes",
"userId": 1
},
"response": {
"responseCode": "0",
311
CHAPTER 6
REST WITH JAKARTA REST
"responseMessage": "OK"
}
}
The Location header, which is set to the full URI of the new user,
allows clients to navigate to and load the newly created user from the
resource class. While Listing 6-11 showed a 200 HTTP response code when
the createUser resource method returned a UserResponse, Listing 6-25
demonstrates that returning the Response object results in a 201 response
code. The Response class enables the creation of any custom response
data for the client.
Exception Mappers
Exception mapping in Jakarta REST is used to map exceptions to client
responses. Business exceptions signal problems with normal application
execution, and exception mappers convey exception messages to clients.
In a POST request in Listing 6-13, the server responded with HTTP status
code 400 for a bad request, which is not very helpful. Exception mappers
provide a better experience by specifying exactly what is wrong with
the data.
An exception mapper is an implementation of the jakarta.ws.rs.ext.
ExceptionMapper interface, which takes a Throwable type and maps it
to a Response object in the toResponse method. Listing 6-26 shows an
exception mapper for returning validation constraint violation messages to
the client.
Listing 6-26. Exception mapper
@Provider
public class ConstraintViolationExceptionMapper implements
ExceptionMapper<ConstraintViolationException> {
312
CHAPTER 6
REST WITH JAKARTA REST
@Override
public Response toResponse(ConstraintViolationException
exception) {
StringBuilder builder = new StringBuilder();
for (ConstraintViolation<?> cv : exception.
getConstraintViolations()) {
String path = cv.getPropertyPath().toString().
split("\\.")[2];
builder.append(path).append(" - ")
.append(cv.getMessage()).append("\n");
}
return Response.status(Response.Status.BAD_REQUEST)
.entity(builder.toString())
.build();
}
}
The ConstraintViolationExceptionMapper maps the jakarta.validation.
ConstraintViolationException exception to a Response object. When a
constraint violation occurs, the ConstraintViolationException is thrown,
with a set of the constraints that occurred. Each constraint object has the
name of the field on which the violation occurred. The toResponse method
maps these to a string and sets that as the entity on the Response. The @
jakarta.ws.rs.ext.Provider annotation on the class registers it as a Jakarta
REST artifact that will be scanned and registered automatically by the
runtime. Listing 6-27 shows the response from a call with malformed data
to the createUser resource method.
313
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-27. Mapped response
HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Language: en-US
Content-Length: 55
Connection: Close
Date: Sat, 18 Jan 2025 00:46:22 GMT
lastName - must not be empty
email - must not be empty
When a CreateUserRequest object’s email and lastName fields are
missing from a request, a validation exception occurs. The registered
exception mapper maps this ConstraintViolationException to the client,
returning a response detailing each violated field and its corresponding
message.
The Jakarta REST Client
Jakarta REST provides an HTTP client for making REST calls. This client
is simple and straightforward, revolving around the jakarta.ws.rs.client.
WebTarget interface. WebTarget targets a resource by its URI. A WebTarget
is obtained by calling the static target method on the jakarta.ws.rs.client.
Client instance returned by the jakarta.ws.rs.client.ClientBuilder class.
Listing 6-28 shows constructing a Client and using it to target a resource to
obtain a WebTarget in the test class of the account module.
Listing 6-28. Obtaining a Client
public class AbstractAccountIT {
protected static final WebTarget target;
protected static final Client client;
314
CHAPTER 6
REST WITH JAKARTA REST
static {
client = ClientBuilder.newClient();
target = client.target("http://localhost:3003/account/
api/v1");
}
@AfterAll
protected static void cleanUp() {
if (client != null) {
client.close();
}
}
}
The ClientBuilder.newClient method returns a Client. Clients are
heavy objects, so you shouldn’t create more than necessary instances. In
the provided example, the returned instance is assigned to the static client
variable. The target method is then invoked with the full base resource
path being targeted to return a WebTarget instance, which is assigned to
the target variable. The instantiation is done in a static block because the
WebTarget and Client instances are static. This initialization is enough to
use the target for all calls.
Once everything is done, the Client should be closed to prevent
resource leakage. According to the API, Clients are heavy-weight objects
that manage the client-side communication infrastructure. Initialization
and disposal of a Client instance may be a rather expensive operation.
So we close the Client instance after all the tests are run in the cleanUp
method annotated with @AfterAll from the JUnit test suite.
With the WebTarget initialized, HTTP REST calls can be made by
specifying the relative path of the resource of interest. Listing 6-29 shows
making both POST and GET requests to the /users and /users/api/{userId}
resource paths, respectively.
315
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-29. Making calls with the client
@Test
void createUser() {
UserResponse createdUser = target.path("users")
.request().post(Entity.json(createUserRequest),
UserResponse.class);
assertEquals("0", createdUser.getResponse().
getResponseCode());
assertEquals("OK", createdUser.getResponse().
getResponseMessage());
// get created user
UserResponse userResponse = target.path("users/
{userId}")
.resolveTemplate("userId", createdUser.
getData().getUserId()).request()
.get(UserResponse.class);
assertEquals("0", userResponse.getResponse().
getResponseCode());
assertEquals("OK", userResponse.getResponse().
getResponseMessage());
}
The path method on the WebTarget returns another WebTarget
instance that resolves to the original path passed to the client.target
invocation and this new path. So the target.path(“users”) call resolves the
returned WebTarget to http://localhost:3003/account/api/v1/users.
The request method is then called on the implicitly returned WebTarget
instance to return a jakarta.ws.rs.client.SyncInvoker instance. This
interface has all the HTTP methods that can be invoked to make the actual
request.
316
CHAPTER 6
REST WITH JAKARTA REST
The post method passes in an instance of the CreateUserRequest.
This instance is transformed to JSON using the static json method on
the jakarta.ws.rs.client.Entity class. The second parameter passed to the
post method is the class type to which the returned response should
be transformed. As per the resource paths, a POST request to the /api/
users resource returns the created user. The post invocation response is
directly assigned to a UserResponse variable because the runtime will
automatically read and convert the returned entity from JSON to the
concrete Java type.
The second call is a GET call to the /api/v1/users/{userId} endpoint.
This endpoint takes a path parameter. The path method is passed the
raw path with the variable name, which is then resolved to the ID of the
user with the resolveTemplate method. This method takes the name of
the variable to resolve and the value to resolve to. The get method is then
invoked to make the HTTP GET request. The returned response is directly
assigned to a Java type because the get method was passed a class type to
which the body of the response should be converted.
Jakarta REST Client is a feature-rich API for making all forms of HTTP
calls to web resources. You can chain paths and resolve variables to create
complex resource paths. You can also get the raw jakarta.ws.rs.core.
Response object returned by a call for use in your code.
The MicroProfile REST Client
The MicroProfile REST Client specification offers a more type-safe way
to make REST calls. While Jakarta REST Client discussed in the previous
section works, it can be verbose and cumbersome. MicroProfile REST
Client offers an alternative for consuming HTTP resources in Java
without the need to create client objects. Listing 6-30 shows a complete
MicroProfile REST Client declaration for making external calls to apilayer.
com’s currency conversion service.
317
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-30. MicroProfile client
@RegisterRestClient(baseUri = BASE_URI)
@ClientHeaderParam(name = "apikey", value = "API_KEY")
@Path("exchangerates_data")
public interface ApiLayer {
String NAME = "ApiLayer";
String BASE_URI = "https://api.apilayer.com";
@GET
@Path("convert")
ApiLayerConvertResponse convertCurrency(@BeanParam
ApiLayerConvertRequest apiLayerConvertRequest);
@GET
@Path("list")
JsonObject getCurrencySymbols();
}
The REST client setup requires defining target resources through an
interface. In this case, the ApiLayer interface specifies two HTTP GET
methods:
1. A method accepting an ApiLayerConvertRequest
with @BeanParam annotation, containing
query parameters needed by the apilayer.com
currency service
2. A method returning either a custom
ApiLayerConvertResponse object or a Jakarta JSON
Processing API JsonObject
318
CHAPTER 6
REST WITH JAKARTA REST
The @RegisterRestClient(baseUri = BASE_URI) annotation marks this
as a MicroProfile REST Client interface and sets the base URL (https://
api.apilayer.com). All requests through this client will use this as their
starting point.
For authentication, @ClientHeaderParam(name = “apikey”,
value = “API_KEY”) adds your API key to every outbound request’s
headers automatically.
The @Path annotation defines the relative path for all client method
calls: https://api.apilayer.com/exchangerates_data . This means
•
First GET Method Calls: https://api.apilayer.com/
exchangerates_data/convert
•
Second GET Method Calls: https://api.apilayer.
com/exchangerates_data/list
To use this client in your code, you simply need to
1. Add the @Inject annotation.
2. Include the MicroProfile @RestClient qualifier.
The RateService bean demonstrates this implementation in
Listing 6-31.
Listing 6-31. REST client use
@ApplicationScoped
public class RateService {
@Inject
@RestClient
ApiLayer apiLayer;
private ConvertCurrencyResponse convert(final
ConvertCurrencyRequest currencyRequest) {
319
CHAPTER 6
REST WITH JAKARTA REST
ApiLayerConvertRequest request = new
ApiLayerConvertRequest();
request.setFromCurrency(currencyRequest.
getSourceCurrency());
request.setToCurrency(currencyRequest.getTargetCurrency());
request.setAmount(currencyRequest.getAmount().
toPlainString());
ApiLayerConvertResponse response = apiLayer.
convertCurrency(request);
ConvertCurrencyResponseData data = new
ConvertCurrencyResponseData();
data.setCurrency(currencyRequest.getTargetCurrency());
data.setAmount(response.getResult());
data.setSource(ApiLayer.NAME);
return ConvertCurrencyResponse.of(data);
}
}
To use the REST client, we inject it using @Inject and qualify it
with the @RestClient CDI qualifier from the MicroProfile REST Client
API. The implementation of the interface will be provided at runtime
by the underlying REST client implementation. The convert method
calls the convertCurrency method on the injected client like any
other Java instance. The implementation will take care of creating the
actual HTTP request, making the invocation to the target resource,
getting and converting the response to the declared Java types. The
ApiLayerConvertRequest and ApiLayerConvertResponse classes are
shown in Listings 6-32 and 6-33, respectively.
320
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-32. ApiLayerConvertRequest
public class ApiLayerConvertRequest {
@QueryParam("from")
private String fromCurrency;
@QueryParam("to")
private String toCurrency;
@QueryParam("amount")
private String amount;
}
Listing 6-33. ApiLayerConvertResponse
public class ApiLayerConvertResponse {
private boolean success;
private Info info;
private LocalDate date;
private BigDecimal result;
@Getter
@Setter
public static class Info {
private Long timestamp;
private BigDecimal rate;
}
}
The ApiLayerConvertResponse is the Java representation of the
JSON that the endpoint returns. The REST client runtime takes care of
marshalling the returned JSON to the Java representation automatically.
Listing 6-34 shows a sample JSON returned by the https://api.
apilayer.com/exchangerates_data/convert endpoint.
321
CHAPTER 6
REST WITH JAKARTA REST
Listing 6-34. Sample return data
{
"date": "2005-01-01",
"historical": true,
"info": {
"quote": 0.51961,
"timestamp": 1104623999
},
"query": {
"amount": 10,
"from": "USD",
"to": "GBP"
},
"result": 5.1961,
"success": true
}
The getCurrencySymbols endpoint of the ApiLayer interface returns a
JsonObject, allowing direct use of JSON data for further processing. When
invoked, the REST client runtime converts the JSON string response to a
JsonObject. The MicroProfile REST Client API offers a powerful, intuitive,
and type-safe way to consume REST resources in Jakarta EE applications.
Documenting REST APIs with OpenAPI
A well-documented API is as important as a well-designed one. The
OpenAPI specification (formerly Swagger) is the industry standard for
documenting REST APIs. When integrated with Jakarta REST through
MicroProfile, OpenAPI annotations provide a declarative way to generate
comprehensive API documentation directly from REST resources.
322
CHAPTER 6
REST WITH JAKARTA REST
API-Level Documentation
The @OpenAPIDefinition annotation in Jakarta REST provides high-level
API metadata, placed at the top level of REST configuration. It includes
details like title, description, version, contact info, licensing, and terms of
service, aiding documentation, SDK creation, and API discovery. Listing
6-35 shows the RestApplicationConfiguration documented with it.
Listing 6-35. OpenAPI-documented REST config class
@OpenAPIDefinition(
info = @Info(
title = "JWallet REST API",
version = "1.0.0",
description = "REST endpoints for the JWallet
application",
contact = @Contact(
name = "JWallet Support",
email = "support@jwallet.com"
)
),
tags = {
@Tag(name = "users", description = "User management
operations"),
@Tag(name = "currency", description = "Currency
conversion operations")
}
)
@ApplicationPath("api/v1")
public class RestApplicationConfiguration extends Application {
}
323
REST WITH JAKARTA REST
CHAPTER 6
The @OpenAPIDefinition annotation provides metadata for OpenAPI
documentation, including the API title, version (1.0.0), description, and
contact information. It also defines two tags: “users” for user management
and “currency” for currency conversion.
Resource Documentation
For resource classes, OpenAPI annotations can be used to document
endpoints, parameters, and responses. Listing 6-36 shows the
UserResource class fully documented via the OpenAPI specification.
Listing 6-36. The UserResource fully documented
@Path("users")
@Tag(name = "users")
public class UserResource {
@Operation(
summary = "Create a new user",
description = "Creates a user based on the provided
request data and returns the resource location"
)
@APIResponses({
@APIResponse(
responseCode = "201",
description = "User successfully created",
content = @Content(
mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation =
UserResponse.class)
)
),
324
CHAPTER 6
REST WITH JAKARTA REST
@APIResponse(
responseCode = "400",
description = "Invalid request data provided"
)
})
@POST
Response createUser(@NotNull @Valid CreateUserRequest
createUserRequest, @Context UriInfo uriInfo);
@Operation(
summary = "Search users",
description = "Search for users with support for
filtering and pagination"
)
@GET
@Path("search")
SearchResult<UserResponse> searchUsers(
@Parameter(
description = "Filter users by first name",
example = "John"
)
@QueryParam("firstName") String firstName,
@Parameter(
description = "Maximum results per page",
schema = @Schema(defaultValue = "150")
)
@QueryParam("limit") @DefaultValue("150") @Positive
Integer limit
);
}
325
CHAPTER 6
REST WITH JAKARTA REST
The class-level @Tag annotation groups related operations under
the “users” category in the generated documentation. Within the class,
each method’s documentation tells a complete story about the endpoint.
The createUser method specifies possible response scenarios through
@APIResponses—a successful creation returns a 201 status code with the
new user’s data in JSON format, while invalid input triggers a 400 response.
For the search endpoint, @Parameter annotations clarify how to use
query parameters, with the firstName parameter demonstrating text-based
filtering and limit showing pagination control. Each annotation builds
upon Jakarta REST’s foundational path and method annotations to create
clear, comprehensive API documentation that guides API consumers
through correct usage patterns.
Notice how each annotation serves a distinct documentation
purpose—@Operation provides the high-level overview, @APIResponses
details possible outcomes, and @Parameter explains input requirements.
Together, they transform what could be cryptic endpoints into welldocumented, self-describing API resources that developers can quickly
understand and implement.
Schema Documentation
The OpenAPI annotations can also document data models. Listing
6-37 shows the CreateUserRequest with OpenAPI schema generation
annotations.
Listing 6-37. Schema generation with OpenAPI
@Schema(description = "Request object for user creation")
public class CreateUserRequest {
@Schema(
description = "User's first name",
example = "John",
326
CHAPTER 6
REST WITH JAKARTA REST
required = true
)
@NotEmpty
private String firstName;
@Schema(
description = "Valid email address for account
verification",
example = "john@example.com",
required = true
)
@NotEmpty
@Email
private String email;
}
The CreateUserRequest class demonstrates how OpenAPI schema
annotations document data models that are exchanged through the
API. The class-level @Schema annotation defines this as the request
payload for user creation operations. At the field level, each property
combines OpenAPI documentation with Jakarta validation constraints—
firstName must be non-empty and shows a sample value of “John”, while
email requires a valid email format and exemplifies this with “john@
example.com”.
These annotations work in tandem to provide both validation rules
and usage guidance. When the OpenAPI documentation is generated,
these descriptions and examples help API consumers understand exactly
what data to send, reducing integration errors and support needs. The
validation constraints ensure the documented requirements are enforced
at runtime, maintaining consistency between documentation and
implementation.
327
CHAPTER 6
REST WITH JAKARTA REST
Generated Documentation
These annotations generate documentation in both human-readable and
machine-readable formats. Listing 6-38 shows a sample output of the
documentation.
Listing 6-38. A sample OpenAPI documentation
openapi: 3.0.1
info:
title: JWallet REST API
version: 1.0.0
description: REST endpoints for the JWallet application
contact:
name: JWallet Support
email: support@jwallet.com
paths:
/users:
post:
summary: Create a new user
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: User successfully created
content:
application/json:
schema:
$ref: '#/components/schemas/UserResponse'
328
CHAPTER 6
REST WITH JAKARTA REST
The generated documentation serves as both a reference for API
consumers and a contract between the API provider and consumers.
Maintaining documentation in code naturally stays synchronized with
implementation changes, reducing the maintenance burden while
improving accuracy.
Modern Jakarta EE implementations automatically expose OpenAPI
documentation through endpoints like /openapi for the raw OpenAPI
document and /openapi-ui for an interactive interface. This allows
developers to explore and test the API directly through their browser,
significantly speeding up integration and development cycles.
Effective API documentation extends beyond the endpoints. It should
provide a comprehensive narrative detailing the practical application
of the API. Use description fields to document the business context of
operations, provide usage examples, and emphasize key considerations for
API consumers.
Summary
This chapter has provided a thorough exploration of Jakarta REST,
examining how to design, implement, and consume RESTful web services
in Jakarta EE applications. We started by understanding core REST
principles and resource modeling, learning how proper design choices
lead to intuitive and maintainable APIs. Through practical examples with
the UserResource implementation, we saw how Jakarta REST’s annotation­
based model elegantly transforms Java classes into web resources.
The integration between Jakarta REST and other specifications,
particularly Bean Validation, demonstrated how the Jakarta EE
ecosystem works together to create robust applications. We explored how
ExceptionMappers provide clean error handling and saw two distinct
approaches to consuming REST services—Jakarta REST Client and the
more modern MicroProfile REST Client.
329
CHAPTER 6
REST WITH JAKARTA REST
Documentation emerged as a crucial component, with OpenAPI
annotations providing a declarative way to maintain accurate API
documentation alongside code. This ensures that documentation naturally
evolves with implementation changes, reducing maintenance overhead
while improving accuracy.
Key Takeaways
1. Jakarta REST’s annotation-based programming
model provides a powerful yet straightforward way
to build web services that integrate smoothly with
the broader Jakarta EE ecosystem.
2. Resource modeling and REST architecture
principles (statelessness, resource-based design,
cacheability, and HATEOS) form the foundation of
well-designed APIs.
3. Jakarta REST offers flexible parameter
handling through annotations like @PathParam,
@QueryParam, and @BeanParam, enabling clean
implementation of complex endpoints.
4. Integration with Bean Validation makes input
validation declarative and maintainable, while
ExceptionMappers provide consistent error
handling.
330
CHAPTER 6
REST WITH JAKARTA REST
5. The specification supports two complementary
client approaches:
•
Jakarta REST Client for flexibility and fine­
grained control
•
MicroProfile REST Client for type-safe, interface­
based consumption
6. OpenAPI integration enables automatic generation
of comprehensive API documentation that stays
synchronized with the implementation.
The next chapter will explore Jakarta EE configuration through
the MicroProfile Config specification, showing how to build flexible
applications that can adapt to different deployment environments through
proper configuration management.
331
CHAPTER 7
Managing
Configurations
Every application will go through different stages on its way to production.
From development to testing to staging to production, all these stages
require different configurations specific to those environments. For
instance, an application that uses an external fraud detection API will need
different service configurations depending on the environment. Similarly,
a batch service importing data will require different configuration
parameters across environments.
While Jakarta EE provides several approaches to configuration
management, this chapter focuses on three main areas:
1. Built-in Jakarta EE configuration options
2. The MicroProfile Config API
3. Environment-specific configuration strategies
By the end of this chapter, you will be able to
•
Understand traditional Jakarta EE configuration
mechanisms including resource injection and
environment entries.
•
Implement the MicroProfile Config API for flexible,
cloud-native configuration management.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_7
333
CHAPTER 7
MANAGING CONFIGURATIONS
•
Create and integrate custom configuration sources with
appropriate priority ordinals.
•
Develop custom type converters for specific
business needs.
•
Apply different configuration value retrieval methods
based on specific use cases.
•
Handle dynamic configuration updates in cloud-native
environments.
•
Choose appropriate configuration approaches for
different scenarios.
Jakarta EE Configuration Fundamentals
Jakarta EE, and its predecessor Java EE, have long provided robust support
for externalizing resources and configuration. Since its earliest versions,
the platform has included capabilities for managing external resources
through JNDI (Java Naming and Directory Interface), allowing applications
to externalize critical resources such as database connections, JMS queues,
and mail sessions. This approach has served enterprise applications well
for decades, particularly in traditional deployment environments where
configurations are relatively static and managed by application servers.
Resource Injection
Jakarta EE’s resource injection capabilities allow applications to reference
externalized resources through JNDI names. These resources are typically
configured at the application server level and injected into application
components. Listing 7-1 shows two examples of externalized resource
connections.
334
CHAPTER 7
MANAGING CONFIGURATIONS
Listing 7-1. Externalized connection resources
@Resource(lookup="java:global/jms/orderQueue")
private Queue orderQueue;
@Resource(lookup="java:comp/env/jdbc/customerDB")
private DataSource customerDB;
The actual connection details for these resources are defined in the
application server’s configuration, keeping sensitive information like
database credentials separate from application code.
Environment Entries
For simpler configuration needs, Jakarta EE provides environment entries
that can be defined in deployment descriptors and accessed through JNDI
or injection. Listing 7-2 shows two environment variable entries in the
web.xml file.
Listing 7-2. Environment variables in the web.xml file
<env-entry>
<env-entry-name>maxRetries</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>3</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>serviceEndpoint</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>https://fooservice.bazz</env-entry-value>
</env-entry>
335
CHAPTER 7
MANAGING CONFIGURATIONS
The two entries can be injected in code as shown in Listing 7-3.
Listing 7-3. Injection of the web.xml deployment descriptor
environment entries
@Resource(lookup="java:comp/env/maxRetries")
private Integer maxRetries;
@Resource(lookup="java:comp/env/serviceEndpoint")
private String serviceEndpoint;
Alternatives andQualifiers
Jakarta CDI’s alternatives and qualifier features (discussed in Chapter 4)
also allow for the swapping of implementations based on runtime or
deployment needs.
The Need for Cloud-Native Configuration
While these traditional Jakarta EE configuration approaches have served
well in conventional enterprise environments, the rise of cloud-native
applications, microservices architectures, and DevOps practices has
introduced new requirements:
336
•
Dynamic configuration changes without
application restart
•
Configuration from multiple sources (files,
environment variables, config servers)
•
Strong typing and conversion of configuration values
•
Support for configuration hierarchies and fallbacks
CHAPTER 7
MANAGING CONFIGURATIONS
•
Easy testing and configuration overrides in different
environments
•
Integration with cloud platforms and container
orchestration systems
These needs led to the development of the MicroProfile Config API,
which we’ll explore in the next section. MicroProfile Config complements
Jakarta EE’s existing configuration capabilities while providing a more
flexible, dynamic approach suited to cloud-native applications.
MicroProfile Config
While Jakarta EE’s traditional configuration mechanisms work well for server­
managed resources, modern cloud-native applications need a more flexible
and dynamic approach. The MicroProfile Config specification was designed
to address these needs while complementing existing Jakarta EE capabilities.
The Config Specification
MicroProfile Config introduces a unified system for managing application
configuration that works alongside Jakarta EE’s resource injection and
JNDI-based configuration. Unlike traditional Jakarta EE configuration
where changes often require redeployment, MicroProfile Config enables
dynamic configuration updates and supports multiple configuration
sources with automatic type conversion.
The specification is built on three core components:
1. Config Sources: Where configuration values are stored
2. Converters: How string values are converted to
Java types
3. Config Values: How applications access
configuration
337
CHAPTER 7
MANAGING CONFIGURATIONS
Config Sources and Priority
Unlike Jakarta EE’s traditional approach where most configuration
comes from deployment descriptors or application server settings,
MicroProfile Config can pull configuration values from multiple sources
simultaneously. A config source can be
•
Property files (similar to traditional resource bundles)
•
Environment variables (especially for container
deployments)
•
System properties (like Jakarta EE already supports)
•
Database entries (for dynamic configuration)
•
Custom sources (for integration with configuration
services)
This flexibility creates a new challenge: what happens when the same
configuration key exists in multiple sources? For example, a database
connection URL might be specified in both a properties file and an
environment variable as shown in Listing 7-4.
Listing 7-4. Two conflicting configuration properties
# microprofile-config.properties
db.url=jdbc:postgresql://dev-db:5432/myapp
# Environment Variable
DB_URL=jdbc:postgresql://prod-db:5432/myapp
338
CHAPTER 7
MANAGING CONFIGURATIONS
Default Config Sources and Ordinals
MicroProfile Config comes with three built-in config sources, each with a
predefined ordinal that determines its priority:
1. System Properties (Ordinal: 400): Accessed through
System.getProperties()
2. Environment Variables (Ordinal: 300): Accessed
through System.getenv()
3. Application Properties (Ordinal: 100): Located in
META-INF/microprofile-config.properties
When retrieving a value, sources with higher ordinals take precedence.
For example, if db.url is defined in both the properties file (ordinal 100)
and an environment variable (ordinal 300), the environment variable’s
value would be used. This makes it easy to override configuration
for different environments without changing code or rebuilding the
application—a key requirement for cloud-native deployments.
If multiple sources share the same ordinal, they’re sorted
alphabetically by their config source name. This hierarchy ensures
that container and system-level configuration can naturally override
application defaults without any code changes, a pattern that aligns
perfectly with cloud-native deployment practices.
Custom Config Sources
While these default sources cover many common scenarios, your
application might need to source configuration from other locations.
For instance, you might need to integrate with legacy systems that store
configuration in databases or modern configuration management services
like etcd or Consul. MicroProfile Config’s extensible architecture makes
this possible through custom config sources.
339
CHAPTER 7
MANAGING CONFIGURATIONS
Let’s examine the components of the ConfigSource implementation as
shown in Listing 7-5.
Listing 7-5. A custom config source implementation
public class CustomConfigSource implements ConfigSource {
private static final Map<String, String> properties = Map.
of("Key1", "value1", "Key2", "value2");
@Override
public Set<String> getPropertyNames() {
return properties.keySet();
}
@Override
public String getValue(final String key) {
return properties.get(key);
}
@Override
public String getName() {
return this.getClass().getSimpleName();
}
@Override
public int getOrdinal() {
return 450;
}
}
The ConfigSource interface, implemented by CustomConfigSource
in Listing 7-5, defines methods that determine how the Config runtime
interacts with your configuration source:
340
CHAPTER 7
MANAGING CONFIGURATIONS
getPropertyNames(): Returns all property keys
available in this config source. This is required for
certain operations where the Config runtime needs
to scan all available properties, such as during
configuration scanning at startup.
getValue(String key): The core method that retrieves
a configuration value. Note that values are always
returned as Strings—type conversion happens later
through the Converter mechanism we’ll discuss in
the next section.
getName(): Provides a unique identifier for the
config source, used primarily for debugging and
logging. By convention, most implementations
return their class name.
getOrdinal(): Determines this source’s priority in the
config source hierarchy. The above implementation
uses 450, placing it above the default sources. If not
overridden, sources receive a default ordinal of 100.
To activate the implemented custom config source, register it through
the ServiceLoader mechanism by adding its fully qualified class name
to a text file located in the META-INF/services folder named org.eclipse.
microprofile.config.spi.ConfigSource.
This extensible design allows integration with any configuration store
while maintaining a consistent interface for the Config runtime. Whether
reading from a database, API, or simple in-memory map as shown here,
the underlying source remains transparent to the application code
accessing the configuration.
While config sources provide the raw configuration values as strings,
the Converter mechanism handles transforming these strings into the Java
types your application needs.
341
CHAPTER 7
MANAGING CONFIGURATIONS
Converters in MicroProfile Config
While config sources provide configuration values, they can only supply
them as strings. For example, when reading the config property rate.
minimum=15 from any source, the raw value “15” is returned as a string.
However, an application often needs these values as specific Java types—
integers, booleans, custom objects, or in this case perhaps a BigDecimal.
This is where converters come in.
Built-In Type Conversion
MicroProfile Config provides default converters for common Java types:
•
Boolean: Supports case-insensitive values “true”, “1”,
“YES”, “Y”, “ON” (all others are false)
•
Numeric Types: byte, short, int, long, float, and double
(using ’.’ as decimal separator)
•
Character: Single character values
•
Class: Using Class.forName
Each built-in converter has a @Priority(1), which becomes important
when multiple converters exist for the same type. Just as config sources
use ordinals, converters use priority—higher-priority converters take
precedence.
Automatic Type Conversion
The Config runtime can automatically create converters for types that
provide any of these methods:
342
•
public static T of(String)
•
public static T valueOf(String)
CHAPTER 7
MANAGING CONFIGURATIONS
•
public static T parse(CharSequence)
•
A public constructor accepting a String parameter
This automatic conversion explains why types like BigDecimal
work without custom converters—they provide the necessary
valueOf(String) method.
Custom Converters
Sometimes applications need to work with configuration values that can’t
be handled by the built-in converters. For these cases, you can implement
custom converters by implementing the org.eclipse.microprofile.config.
spi.Converter<T> interface. These converters transform configuration
strings into custom types your application needs. Listing 7-6 shows an
example Converter implementation along with the Java target type of the
conversion.
Listing 7-6. Custom converter implementation
public class CurrencyRequestConverter implements Converter
<ConvertCurrencyRequest> {
@Override
public ConvertCurrencyRequest convert(final String value) {
if (value == null || value.isBlank()) {
throw new NullPointerException("Value must not be
null or empty string");
}
final String[] split = value.split(",");
if (split.length != 3) {
throw new IllegalArgumentException("The resulting
array has less than 3 elements.");
}
343
CHAPTER 7
MANAGING CONFIGURATIONS
return ConvertCurrencyRequest.builder()
.sourceCurrency(split[0])
.targetCurrency(split[1])
.amount(new BigDecimal(split[2]))
.build();
}
}
// Target type for conversion
public class ConvertCurrencyRequest {
private String sourceCurrency;
private String targetCurrency;
private BigDecimal amount;
// Getters, setters, and builder methods omitted
for brevity
}
This example demonstrates key aspects of implementing a custom
converter. First, the converter ensures type safety by implementing
the generic interface Converter<T> where T is the target type
(ConvertCurrencyRequest in this case). This provides compile-time
verification that the converter will produce objects of the correct type.
The implementation incorporates validation logic to maintain data
integrity. It verifies that the input string is not null and contains all required
components—source currency, target currency, and amount—throwing an
appropriate exception if the format doesn’t meet requirements. This helps
catch configuration errors early in the application lifecycle.
The converter also defines a specific format expectation, processing
comma-separated values to construct the final object. This format
definition creates a clear contract between the configuration source
and the converter, making it easier to understand and maintain the
configuration values.
344
CHAPTER 7
MANAGING CONFIGURATIONS
To register your custom converter, you must
1. Create a file named org.eclipse.microprofile.config.
spi.Converter in the META-INF/services/ directory.
2. Add the fully qualified class name of the converter
implementation to this file.
Once registered, the converter can be used with configuration
properties as shown in Listing 7-7.
Listing 7-7. Setting a custom converter property
convert.currency=USD,GHS,5
This property can be read in code through the normal MicroProfile
Config injection mechanism as shown in Listing 7-8.
Listing 7-8. Injection of ConvertCurrencyRequest
@Inject
@ConfigProperty(name="convert.currency")
ConvertCurrencyRequest conversionRequest;
Converter Priority
You can also specify a priority for converters using the @jakarta.annotation.
Priority annotation. This is useful when multiple converters exist for the same
type. Listing 7-9 shows the CurrencyRequestConverter with a set priority.
Listing 7-9. Priority setting on a converter
@Priority(150)
public class CurrencyRequestConverter implements Converter
<ConvertCurrencyRequest> {
// Implementation as above in Listing 7-6
}
345
CHAPTER 7
MANAGING CONFIGURATIONS
If no priority is specified, the default priority of 100 is assigned.
Converters with higher priority values take precedence over those with
lower values.
Remember that custom converters must
•
Be deterministic (same input string always produces
the same output)
•
Be thread-safe
•
Handle null values appropriately
•
Provide clear error messages when conversion fails
•
Follow the Single Responsibility Principle by focusing
solely on the conversion logic
The above converter can be used to read ConvertCurrencyRequest
config values from a database that was populated by a legacy COBOL
application. This way, the application can be used to interface with a
legacy application without much need for refactoring. The final third of the
MicroProfile Config components is the actual property value.
Config Values
The third of the config trio is the actual config value. The essence of the
Config specification is to abstract away all possible sources of application
configuration values into a transparent, single view in the form of config
sources. Using these config sources, you can get config values based on the
keys for each value needed.
For the given configuration convert.request=“USD,GHS,5”, there
are six different ways to get the config value using the Config API. This
configuration should get mapped to the ConvertCurrencyRequest type.
What happens in the absence of a value for a given property request
depends on the retrieval method. These retrieval methods are as follows.
346
CHAPTER 7
MANAGING CONFIGURATIONS
The Config Bean
The most basic config value reading approach is to inject the org.eclipse.
microprofile.config.Config bean directly. This bean resolves property
values by searching through all available config sources, respecting their
ordinal values. When the same property exists in multiple sources, the
source with the highest ordinal wins.
The getValue method takes two parameters: the property key and the
expected type. If the value is missing or resolves to null, it throws a java.
util.NoSuchElementException. Listing 7-10 shows an example of this
config retrieval method.
Listing 7-10. Config bean property retrieval example
@Inject Config config;
public ConvertCurrencyResponse batchConvertWithConfig() {
ConvertCurrencyRequest request = config.getValue("convert.
request", ConvertCurrencyRequest.class);
return convert(request);
}
To handle cases where a configuration property might be absent
without causing an exception, you can use the getOptionalValue method.
It takes the same arguments as getValue (property key and expected type)
but returns a java.util.Optional<T>. If the property is found and converted
successfully, it returns an Optional containing the value; otherwise, it
returns an empty Optional. Listing 7-11 shows an example.
347
CHAPTER 7
MANAGING CONFIGURATIONS
Listing 7-11. The use of Optional from the Config bean
@Inject
Config config;
public ConvertCurrencyResponse
batchConvertWithOptionalConfig() {
Optional<ConvertCurrencyRequest> maybeRequest
= config.getOptionalValue("convert.request",
ConvertCurrencyRequest.class);
// Handle the Optional result, e.g., provide a default or
alternative logic
return maybeRequest.map(this::convert)
.orElseGet(ConvertCurrency
Response::new);
}
This allows for more functional-style handling of potentially missing
configuration values when interacting directly with the Config bean.
Direct Injection
For simpler scenarios, you can inject configuration values directly using
@Inject with the @ConfigProperty qualifier. This qualifier requires a name
parameter and optionally accepts a defaultValue. Without a default value,
a missing configuration will cause a deployment exception.
If the name parameter is omitted, the runtime uses the pattern
class_name.injection_point_name, where class_name is the fully qualified
class name and injection_point_name is the field or parameter name. An
example of this can be found in Listing 7-8. This is the most popular way of
retrieving config values for a large number of applications.
348
CHAPTER 7
MANAGING CONFIGURATIONS
Optional Injection
When a configuration value might not be present, you can wrap the target
type in java.util.Optional<T>. Instead of throwing exceptions, missing
values return an empty Optional. This approach provides a more graceful
way to handle missing configurations. Listing 7-12 shows an example of
this approach.
Listing 7-12. An example of injecting a config value through
Optional
@Inject
@ConfigProperty(name = "convert.request")
Optional<ConvertCurrencyRequest> convertRequest;
public ConvertCurrencyResponse batchConvertOptional() {
return convertRequest.map(this::convert)
.orElseGet(ConvertCurrency
Response::new);
}
Dynamic Value Access
Two mechanisms support accessing dynamically changing
configuration values.
Provider Injection
Using jakarta.inject.Provider<T> ensures each call to get() retrieves the
latest value from the underlying configuration source. However, it throws
a RuntimeException for missing values. Listing 7-13 shows an example of
this mechanism.
349
CHAPTER 7
MANAGING CONFIGURATIONS
Listing 7-13. Provider config value retrieval example
@Inject
@ConfigProperty(name = "convert_request")
Provider<ConvertCurrencyRequest> currencyRequestProvider;
public ConvertCurrencyResponse batchConvertWithProvider() {
return convert(currencyRequestProvider.get());
}
While Provider<T> retrieves the latest value, it still throws an exception
if the property is missing at the time get() is called. If you need dynamic
retrieval and optionality, you can inject a Provider<Optional<T>>. Calling
get() on this provider will return an Optional representing the current
state of the configuration property. Listing 7-14 shows the above example
rewritten to return an Optional.
Listing 7-14. The use of Optional with the Provider mechanism
@Inject
@ConfigProperty(name = "convert.request")
Provider<Optional<ConvertCurrencyRequest>>
currencyRequestProvider;
public ConvertCurrencyResponse
batchConvertWithOptionalProvider() {
Optional<ConvertCurrencyRequest> maybeRequest =
currencyRequestProvider.get();
// Handle the Optional result
return maybeRequest.map(this::convert)
.orElseGet(ConvertCurrency
Response::new);
}
350
CHAPTER 7
MANAGING CONFIGURATIONS
Supplier Injection
Similar to Provider, the java.util.function.Supplier<T> interface offers
dynamic access to configuration values. Each call to get() resolves to
the latest value, with missing values triggering a RuntimeException.
Listing 7-15 shows an example.
Listing 7-15. Supplier config value retrieval example
@Inject
@ConfigProperty(name = "convert_request")
Supplier<ConvertCurrencyRequest>
convertCurrencyRequestSupplier;
public ConvertCurrencyResponse batchConvertWithSupplier() {
return convert(convertCurrencyRequestSupplier.get());
}
Similar to Provider, the standard Supplier<T> injection throws an
exception for missing values. To combine dynamic retrieval with graceful
handling of absent properties, inject a Supplier<Optional<T>>. Each
call to get() on this supplier will resolve the property against the current
configuration sources and return an Optional result. Listing 7-16 shows the
above example rewritten to use Optional.
Listing 7-16. The use of Optional with the Supplier mechanism
@Inject
@ConfigProperty(name = "convert.request")
Supplier<Optional<ConvertCurrencyRequest>>
convertCurrencyRequestSupplier;
public ConvertCurrencyResponse
batchConvertWithOptionalSupplier() {
351
CHAPTER 7
MANAGING CONFIGURATIONS
Optional<ConvertCurrencyRequest> maybeRequest =
convertCurrencyRequestSupplier.get();
// Handle the Optional result
return maybeRequest.map(this::convert)
.orElseGet(ConvertCurrency
Response::new);
}
ConfigValue Metadata
For advanced scenarios requiring metadata about the configuration, the
org.eclipse.microprofile.config.ConfigValue interface provides access to
•
The config source name
•
The source’s ordinal
•
The raw string value
•
The property name
•
The converted value
This interface is useful when you need runtime information about
configuration sources and resolution, though it’s less commonly used for
basic configuration access.
Each of these approaches has its own trade-offs in terms of error
handling, dynamic updates, and ease of use. The choice depends on your
specific requirements for handling missing values, dynamic updates, and
error conditions.
352
CHAPTER 7
MANAGING CONFIGURATIONS
Chapter Summary
The chapter explored a comprehensive overview of configuration
management in Jakarta EE applications, examining both traditional
approaches and modern cloud-native solutions. Traditional Jakarta EE
configuration mechanisms, including resource injection through JNDI
and environment entries in deployment descriptors, were covered as
foundational concepts.
MicroProfile Config emerged as the centerpiece of modern
configuration management, introducing a flexible and dynamic system
built on three core components: config sources, converters, and config
values. Config sources enable configuration from multiple origins with
a priority-based ordinal system. Converters transform configuration
strings into appropriate Java types, supporting both built-in and custom
conversions. Config values provide various access methods, from direct
injection to dynamic retrieval using Providers and Suppliers.
Together, these components create a configuration system that
meets cloud-native requirements while maintaining compatibility with
traditional Jakarta EE approaches. The result is a flexible, maintainable
configuration framework that supports modern deployment scenarios
while respecting enterprise stability needs.
Key Takeaways
1. Traditional Jakarta EE configuration methods serve
static, server-managed resources well but lack
flexibility for cloud environments.
2. MicroProfile Config provides a unified system for
managing configuration from multiple sources with
defined priorities.
353
CHAPTER 7
MANAGING CONFIGURATIONS
3. System properties (ordinal 400), environment variables
(300), and application properties (100) form the default
configuration hierarchy.
4. Custom configuration sources can be implemented and
prioritized to meet specific business needs.
5. Built-in type converters handle common Java types,
while custom converters support complex business
objects.
6. Configuration values can be accessed through direct
injection, optional injection, or dynamic access
patterns.
7. Custom converters must be deterministic, thread-safe,
and provide clear error messages.
8. Higher ordinals enable environment-specific
configuration overrides without code changes.
9. Dynamic configuration changes can be implemented
without application restart.
10. Multiple configuration sources can be integrated to
support different deployment scenarios.
11. The Config API supports both compile-time safety
through injection and runtime flexibility through
programmatic access.
12. Configuration metadata provides insight into value
resolution and source tracking for debugging purposes.
Even the most well-configured application can encounter failures in
a distributed system, which is why we’ll next explore how MicroProfile
Fault Tolerance helps build resilient cloud-native applications that can
gracefully handle service disruptions and network issues.
354
CHAPTER 8
Resilience
with the Fault
Tolerance API
In distributed systems, failure is not just a possibility—it is inevitable.
A service may become unresponsive, a network connection might fail,
or a database could experience unexpected latency. These failures, if
not properly managed, can cascade through an application, degrading
performance or causing complete system outages.
Consider a typical enterprise application processing financial
transactions. Each transaction might require validating account
credentials, checking available funds, executing the transfer, updating
account balances, generating transaction records, and sending
notifications. A failure at any step could lead to inconsistent data, locked
resources, or degraded service. Traditional error handling mechanisms,
while necessary, are often insufficient for managing the complexity of
distributed system failures.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_8
355
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
The Evolution of Fault Tolerance
Historically, enterprise applications relied on simple error handling and
database transactions for reliability. However, as applications evolved into
distributed systems, new challenges emerged:
1. Service Dependencies: Applications now depend
on multiple external services, each representing a
potential point of failure.
2. Resource Management: Systems must handle
varying loads while preventing any single
component from consuming excessive resources.
3. Network Uncertainty: Network latency and failures
introduce unpredictability into service interactions.
4. Cascading Failures: Problems in one service can
rapidly spread, affecting dependent services and
overall system health.
To address these challenges, several key patterns have emerged.
Circuit breakers prevent cascade failures by monitoring service health.
Bulkheads isolate components to contain failures. Retry mechanisms
handle transient failures, while timeouts prevent resource exhaustion.
Fallbacks provide alternative functionality when primary operations fail.
The MicroProfile Fault Tolerance specification brings these patterns to
Jakarta EE applications through a standardized, annotation-based approach.
This allows developers to implement sophisticated resilience strategies
without cluttering business logic with complex failure handling code.
By the end of this chapter, you will be able to
356
•
Design resilient Jakarta EE applications using fault
tolerance patterns.
•
Implement MicroProfile Fault Tolerance annotations
effectively.
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
•
Configure fault tolerance strategies for different failure
scenarios.
•
Integrate fault tolerance with existing Jakarta EE
components.
•
Monitor and maintain fault-tolerant applications.
•
Apply best practices for error handling and recovery.
Fault Tolerance Patterns
Building resilient applications requires a systematic approach to handling
failures. The MicroProfile Fault Tolerance specification provides a
framework of patterns implemented through annotations that integrate
with Jakarta EE applications. Before looking into specific annotations, let’s
understand these core patterns and when to apply them.
Core Fault Tolerance Patterns
Fallback
When a service fails, having an alternative response is often better than
failing entirely. Fallback mechanisms provide these alternatives, whether
through simplified functionality, cached data, or default responses. For
example, if a product recommendation service fails, an ecommerce
application might fall back to displaying bestsellers rather than
personalized suggestions.
MicroProfile implements fallback behavior through the @Fallback
annotation, which can specify either a replacement method or a dedicated
handler class. This flexibility allows for both simple default values and
complex alternative logic.
357
RESILIENCE WITH THE FAULT TOLERANCE API
CHAPTER 8
Timeout
In distributed systems, slow responses can be as problematic as failures.
A service that takes too long to respond can block threads, exhaust
connection pools, and degrade overall system performance. Timeouts
establish clear boundaries for acceptable response times.
The @Timeout annotation allows you to specify maximum duration for
method execution. When a timeout occurs, the operation is interrupted,
and you can combine this with other patterns like fallback or retry for more
sophisticated handling.
Retry
Some failures are transient—a network glitch, a temporary database lock,
or a brief service unavailability. In these cases, automatically retrying the
operation after a short delay often succeeds. However, retry logic needs to
be carefully tuned to avoid making problems worse.
The @Retry annotation supports sophisticated retry policies, including
•
Maximum number of retries
•
Delay between attempts
•
Exponential backoff
•
Specific exceptions to trigger retries
•
Maximum duration for all attempts
Circuit Breaker
Named after electrical circuit breakers, this pattern prevents system
overload by temporarily stopping requests when a service shows signs of
failure. Like its electrical counterpart, it protects the broader system by
isolating problems.
358
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
The @CircuitBreaker annotation implements this pattern with
three states:
•
Closed: Normal operation, requests proceed
•
Open: Service suspected of failure, requests fail fast
•
Half-Open: Testing if service has recovered
Bulkhead
Just as ships use bulkheads to prevent one breach from flooding the
entire vessel, software bulkheads prevent one failing component from
consuming all system resources. This pattern limits concurrent execution
to maintain overall system health.
MicroProfile offers two bulkhead approaches through the @Bulkhead
annotation:
•
Thread pooling for asynchronous execution
•
Semaphore-style limiting for synchronous execution
These patterns—fallback, timeout, retry, circuit breaker, and
bulkhead—form a comprehensive toolkit for handling different types of
failures in distributed systems. To effectively apply these tools, we must
first understand the categories of failures they address and how they map
to different failure scenarios.
Failure Categories
To effectively apply fault tolerance patterns, we must understand the
different types of failures commonly encountered in distributed systems
and their appropriate solutions. Table 8-1 summarizes these failure
categories and their handling approaches.
359
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Table 8-1. Common Failure Categories and Their Solutions
Failure
Examples
Characteristics
Category
Primary
Solutions
Transient
• Network timeouts
Short-lived issues
failures
• Database deadlocks
that typically resolve with appropriate
• Resource contention
on their own
Retry patterns
backoff
strategies
Partial
• Degraded performance
Service continues
Circuit breakers
failures
• Limited functionality
but with reduced
and fallbacks
• Inconsistent responses
capabilities
Resource
• Thread pool saturation
System resources
Bulkheads and
exhaustion
• Memory constraints
reaching or
timeouts
• Connection pool depletion
exceeding limits
Cascade
• Dependency chain failures Problems
Combination of
failures
• Resource contention
propagating across
circuit breakers,
service boundaries
bulkheads, and
spreading
• System-wide degradation
fallbacks
Understanding these failure categories provides the foundation
for implementing effective fault tolerance strategies. In the following
sections, we’ll explore each MicroProfile Fault Tolerance annotation in
detail, starting with @Fallback. This annotation provides the fundamental
capability to handle failures gracefully by defining alternative behavior
when operations fail.
360
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
@Fallback
The @Fallback annotation provides a way to define alternative behavior
when an operation fails. Instead of propagating errors to users or
dependent services, applications can gracefully degrade by providing
default values, cached data, or simplified functionality.
Annotation Approach
Consider a currency conversion service that normally makes external API
calls. When the service can’t reach the external rate provider, it should
still function, even if only returning the original amount. Listing 8-1
demonstrates this pattern.
Listing 8-1. Currency conversion service with fallback
@ApplicationScoped
public class ResilientRateService extends SimpleRateService {
@Fallback(
fallbackMethod = "fallbackConvert",
applyOn = { java.net.UnknownHostException.class})
@Override
public BigDecimal convert(String sourceCurrency, BigDecimal
amount, String targetCurrency) {
return super.convert(sourceCurrency, amount,
targetCurrency);
}
private BigDecimal fallbackConvert(String sourceCurrency,
BigDecimal amount, String targetCurrency) {
return amount;
}
}
361
RESILIENCE WITH THE FAULT TOLERANCE API
CHAPTER 8
The @Fallback annotation provides two core parameters that control
its behavior. The fallbackMethod parameter specifies an alternative
method to call when the primary method fails. This fallback method must
reside in the same class as the annotated method or in a superclass or
implemented interface. Most importantly, the fallback method must have
the exact same method signature as the annotated method—matching
parameter types, return type, and thrown exceptions.
The fallbackConvert method in Listing 8-1 has the same method
signature as the convert method. The fallback could, for instance,
implement default rate exchange lookup through a static JSON file as a
fallback.
The applyOn parameter defines which exceptions should
trigger the fallback behavior. The convert method specifies java.net.
UnknownHostException.class as the exception type that should cause the
fallback method to be invoked. This configuration means the fallback will
trigger specifically when an UnknownHostException occurs.
The runtime behavior of @Fallback follows these steps:
1. Primary method execution fails with an exception.
2. Runtime checks if the exception matches any
skipOn exceptions:
•
If yes, the exception propagates normally.
3. Runtime checks if the exception matches any
applyOn exceptions:
•
If yes, the fallback method is invoked.
•
If no, the exception propagates normally.
4. Fallback method executes with the same parameters
as the primary method.
362
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Using a Fallback Handler
For more complex fallback scenarios, the @Fallback annotation supports
an alternative approach using a FallbackHandler class. This approach
offers several advantages over the fallback method:
•
Separates fallback logic into a dedicated class
•
Provides access to execution context and failure
information
•
Allows for more sophisticated fallback
implementations
•
Enables reuse across multiple methods
Implementing aFallbackHandler
public class RateConversionFallbackHandler implements
FallbackHandler<BigDecimal> {
@Inject
private RateCache rateCache; // Example of dependency
injection
@Override
public BigDecimal handle(ExecutionContext context) {
String sourceCurrency = (String) context.
getParameters()[0];
BigDecimal amount = (BigDecimal) context.
getParameters()[1];
String targetCurrency = (String) context.
getParameters()[2];
Throwable failure = context.getFailure();
363
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Logger.warn("Currency conversion failed: {}",
failure.getMessage());
try {
if (rateCache.hasRate(sourceCurrency,
targetCurrency)) {
BigDecimal rate = rateCache.
getRate(sourceCurrency, targetCurrency);
return amount.multiply(rate);
}
return amount;
} catch (Exception e) {
Logger.error("Fallback processing
failed", e);
return amount;
}
}
}
The above code shows a complete implementation of a fallback
handler for the ResilientRateService currency conversion component.
The fallback handler implements FallbackHandler<T>’s handle
method, which takes an org.eclipse.microprofile.faulttolerance.
ExecutionContext object. The ExecutionContext interface provides
information about the original method for which this implementation is
a fallback. The handle method of the FallbackHandler interface has the
same return type as the convert method for which it’s acting as a fallback.
The fallback handler can now be applied as shown in Listing 8-2.
364
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Listing 8-2. The application of the fallback handler
@Fallback(
value = RateConversionFallbackHandler.class,
applyOn = {ConnectException.class,
UnknownHostException.class},
skipOn = {IllegalArgumentException.class}
)
public BigDecimal convert(String sourceCurrency, BigDecimal
amount, String targetCurrency) {
return externalRateService.
convertCurrency(sourceCurrency, amount, targetCurrency);
}
The fallback handler is passed as the implementing class to the
@Fallback annotation through the value parameter.
The @Fallback annotation provides a safety net when operations
fail, ensuring your application can gracefully handle unexpected errors
and continue serving requests. Working hand in hand with fallbacks,
the @Timeout annotation adds another layer of resilience by preventing
operations from running indefinitely, helping maintain system
responsiveness even under challenging conditions.
@Timeout
In distributed systems, operations can sometimes take longer than
expected or hang indefinitely. A network call might never return, a
database query could stall, or a third-party service might become
unresponsive. Left unchecked, these scenarios can cascade into system­
wide failures, with threads getting blocked and resources becoming
exhausted. This is where the @Timeout annotation comes in—it acts as a
safety valve, ensuring that operations complete within a reasonable time
frame or fail fast if they cannot.
365
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
At its core, a timeout is a constraint that limits how long an operation
can run. Think of it as setting an alarm clock for your code: if the operation
hasn’t finished by the time the alarm rings, it’s interrupted and an
exception is thrown. This seemingly simple mechanism is crucial for
building robust distributed systems.
The @Timeout annotation can be applied at either the method
or class level. Listing 8-3 shows the annotation being applied to the
ResilientRateService.
Listing 8-3. Class-level @Timeout annotation
@ApplicationScoped
@Timeout
public class ResilientRateService extends SimpleRateService {
@Override
public BigDecimal convert(String sourceCurrency, BigDecimal
amount, String targetCurrency) {
return super.convert(sourceCurrency, amount,
targetCurrency);
}
private BigDecimal fallbackConvert(String sourceCurrency,
BigDecimal amount, String targetCurrency) {
return amount;
}
}
At the class level as shown above, all methods in the class will time out
after a default of 1,000 milliseconds. The timeout duration and unit can be
customized by passing the value and unit parameters to the annotation as
shown in Listing 8-4.
366
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Listing 8-4. A customized @Timeout annotation
@ApplicationScoped
@Timeout(value = 5, unit = ChronoUnit.SECONDS)
public class ResilientRateService extends SimpleRateService {
@Override
public BigDecimal convert(String sourceCurrency, BigDecimal
amount, String targetCurrency) {
return super.convert(sourceCurrency, amount,
targetCurrency);
}
private BigDecimal fallbackConvert(String sourceCurrency,
BigDecimal amount, String targetCurrency) {
return amount;
}
}
The timeout period in the above example is set to 5 with a timeout unit
of seconds. All methods in this class will time out with a TimeoutException
if they do not return after 5 seconds. This prevents the thread from being
blocked indefinitely and allows the system to handle the failure gracefully,
especially as the rate service might depend on an external API service for
real-time exchange rates.
The @Timeout annotation can also be declared at the method level.
The annotation at the method level takes precedence over the class-level
annotation. So, for example, another method in the ResilientRateService
could declare a timeout of 10 nanoseconds instead of the class-level 5
seconds. The @Timeout of the method level will take precedence.
While timeouts effectively prevent operations from hanging
indefinitely, they represent only half the solution. A timeout tells us
when to stop waiting, but it doesn’t tell us what to do next. In many cases,
especially in distributed systems, a timeout doesn’t necessarily mean
367
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
the operation is fundamentally broken—it might just be experiencing
temporary difficulties. The network might be congested, a service might be
recovering from a restart, or a database might be experiencing momentary
high load.
The @Retry annotation provides the other half of the solution by
answering the question: when an operation fails (whether due to a timeout
or other issues), should we try again? And if so, how?
@Retry
Almost all modern applications need to make network calls to other
services, whether they’re within the same network or external. Network
glitches can cause these calls to fail temporarily. In such cases, having a
mechanism to automatically retry the failed operation can help maintain
service reliability. The @Retry annotation provides this capability by
automatically retrying failed operations based on configurable criteria.
The annotation is used to automatically retry operations that fail with
exceptions. When applied to a method, it will intercept any exceptions
thrown and attempt to execute the method again according to the
configured retry policy. Listing 8-5 shows an example usage on the
convertCurrencyAsync method.
Listing 8-5. @Retry annotation
@Retry(maxRetries = 4,
delay = 200,
jitter = 100,
retryOn = IOException.class)
public CompletionStage<ConvertCurrencyResponse>
convertCurrencyAsync(
368
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
final ConvertCurrencyRequest convertCurrencyRequest) {
return CompletableFuture.completedFuture(convert(convert
CurrencyRequest));
}
The example in Listing 8-5 uses the @Retry annotation to add
resilience to the convertCurrencyAsync method, which handles currency
conversion requests asynchronously. If an IOException occurs during the
conversion process, the method will automatically retry up to four times.
The retries have a base delay of 200 milliseconds with a random variation
of up to 100 milliseconds to prevent overwhelming the underlying service
and allow for potential recovery. This ensures that transient network issues
are less likely to disrupt the currency conversion process.
The @Retry annotation supports several parameters to customize its
behavior:
•
maxRetries: Maximum number of retry attempts
(default: 3)
•
delay: Time to wait between retries in milliseconds
(default: 0)
•
delayUnit: Unit for the delay value (default:
ChronoUnit.MILLIS)
•
maxDuration: Maximum time to keep retrying (default:
180000ms)
•
durationUnit: Unit for maxDuration (default:
ChronoUnit.MILLIS)
•
jitter: Random variation in retry delays (default: 200ms)
•
retryOn: Array of exception types that trigger retries
•
abortOn: Array of exception types that abort retries
369
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Retry Behavior
When a method with @Retry annotation returns, the following rules are
applied:
•
If the method returns normally (no exception), the
result is returned immediately.
•
If an exception is thrown that matches any type in
abortOn, it’s rethrown immediately.
•
If an exception is thrown that matches any type in
retryOn, a retry is attempted.
•
If neither condition matches, the exception is rethrown.
In the example in Listing 8-5, any IOException thrown during
execution of the annotated method will cause the method to be retried a
maximum of four times.
Jitter andDelays
The jitter parameter adds randomness to retry delays to prevent
synchronized retries across multiple instances. With jitter set to 200
(default)
370
•
Effective delay range = [delay - jitter, delay + jitter].
•
If delay is 0, effective range = [0, 200].
•
Negative effective delays are treated as 0.
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Maximum Duration
The maxDuration parameter sets an overall time limit for the retry process.
Once this duration is reached, no more retries will be attempted, even
if maxRetries hasn’t been reached. This prevents excessive retries from
impacting system performance.
Scope andApplication
@Retry can be applied at either the method or class level:
•
Method Level: Affects only the annotated method.
•
Class Level: Applies to all methods in the class.
•
When Both Present: Method-level annotation takes
precedence.
Remember that the @Retry state is evaluated fresh for each method
invocation—there is no shared state between different calls to the same
method. While this makes @Retry excellent for handling transient failures,
it may not be the best choice when dealing with systemic problems
that affect multiple calls over time. In such cases, repeatedly retrying
might actually worsen the situation by increasing load on an already
stressed system.
This is where circuit breaker patterns become essential. Rather than
continuously retrying failing operations, a circuit breaker can temporarily
stop all attempts when it detects a systemic problem, giving the underlying
system time to recover.
371
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
@CircuitBreaker
In distributed systems, failing components can create cascading failures
that ripple through an entire application. When a service is failing
consistently, continuing to make calls to it can waste resources and
degrade the overall system performance. The circuit breaker pattern,
implemented through the @CircuitBreaker annotation, prevents this by
failing fast when a service shows signs of systematic failure.
A circuit breaker operates in three distinct states, managing access to
protected methods based on their failure patterns.
Closed State (Normal Operation)
•
Default starting state
•
Allows calls to pass through to the protected method
•
Monitors failures and maintains statistics in a
rolling window
•
Transitions to Open if the failure threshold is exceeded
Open State (Fail Fast)
372
•
Immediately rejects calls with
CircuitBreakerOpenException
•
Prevents resource exhaustion
•
Allows the failing component time to recover
•
Transitions to Half-Open after configured delay
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Half-Open State (Recovery Testing)
•
Allows a limited number of test calls through
•
Success: Returns to the Closed state
•
Failure: Returns to the Open state
•
Acts as a safe way to test system recovery
Circuit Breaker Usage
Listing 8-6 shows the use of the @CircuitBreaker annotation on the
convertCurrency method.
Listing 8-6. Circuit breaker annotation use
@CircuitBreaker(
requestVolumeThreshold = 4,
failureRatio = 0.5,
delay = 1000
)
public ConvertCurrencyResponse convertCurrency(final
ConvertCurrencyRequest convertCurrencyRequest) {
return convert(convertCurrencyRequest);
}
This code uses the @CircuitBreaker annotation to protect the
convertCurrency method by temporarily stopping calls to it if at least four
requests are made and 50% of them fail, allowing the system to recover for
1 second before accepting new requests.
373
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
The @CircuitBreaker annotation offers extensive configuration options
through its parameters as follows:
•
failOn: Exception types that count as failures (default:
Throwable.class)
•
skipOn: Exception types to ignore when counting
failures
•
delay: Time circuit stays open before testing recovery
(default: 5000ms)
•
delayUnit: Time unit for delay (default:
ChronoUnit.MILLIS)
•
requestVolumeThreshold: Size of rolling window
(default: 20)
•
failureRatio: Failure threshold to open circuit
(default: 0.5)
•
successThreshold: Successes needed in Half-Open
state to close (default: 1)
These parameters can be combined to create a very sophisticated
circuit breaker implementation as shown in Listing 8-7.
Listing 8-7. Advanced @CircuitBreaker pattern usage
@CircuitBreaker(
failOn = {ServiceException.class,
ConnectException.class},
skipOn = ValidationException.class,
requestVolumeThreshold = 10,
failureRatio = 0.3,
delay = 2000,
successThreshold = 2
)
374
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
@Fallback(fallbackMethod = "convertCurrencyFallback")
public ConvertCurrencyResponse convertCurrency(final
ConvertCurrencyRequest convertCurrencyRequest) {
return convert(convertCurrencyRequest);
}
The @CircuitBreaker annotation instructs the system to temporarily
stop executing the method if it encounters frequent failures (specifically,
30% or more failures out of ten consecutive calls), giving it a 2-second
pause to recover. This circuit breaker is triggered by ServiceException
and ConnectException, but ignores ValidationException. Furthermore,
the @Fallback annotation ensures that if the circuit breaker trips, the
convertCurrencyFallback method will be called instead, providing a
graceful alternative to prevent complete service disruption.
Failure Counting Rules
When a method protected by @CircuitBreaker returns, the following rules
determine if it counts as a failure:
•
Normal Return: Counted as success
•
Exception Matching skipOn: Not counted
•
Exception Matching failOn: Counted as failure
•
Other Exceptions: Not counted
Integration with Other Patterns
@CircuitBreaker works well with other fault tolerance patterns:
•
With @Retry: Each retry attempt is counted separately.
•
With @Fallback: Provides an alternative when circuit
is open.
375
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
•
With @Timeout: Timeout exceptions can trigger the
circuit breaker.
•
With @Bulkhead: Applied before attempting to acquire
bulkhead slot.
If the annotation is used at the class level, then all methods in the class
will have circuit breakers. If used on a class and a method inside that class,
then the @CircuitBreaker at the method level takes precedence over the
class-level annotation for that method.
Managing Circuit State
Unlike @Retry, circuit breaker state persists between method calls.
The state is maintained independently for each unique combination of
protected class and method. This means that a failing method in one part
of your application won’t affect circuit breakers protecting other methods.
While circuit breakers are good at preventing cascading failures by
isolating failing services, they don’t address all aspects of system resilience.
For instance, a properly functioning but overwhelmed service might still
consume too many resources, potentially impacting other parts of the
system. This is where the bulkhead pattern comes in handy—by limiting
concurrent calls to a component, it ensures that no single service can
monopolize system resources.
@Bulkhead
The @Bulkhead annotation is a fault tolerance mechanism designed
to prevent system overload by limiting concurrent access to services.
The bulkhead pattern, inspired by ship construction, isolates failures
within a system to prevent cascading failures that could bring down the
entire system. This is achieved by restricting the number of concurrent
376
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
requests that can access a particular method or service. The bulkhead
implementation offers two approaches depending on how the annotation
is used.
Semaphore-Style Bulkhead
When @Bulkhead is used without @Asynchronous (covered in the next
section), the semaphore isolation approach is applied. This style simply
limits the number of concurrent executions. Listing 8-8 shows this
approach.
Listing 8-8. Semaphore bulkhead approach usage
@Bulkhead
public ConvertCurrencyResponse convertCurrency(final
ConvertCurrencyRequest convertCurrencyRequest) {
return convert(convertCurrencyRequest);
}
In this example, only five concurrent requests are allowed to execute
the method at any time. When the concurrent request limit is reached, any
additional requests will fail immediately with a BulkheadException.
Thread Pool-Style Bulkhead
When @Bulkhead is used together with @Asynchronous, the thread pool
isolation approach is used. This style not only limits concurrent executions
but also provides a waiting queue for pending requests. Listing 8-9 shows
this approach.
377
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Listing 8-9. Thread pool-style bulkhead approach usage
@Asynchronous
@Bulkhead(value = 5, waitingTaskQueue = 8)
public CompletionStage<ConvertCurrencyResponse>
convertCurrencyAsync(
final ConvertCurrencyRequest convertCurrencyRequest) {
return CompletableFuture.completedFuture(convert
(convertCurrencyRequest));
}
This configuration
•
Allows maximum five concurrent executions
•
Maintains a waiting queue that can hold up to eight
requests
•
Throws a BulkheadException when both the execution
slots are full and the waiting queue is full
Integration with Other Fault
Tolerance Annotations
The @Bulkhead annotation can be used in conjunction with other fault
tolerance annotations:
378
•
With @Fallback: The fallback will be triggered if a
BulkheadException is thrown.
•
With @CircuitBreaker: The circuit breaker is checked
before attempting to enter the bulkhead.
•
With @Retry: When a BulkheadException occurs,
the request may be retried based on the retry
configuration.
CHAPTER 8
•
RESILIENCE WITH THE FAULT TOLERANCE API
With @Timeout: For asynchronous bulkheads,
the timeout duration includes both queuing and
execution time.
Lifecycle Management
Bulkhead state (tracking concurrent executions and queue) is maintained
as a singleton, regardless of the bean’s scope. The state is uniquely
identified by the combination of
•
The bean class (java.lang.Class)
•
The guarded method (java.lang.reflect.Method)
For example, if a @RequestScoped bean has a bulkhead-protected
method, while each request gets its own bean instance, all invocations
share the same bulkhead state.
While bulkhead patterns help control and isolate concurrent access,
there are scenarios where you need to handle long-running operations
without blocking the client thread. The @Asynchronous annotation
provides this capability by executing operations on separate threads,
making it a fundamental building block for responsive and scalable
microservices.
@Asynchronous
The @Asynchronous annotation is a key component of MicroProfile
Fault Tolerance that enables asynchronous execution of methods. When
a method is annotated with @Asynchronous, its execution occurs on a
separate thread from the calling thread, providing non-blocking behavior
in your applications.
379
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Basic Usage
The @Asynchronous annotation can be applied at either the class or
method level. When applied to a class, all methods within that class will
execute asynchronously. When applied at the method level, only the
specifically annotated method executes asynchronously.
Methods annotated with @Asynchronous must return either
java.util.concurrent.Future<T> or java.util.concurrent.CompletionStage<T>.
The specification recommends using CompletionStage as the return type
when possible, as it provides better integration with other fault tolerance
features and more flexible composition of asynchronous operations.
The @Asynchronous annotation does not take any parameter. Its example
usage can be found in Listing 8-9.
Integration with Other Fault
Tolerance Annotations
The @Asynchronous annotation works with other fault tolerance features.
When used with @Retry, any retry attempts occur on the asynchronous
thread, with the retry logic executing after the asynchronous execution
begins. This means that if an asynchronous operation fails, the retry will
happen in the background without blocking the calling thread.
When combining @Asynchronous with @Fallback, the fallback method
must maintain signature compatibility with the original method. This
means it must return the same type (Future<T> or CompletionStage<T>)
as the original method and execute asynchronously just like the original
method. This ensures consistent behavior whether the primary execution
succeeds or falls back to the alternative implementation.
Timeout behavior becomes interesting when @Asynchronous is used
with @Timeout. The timeout period encompasses the entire asynchronous
execution, and when using CompletionStage, the method isn’t considered
380
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
complete until the returned CompletionStage completes. If a timeout
occurs, it will interrupt the executing thread.
The combination of @Asynchronous with @Bulkhead as used in
Listing 8-9 automatically switches to thread pool isolation instead of
semaphore isolation. This allows for configuration of both concurrent
execution limits and waiting queue size. The execution is considered
running until the returned Future or CompletionStage completes, ensuring
proper resource management.
Context and Exception Handling
Context handling is an important consideration with asynchronous
execution. The specification ensures that the RequestScoped context
remains active during the asynchronous method invocation, maintaining
proper context propagation to the asynchronous thread.
Exception handling in asynchronous methods differs from
synchronous code. Exceptions never propagate directly to the
calling thread. Instead, they are wrapped in the returned Future or
CompletionStage. When using Future, exceptions are wrapped in an
ExecutionException when calling get(). With CompletionStage, exceptions
trigger any registered error handlers, providing a more flexible error
handling approach.
Implementation Considerations
While @Asynchronous doesn’t have configurable parameters, its behavior
is influenced by the container integration settings and thread pool
configurations in your runtime environment. When running in a Jakarta EE
container, threads servicing @Asynchronous invocations maintain proper
security and naming contexts throughout the method execution.
381
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
For optimal usage, prefer CompletionStage over Future as the return
type. This choice provides better integration with other fault tolerance
features and more flexible composition of asynchronous operations.
Always consider the implications of context propagation in your
asynchronous methods and ensure proper exception handling through the
asynchronous execution chain. When combining with other fault tolerance
features, be mindful of resource usage and potential interactions between
different fault tolerance mechanisms.
The flexibility of Fault Tolerance annotations extends beyond their
basic usage through MicroProfile Config, which allows you to externalize
and customize fault tolerance behavior. Let’s explore how to configure
these fault tolerance capabilities.
Configuring Fault Tolerance with Config
MicroProfile Fault Tolerance adopts the MicroProfile Config specification
to provide flexible configuration of fault tolerance policies. This integration
enables you to modify fault tolerance behavior without changing code,
making your applications more adaptable across different environments.
Configuration Patterns
Each fault tolerance annotation’s parameters can be configured through
three increasingly specific levels: global, class-level, and method-level. For
example, to configure the maxRetries parameter for the retry method in
Listing 8-5, you would use the property
com.example.RateService/convertCurrencyAsync/Retry/maxRetries=5
This configuration follows the pattern <classname>/<methodname>/<
annotation>/<parameter>, where each component precisely identifies the
target of the configuration.
382
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Configuration Hierarchy
The configuration system follows a clear precedence order. Method-level
configurations take precedence over class-level configurations, which in
turn override global configurations. This hierarchy allows for fine-grained
control while maintaining sensible defaults.
To configure all retry operations in the RateService class, you
would use
com.example.RateService/Retry/maxRetries=8
For application-wide retry configuration, the property becomes even
simpler:
Retry/maxRetries=10
This hierarchical approach enables you to establish baseline behaviors
at the application level while allowing specific overrides where needed.
For instance, you might set conservative timeouts globally but configure
more generous limits for known long-running operations.
Dynamic Properties
While fault tolerance parameters can be configured through various
MicroProfile Config sources, some properties, such as MP_Fault_
Tolerance_NonFallback_Enabled and the fault tolerance interceptor
priority, are only read during application startup. This design choice
ensures consistent behavior during runtime while still providing
deployment-time flexibility.
383
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Configuration Effect
When you provide a configuration value, it completely replaces the
corresponding parameter in the annotation. For example, if a method is
annotated with @Retry(maxRetries=3) and you configure com.example.
Service/methodName/Retry/maxRetries=5, the method will use 5 as its
maxRetries value. This behavior is designed to ensure that configuration
takes precedence over hardcoded values, supporting the principle of
externalized configuration.
Summary
In this chapter, you learned how to build resilient Jakarta EE applications
using MicroProfile Fault Tolerance annotations and patterns. Key
takeaways include the following:
384
•
Apply fault tolerance patterns like fallbacks, timeouts,
retries, circuit breakers, and bulkheads to handle
failures gracefully.
•
Implement patterns using annotations like @Fallback,
@Timeout, @Retry, @CircuitBreaker, @Bulkhead, and
@Asynchronous.
•
Combine annotations thoughtfully for resilience and
use @Asynchronous for long-running operations.
•
Externalize fault tolerance configuration using
MicroProfile Config to enable dynamic modifications
without code changes.
CHAPTER 8
RESILIENCE WITH THE FAULT TOLERANCE API
Fault tolerance techniques are critical for building resilient distributed
systems. These techniques ensure your microservices gracefully handle
failures, optimize resource usage, and recover effectively, leading to a more
reliable and performant architecture.
Now, let’s explore another key aspect of managing microservices:
observability through the MicroProfile Telemetry specification.
385
CHAPTER 9
Metrics for Jakarta
EE Applications:
Monitoring and
Observability
Modern cloud-native applications need reliable observability to
help teams understand system behavior and troubleshoot issues in
production. This chapter explores how to implement observability in
Jakarta EE applications using the MicroProfile 7.0 Telemetry and Metrics
specifications.
MicroProfile 7.0 emphasizes observability, aligning with the
industry standard, OpenTelemetry. The new MicroProfile Telemetry
specification provides a common API for tracing, with Telemetry 2.0 using
OpenTelemetry metrics. While MicroProfile Metrics is still supported
for backward compatibility, the API has been updated to allow for
multiple implementations, including Micrometer and OpenTelemetry.
Functionally, OpenTelemetry metrics (as used in Telemetry 2.0) and
MicroProfile Metrics are equivalent. This chapter will cover both
MicroProfile Metrics, due to its widespread use, and tracing with
OpenTelemetry.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_9
387
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
By the end of this chapter, you will be able to
•
Understand the three pillars of observability: metrics,
logs, and traces.
•
Implement metrics collection in your Jakarta EE
applications using MicroProfile Metrics.
•
Set up distributed tracing using MicroProfile Telemetry.
•
Configure and integrate with popular monitoring
solutions.
•
Apply best practices for effective application
observability.
Understanding Observability
Observability is the ability to understand a system's internal state by
examining its outputs. Unlike traditional monitoring that tells you when
something is wrong, observability helps you understand why something is
wrong. It enables teams to
388
•
Debug production issues efficiently.
•
Understand system behavior in real time.
•
Make data-driven decisions about performance and
reliability.
•
Reduce Mean Time To Resolution (MTTR).
•
Proactively identify potential issues.
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
The Three Pillars of Observability
Modern observability is built on three fundamental pillars:
1. Metrics: Numerical measurements collected over
time that provide quantitative data about system
performance and behavior
2. Logs: Timestamped records of discrete events that
provide detailed context about specific occurrences
3. Traces: Records that track the journey of requests as
they flow through distributed systems
Jakarta EE applications can implement observability through the
MicroProfile Telemetry specification. Let’s start by looking at the metrics
part of the specification.
Deployed, user-facing applications need to be monitored to ensure
they are delivering as expected. Cloud-native applications deployed to
complex cloud hosting environments need to be monitored even more
because any unexpected deviation from preset expectations could mean
significant extra hosting bills.
The way to monitor deployed, running applications is through the
use of application metrics. Different metrics such as how many times a
method has been called and how many seconds did a given method take
to return are all different kinds of metrics that can give insights into how an
application is performing.
389
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Taking Count of Distributed Tracing
with MicroProfile Telemetry Metrics
The MicroProfile Metrics part of the Telemetry specification provides a
set of API constructs for exposing different types and kinds of application
metrics. With this API, you can expose application, implementation
runtime, and Java Virtual Machine (JVM) metrics through annotations
and a Java API in the OpenMetrics format, consumable by monitoring
applications like Prometheus.
The Structure
MicroProfile Metrics is mostly a metadata-driven API for exposing metrics
in an application. The scope and type of metrics you can expose depends
on the application requirements. All the metrics exposed through the use
of this API are hosted automatically under the context path /metrics.
For local development, this will mostly be htttp://localhost:8080/
metrics, and for an application deployed to foo.com, the metrics will be
hosted at https://foo.com/metrics. The specification defines three
scopes or categories of metrics. These are base, application, and vendor­
specific metrics.
Base Metrics
The base metrics are metrics that all implementations are mandated to
provide. These metrics expose information about the underlying JVM and
operating system. Some of these base metrics are available processors
and used, maximum, and committed heap memory among others. There
are some metrics under base metrics that could be optional as they could
pertain to specific JVM or operating system release. These metrics are
hosted at the path /metrics/base.
390
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Application Metrics
Application metrics are the set of custom metrics that you would like
to collect about your application. You can use either annotations or the
Java API to expose these metrics. Examples of such metrics are how long
it takes for a given method to execute. These metrics are accessible at /
metrics/application.
Vendor Metrics
Vendor metrics are custom metrics that a compatible implementation of
the MicroProfile specification optionally provides on top of the mandatory
base metrics. The vendor metrics are hosted at /metrics/vendor.
Metrics Data Format
By default, when a GET request is made to the /metrics resource, the
returned metrics information is in the OpenMetrics text format. This is an
open standard format for metrics supported by a number of monitoring
applications like Prometheus.
However, the same metrics data can be returned in the JSON format
if the Accept header of the HTTP request matches application/json. If the
Accept header of the request matches both application/json and text/plain
or no Accept header is specified, then the data is returned in the default
OpenMetrics text format.
The Metrics Registry
The metrics registry is a registry of all metrics that can be accessed under
the /metrics resource and their metadata. There is a shared singleton
registry for each of the three metrics scopes of base, application, and
vendor. Metrics are identified in the registry through their metrics ID
391
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
comprising their names and tags (if available). Think of the metrics registry
as a database of the metrics found in each scope. The registry will be
transparent to you as an application developer most of the time. But you
should know it’s there when you have to interact with it.
Using Metrics
There are two ways you can use the Metrics API in your application. One
is through annotations, and the other is through the Java API. Whichever
you choose is only a matter of application requirements and developer
preference. The annotations are interceptor bindings that are managed by
the CDI runtime. Consequently, only proxyable managed beans can use
the annotations for collecting metrics.
Annotations
There are six annotations for creating different kinds of metrics. These are
•
@Counted
•
@ConcurrentGauge
•
@Gauge
•
@Metered
•
@SimplyTimed
•
@Timed
All these annotations have parameters that are common to all of them.
These are shown in Table 9-1.
392
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Table 9-1. Common Metrics Annotation Parameters
Name
Type
Description
Optional/Required
name
String
Sets the name of the metric.
Optional. Defaults to the
name of the annotated
object
absolute
Boolean
If true, name is used as the
Optional. Defaults to false
absolute name of the metric.
If false, prepends the package
name and class name before
the given name.
displayName
String
Human-readable name for
Optional. Defaults to null
metadata.
Optional. Defaults to null
description
String
A description of the metric.
unit
String
The unit of the specific metric. Optional. Different
defaults
tags
String[]
An array of “key=value” tags
Optional. Empty array
for the metric.
@Counted
The @Counted metrics annotation counts the number of times the
annotated method, constructor, or type is invoked or instantiated. This
annotation can be used on a method, constructor, or class. If used at the
class level, all methods in that class will have their invocations counted.
Listing 9-1 shows method convetrCurrency in the RateResourceImpl class
annotated with @Counted, passing in some parameters.
393
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Listing 9-1. The use of @Counted
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("rates")
public class RateResourceImpl {
@Path("convert")
@POST
@Counted(name = "convert_currency",
absolute = true,
displayName = "Convert currency method",
description = "Method to convert one currency to
the other",
tags = { "info=conversions", "type=meta" })
ConvertCurrencyResponse convertCurrency(@Valid
ConvertCurrencyRequest convertCurrencyRequest){
return rateService.convertCurrency(convertCurrencyRequest)
};
}
Listing 9-1 shows the @Counted annotation used on the
convertCurrency method.
It has the name parameter set and the absolute set to true. This means
the name of this metric that will be registered in the registry is convert_
currency. If absolute was not set to true, the name of the metric would be
package name + class name + passed value to the name parameter. The
tags are also set to some method-specific info.
Tags play an important role in metrics because in a cloud-native
environment where orchestration of deployed containers is done by
engines like Kubernetes, the traditional mapping of application runtime
and host is no longer the case. In the context of metrics, tags add an
additional dimension for identifying metrics in addition to the name of the
metrics.
394
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
The counted metric can be accessed directly from /metrics/
application/convert_currency when the application is deployed. The
name of the metric is enough to access it via the REST endpoint because
the absolute parameter was set to true. A sample call for this metric in the
OpenMetrics format returns the result shown in Listing 9-2.
Listing 9-2. Sample metric for @Counted
# TYPE application_convert_currency_total counter
# HELP application_convert_currency_total Method to convert one
currency to the other
application_convert_currency_total{info="conversions",type=
"meta"} 75
Listing 9-2 shows the @Counted annotation when accessed directly
from the /metrics/application context path.
The returned data is annotated with TYPE and HELP that show
the type and description of the metric, respectively. The metric count
is preceded by application_. This is how application-level metrics are
differentiated from base and vendor-level metrics. The tags passed to the
@Counted annotation are also returned as part of the full metric ID. As per
the count, the convertCurrency method has been called a total of 75 times.
@ConcurrentGauge
This annotation is used to gauge concurrent invocations of an annotated
method or constructor or instantiations of an annotated class. This metric
works by incrementing the parallel count by one when the annotated
element is entered and decremented by the same number when exited.
This metric gauges the number of concurrent invocations of the annotated
element.
395
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
When used on a class, any parallel invocation counter for the current,
previous minute maximum, and previous minute minimum is created and
registered in the metrics registry for each constructor and method of the
class using the name and absolute field values of the annotation.
When used on a method, the metric gauges for the current, previous
minute maximum, and previous minute minimum are created and
registered in the metrics registry. When used on a constructor, the
same gauges for that constructor are registered. Listing 9-3 shows the
convertCurrency method annotated with @ConcurrentGauge.
Listing 9-3. @ConcurrentGauge on the convertCurrency method
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("rates")
public class RateResourceImpl {
@Path("convert")
@POST
@ConcurrentGauge(name = "convert_currency_
concurrent_gauge",
absolute = true,
description = "Method to convert one currency to
the other",
tags = { "convert=custom" }
)
ConvertCurrencyResponse convertCurrency(@Valid
ConvertCurrencyRequest convertCurrencyRequest){};
}
Listing 9-3 shows the convertCurrency method annotated with
@ConcurrentGauge.
396
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
The name, absolute, and description are set, along with some custom
tags. This is accessible at /metrics/application/convert_currency_
concurrent_gauge. A sample call for the default text format returns the
data as shown in Listing 9-4.
Listing 9-4. The result for the @ConcurrentGauge metric
# TYPE application_convert_currency_concurrent_gauge_
current gauge
# HELP application_convert_currency_concurrent_gauge_current
Method to convert one currency to the other
application_convert_currency_concurrent_gauge_
current{convert="custom"} 0
# TYPE application_convert_currency_concurrent_gauge_min gauge
application_convert_currency_concurrent_gauge_
min{convert="custom"} 0
# TYPE application_convert_currency_concurrent_gauge_max gauge
application_convert_currency_concurrent_gauge_
max{convert="custom"} 1
@Gauge
The @Gauge metric is used to sample the return value of a method.
This method is mostly a business method that returns some form of
meaningful, business context value for analysis. The method will be
invoked by the Metrics runtime and the return value assigned as the value
of the metric. @Gauge can be used for only methods.
As an example, if we want to sample the number of currency
conversions in jwallet, @Gauge is the perfect metric for that. The return
value of the method is the value of the metric. This metric can only be
used with @ApplicationScoped or @Singleton CDI beans because using
it with other non-singleton beans will not be clear as to which instance
397
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
of the bean to use for obtaining the gauge value. Listing 9-5 shows
the RateService @ApplicationScoped bean with a countConversions
gauge method.
Listing 9-5. @Gauge usage
@ApplicationScoped
public class RateService {
@Gauge(name = "convert_currency_gauge_count", unit =
MetricUnits.NONE, absolute = true)
public int countConversions() {
return ThreadLocalRandom.current().nextInt(250,
500 + 1);
}
}
Listing 9-5 shows the RateService singleton with a countConversions
method that returns an int.
When this metric is queried, the runtime will call this method and
use the returned method value as the value of the metric. With the name,
this metric can be directly accessed from the path /metrics/application/
convert_currency_gauge_count. A sample invocation return data is shown
in Listing 9-6.
Listing 9-6. Sample return data for the @Gauge metric
# TYPE application_convert_currency_gauge_count gauge
application_convert_currency_gauge_count 474
@Metered
The @Metered annotation is a metric that tracks the frequency of
invocations of the annotated method or constructor or class instantiation.
It tracks the mean throughput and one-, five-, and fifteen-minute
398
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
exponentially weighted moving average throughput. The default
MetricUnit is seconds. @Metered can be used on a class, method, or
constructor.
Listing 9-7. The convertCurrency method with the @Metered
annotation
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("rates")
public class RateResourceImpl implements RateResource {
@Inject
RateService rateService;
@Path("convert")
@POST
@Override
@Metered(name = "convert_currency_meter", absolute = true)
public ConvertCurrencyResponse convertCurrency(ConvertCurre
ncyRequest convertCurrencyRequest) {
return rateService.convertCurrency(convert
CurrencyRequest);
}
}
Listing 9-7 shows the @Metered annotation on the
convertCurrency method.
With the passed absolute name, the metric can be queried from
the path /metrics/application/convert_currency_meter, with a sample
returned data shown in Listing 9-8.
399
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Listing 9-8. The @Metered sample returned data for the
convertCurrency method
# TYPE application_convert_currency_meter_total counter
application_convert_currency_meter_total 5
# TYPE application_convert_currency_meter_rate_per_second gauge
application_convert_currency_meter_rate_per_second
0.017981750828888407
# TYPE application_convert_currency_meter_one_min_rate_per_
second gauge
application_convert_currency_meter_one_min_rate_per_second
0.009080280587651975
# TYPE application_convert_currency_meter_five_min_rate_per_
second gauge
application_convert_currency_meter_five_min_rate_per_second
0.3266223165978052
# TYPE application_convert_currency_meter_fifteen_min_rate_per_
second gauge
application_convert_currency_meter_fifteen_min_rate_per_second
0.5934799986177786
@SimplyTimed
The @SimplyTimed annotation is a metric for marking a method,
constructor, or class as simply timed. By simply timed, it means a
timer to track elapsed time duration and count. It measures duration
in nanoseconds. Listing 9-9 shows the convertCurrency method of
RateResourceImpl simply timed with @SimplyTimed.
400
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Listing 9-9. The @SimplyTimed annotation on convertCurrency
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("rates")
public class RateResourceImpl implements RateResource {
@Inject
RateService rateService;
@Path("convert")
@POST
@Override
@SimplyTimed(name = "convert_currency_simple_timer",
absolute = true)
public ConvertCurrencyResponse convertCurrency(Convert
CurrencyRequest convertCurrencyRequest) {
return rateService.convertCurrency(convertCurrency
Request);
}
}
Listing 9-9 shows the @SimplyTimed metric, passed the absolute name
convert_currency_simple_timer, making this metric directly accessible
from /metrics/application/convert_currency_simple_timer.
A call to that endpoint returns the sample data shown in Listing 9-10.
Listing 9-10. The result for the @SimplyTimed metric on
convertCurrency
# TYPE application_convert_currency_simple_timer_total counter
application_convert_currency_simple_timer_total 45
# TYPE application_convert_currency_simple_timer_elapsedTime_
seconds gauge
401
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
application_convert_currency_simple_timer_elapsedTime_seconds
33.182224819000005
# TYPE application_convert_currency_simple_timer_
maxTimeDuration_seconds gauge
application_convert_currency_simple_timer_maxTimeDuration_
seconds 1.5874110110000001
# TYPE application_convert_currency_simple_timer_
minTimeDuration_seconds gauge
application_convert_currency_simple_timer_minTimeDuration_
seconds 0.586819599
@Timed
The @Timed metric is used to track how frequently a class, constructor,
or method is invoked and tracks how long it took the invocations to
complete. @Timed aggregates timing durations to provide duration
and throughput statistics for the annotated object. It is a much more
detailed metric relative to @SimplyTimed that only tracks elapsed time
duration and count. Listing 9-11 shows the convertCurrency method
annotated @Timed.
Listing 9-11. Usage of @Timed
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("rates")
public class RateResourceImpl implements RateResource {
@Inject
RateService rateService;
@Path("convert")
@POST
@Override
402
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
@Timed(name = "convert_currency_timer", absolute = true)
public ConvertCurrencyResponse convertCurrency(Convert
CurrencyRequest convertCurrencyRequest) {
return rateService.convertCurrency(convertCurrency
Request);
}
}
Listing 9-11 shows the @Timed metric on the
convertCurrency method.
With the absolute name, the metric can be accessed directly from /
metrics/application/convert_currency_timer. A sample call returns the
metrics data shown in Listing 9-12.
Listing 9-12. The @Timed metrics data
# TYPE application_convert_currency_timer_rate_per_second gauge
application_convert_currency_timer_rate_per_second
0.07333255542294032
# TYPE application_convert_currency_timer_one_min_rate_per_
second gauge
application_convert_currency_timer_one_min_rate_per_second
3.0039512838912655E-4
# TYPE application_convert_currency_timer_five_min_rate_per_
second gauge
application_convert_currency_timer_five_min_rate_per_second
0.02560887973769466
# TYPE application_convert_currency_timer_fifteen_min_rate_per_
second gauge
application_convert_currency_timer_fifteen_min_rate_per_second
0.02345612678178861
# TYPE application_convert_currency_timer_mean_seconds gauge
403
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
application_convert_currency_timer_mean_seconds
0.9913156544019269
# TYPE application_convert_currency_timer_max_seconds gauge
application_convert_currency_timer_max_seconds 4.622333082
# TYPE application_convert_currency_timer_min_seconds gauge
application_convert_currency_timer_min_seconds 0.375723652
# TYPE application_convert_currency_timer_stddev_seconds gauge
application_convert_currency_timer_stddev_seconds
0.8967743131501213
# TYPE application_convert_currency_timer_seconds summary
application_convert_currency_timer_seconds_count 35
application_convert_currency_timer_seconds_sum 34.812993443
application_convert_currency_timer_seconds{quantile="0.5"}
0.687353305
application_convert_currency_timer_seconds{quantile="0.75"}
1.037883712
application_convert_currency_timer_seconds{quantile="0.95"}
4.2614521750000005
application_convert_currency_timer_seconds{quantile="0.98"}
4.622333082
application_convert_currency_timer_seconds{quantile="0.99"}
4.622333082
application_convert_currency_timer_seconds{quantile="0.999"}
4.622333082
As you can see from the returned data, the @Timed metric returns a
lot more detailed information about the method invocation relative to the
@SimplyTimed metric. These two complement each other for when you
need lightweight and heavyweight timing metrics.
404
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Injecting Metrics
Apart from the use of annotations, you can also directly inject metrics
of type meter, timer, counter, and histogram in your applications.
You can inject metrics into fields, methods, and parameters using the
@Metric annotation in combination with @Inject. The @Metric annotation
supports all the metadata that the respective metrics support, such as
name, description, and absolute values.
Using the Histogram Metric
One metric that does not have an annotation equivalent is the histogram.
This is a complex metric that measures the min, max, mean, standard
deviation, and quartiles like the median or 95th percentile. To use this
metric, we can inject it as shown in Listing 9-13 in the RateService bean.
Listing 9-13. The use of the histogram metric through injection
@ApplicationScoped
public class RateService {
@Inject
@Metric(name = "count_conversions_histogram",
absolute = true,
description = "A histogram for the count of
conversions",
tags = { "count=histogram", "metric=histogram" })
Histogram histogram;
@Gauge(name = "convert_currency_gauge_count",
unit = MetricUnits.NONE, absolute = true)
public int countConversions() {
int conversionCount = ThreadLocalRandom.current().
nextInt(250, 500 + 1);
405
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
histogram.update(conversionCount);
return conversionCount;
}
}
Listing 9-13 shows the use of @Inject in combination with @Metric to
inject the histogram metric.
This metric takes a long or int for its update methods to update
the internal data. The @Metric annotation is used to pass in the name,
description, and absolute metadata values to the metric. Within the
countConversions method, the returned count is passed to the update
method for the computation. With the name set to absolute, the metric
can be queried from the path /metrics/application/count_conversions_
histogram. Listing 9-14 shows the sample returned data for the invocation.
Listing 9-14. The data returned for the histogram metric
# TYPE application_count_conversions_histogram_mean gauge
application_count_conversions_histogram_mean{count="histogram",
metric="histogram"} 417.7099758660769
# TYPE application_count_conversions_histogram_max gauge
application_count_conversions_histogram_max{count="histogram",
metric="histogram"} 500.0
# TYPE application_count_conversions_histogram_min gauge
application_count_conversions_histogram_min{count="histogram",
metric="histogram"} 253.0
# TYPE application_count_conversions_histogram_stddev gauge
application_count_conversions_histogram_stddev{count="histogram
",metric="histogram"} 82.50134125075685
# TYPE application_count_conversions_histogram summary
# HELP application_count_conversions_histogram A histogram for
the count of conversions
406
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
application_count_conversions_histogram_count{count="histogram",
metric="histogram"} 21
application_count_conversions_histogram_sum{count="histogram",
metric="histogram"} 8541
application_count_conversions_histogram{count="histogram",
metric="histogram",quantile="0.5"} 462.0
application_count_conversions_histogram{count="histogram",
metric="histogram",quantile="0.75"} 490.0
application_count_conversions_histogram{count="histogram",
metric="histogram",quantile="0.95"} 500.0
application_count_conversions_histogram{count="histogram",
metric="histogram",quantile="0.98"} 500.0
application_count_conversions_histogram{count="histogram",
metric="histogram",quantile="0.99"} 500.0
application_count_conversions_histogram{count="histogram",
metric="histogram",quantile="0.999"} 500.0
As shown in the above listing, the histogram metric returns statistical
data for a given object that you want to track. Unlike the other metrics,
you will need to inject the histogram as done in Listing 9-13 to have it
automatically registered in the registry or manually register it.
Manual Registration of Metrics
The histogram metric can equally be manually instantiated and registered
in the metrics registry by first injecting the MetricRegistry through CDI,
then building the metadata through the Metadata interface, and finally
calling the histogram method on the injected MetricRegistry instance to
register and get a Histogram instance. Listing 9-15 shows these steps in
code in the RateService bean.
407
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Listing 9-15. Manual instantiation of the histogram metric
@ApplicationScoped
public class RateService {
@Inject
MetricRegistry registry;
@Gauge(name = "convert_currency_gauge_count", unit =
MetricUnits.NONE, absolute = true)
public int countConversions() {
int conversionCount = ThreadLocalRandom.current().
nextInt(250, 500 + 1);
Metadata metadata = Metadata.builder()
.withName("count_conversions_histogram")
.withDescription("A histogram for the count of
conversions")
.withDisplayName("A histogram")
.build();
Histogram manualHistogram = registry.
histogram(metadata);
manualHistogram.update(conversionCount);
return conversionCount;
}
}
Listing 9-15 shows the histogram metric manually instantiated in the
RateService bean.
The MetricRegistry is injected with @Inject. Then the builder pattern is
used to build a Metadata object. This Metadata is exactly the same details
you would have passed to the @Metric annotation. Then the histogram
method is called on the MetricRegistry object, passing in the just-built
408
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Metadata object. This invocation returns a Histogram instance that can
then be used to create histograms. The Histogram functionality will be the
same no matter which construct is used to instantiate it.
Metrics Metadata
Metadata is all the information that helps describe a given metric. You
can retrieve metadata about an individual metric or that of a given scope
or the entire set of metrics by making an HTTP OPTIONS call to /metrics
or any of its variations. The Accept header of the OPTIONS call should be
application/json because the metadata is returned as JSON. For instance,
we can get all the metadata for all the metrics covered in this chapter by
making an HTTP OPTIONS call to /metrics/application. The sample call
shown in Listing 9-16 returns the metadata shown in Listing 9-17.
Listing 9-16. Sample metadata call
OPTIONS http://localhost:3001/metrics/application/base
Accept: application/json
Listing 9-17. Metadata for the application metrics scope
{
"convert_currency_simple_timer": {
"unit": "nanoseconds",
"displayName": "convert_currency_simple_timer",
"name": "convert_currency_simple_timer",
"description": "",
"type": "simple timer",
"tags": []
},
"convert_currency_counted": {
"unit": "none",
409
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
"displayName": "Convert currency method",
"name": "convert_currency_counted",
"description": "Method to convert one currency to
the other",
"type": "counter",
"tags": [
[
"info=conversions",
"type=meta"
]
]
},
"convert_currency_timer": {
"unit": "nanoseconds",
"displayName": "convert_currency_timer",
"name": "convert_currency_timer",
"description": "",
"type": "timer",
"tags": []
},
"convert_currency_meter": {
"unit": "per_second",
"displayName": "convert_currency_meter",
"name": "convert_currency_meter",
"description": "",
"type": "meter",
"tags": []
},
"count_conversions_histogram": {
"unit": "none",
"displayName": "count_conversions_histogram",
"name": "count_conversions_histogram",
410
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
"description": "A histogram for the count of
conversions",
"type": "histogram",
"tags": [
[
"count=histogram",
"metric=histogram"
]
]
},
"convert_currency_concurrent_gauge": {
"unit": "none",
"displayName": "convert_currency_concurrent_gauge",
"name": "convert_currency_concurrent_gauge",
"description": "Method to convert one currency to
the other",
"type": "concurrent gauge",
"tags": [
[
"convert=custom"
]
]
}
}
Other MicroProfile Spec Metrics
As a suite of tightly integrated specifications, using the Fault Tolerance
API in an application automatically exposes related metrics under the /
metrics/base scope. As a developer, all you have to do is use the Fault
411
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Tolerance API and you will have these metrics exposed for you. As
an example, a call to the /metrics/base endpoint returns all the Fault
Tolerance metrics, a sample of which is shown in Listing 9-18.
Listing 9-18. A sample of the Fault Tolerance metrics
# TYPE base_ft_bulkhead_runningDuration_mean_seconds gauge
base_ft_bulkhead_runningDuration_mean_seconds{method="com.
example.jwallet.rate.rate.control.RateService.convertCurrency"}
0.6664609707678424
# TYPE base_ft_bulkhead_runningDuration_max_seconds gauge
base_ft_bulkhead_runningDuration_max_seconds{method="com.
example.jwallet.rate.rate.control.RateService.convertCurrency"}
7.678077344
# TYPE base_ft_bulkhead_runningDuration_min_seconds gauge
base_ft_bulkhead_runningDuration_min_seconds{method="com.
example.jwallet.rate.rate.control.RateService.convertCurrency"}
0.28274852300000003
# TYPE base_ft_bulkhead_runningDuration_stddev_seconds gauge
base_ft_bulkhead_runningDuration_stddev_seconds{method="com.
example.jwallet.rate.rate.control.RateService.convertCurrency"}
1.504029612722161
# TYPE base_ft_bulkhead_runningDuration_seconds summary
base_ft_bulkhead_runningDuration_seconds_count{method="com.
example.jwallet.rate.rate.control.RateService.
convertCurrency"} 20
base_ft_bulkhead_runningDuration_seconds_sum{method="com.
example.jwallet.rate.rate.control.RateService.convertCurrency"}
14199386249
base_ft_bulkhead_runningDuration_seconds{method="com.example.
jwallet.rate.rate.control.RateService.convertCurrency",
quantile="0.5"} 0.308184634
412
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
base_ft_bulkhead_runningDuration_seconds{method="com.example.
jwallet.rate.rate.control.RateService.convertCurrency",
quantile="0.75"} 0.39874514600000005
base_ft_bulkhead_runningDuration_seconds{method="com.example.
jwallet.rate.rate.control.RateService.convertCurrency",
quantile="0.95"} 0.48290750400000004
base_ft_bulkhead_runningDuration_seconds{method="com.example.
jwallet.rate.rate.control.RateService.convertCurrency",
quantile="0.98"} 7.678077344
base_ft_bulkhead_runningDuration_seconds{method="com.example.
jwallet.rate.rate.control.RateService.convertCurrency",
quantile="0.99"} 7.678077344
base_ft_bulkhead_runningDuration_seconds{method="com.example.
jwallet.rate.rate.control.RateService.convertCurrency",
quantile="0.999"} 7.678077344
CDI Stereotypes and Metrics
As discussed in Chapter 4, CDI stereotypes are a way to group common
infrastructure annotations together under one annotation. Using the
resulting stereotype on a bean is as if all the annotations that make up the
stereotype are used individually on the bean.
Consequently, when you annotate a stereotype with any of the Metrics
annotations, the resulting bean will be treated by the Metrics runtime as
if the metrics annotation was applied directly to the bean. The resulting
names of the metrics are computed relative to the name and package of
the bean itself, not of the stereotype.
As an example, the @Action stereotype, developed in Chapter 4
(CDI), is reproduced in Listing 9-19, annotated with @Counted and
@SimplyTimed. These annotations will cause all beans that are annotated
@Action to have their constructor and method invocations counted and
simply timed, respectively.
413
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Listing 9-19. @Action stereotype with @Counted and
@SimplyTimed
@Stereotype
@RequestScoped
@Counted
@SimplyTimed
@Transactional
@Logged
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Action {
}
Distributed Tracing with Telemetry
While metrics give insights into an application's performance and
behavior, modern distributed systems need more. As requests flow through
multiple services, there is a need to understand the complete journey of
each request—where it went, how long each step took, and what happened
along the way. Distributed tracing is how this is achieved.
MicroProfile Telemetry builds on Metrics, adding distributed tracing
capabilities through OpenTelemetry integration. Combining metrics
and tracing, you get a complete picture of an application's behavior and
performance. Let's explore how to implement distributed tracing in your
Jakarta EE applications using MicroProfile Telemetry.
414
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Telemetry Data Collection Options
The landscape of telemetry data collection has evolved significantly,
with two major approaches emerging as primary options for Jakarta EE
applications: OpenTelemetry and MicroProfile Telemetry. Both options
offer full-featured APIs for collecting telemetry data in your applications.
Their differences lie in the scope of the underlying projects.
OpenTelemetry Overview
OpenTelemetry has emerged as the de facto standard for telemetry
data collection in cloud-native applications. It represents a significant
advancement in observability by providing the following.
Unified Standard for Telemetry Data
•
A single, coherent set of APIs, libraries, agents, and
instrumentation
•
Consistent data collection across all three observability
pillars (logs, metrics, and traces)
•
Standardized data formats and semantic conventions
•
Support for multiple programming languages and
platforms
•
Built-in context propagation across service boundaries
Vendor-Neutral Approach
•
Open governance under the Cloud Native Computing
Foundation (CNCF)
•
Wide industry adoption and support
415
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
•
Pluggable architecture supporting multiple backends
•
No vendor lock-in for telemetry data
•
Compatible with popular observability platforms
(Jaeger, Zipkin, Prometheus, etc.)
MicroProfile Telemetry Specification
The MicroProfile Telemetry specification provides a standards-based
approach specifically designed for Jakarta EE applications, offering a
bridge between traditional enterprise Java applications and modern
observability practices.
Standards-Based Approach for Jakarta EE
•
Native integration with the Jakarta EE
programming model
•
Consistent with Jakarta EE principles and patterns
•
Declarative configuration through annotations
•
CDI-based integration
•
Compatible with existing Jakarta EE applications
Integration withOpenTelemetry
416
•
Built on top of OpenTelemetry APIs
•
Uses OpenTelemetry's core functionality
•
Provides Jakarta EE-specific conventions
•
Automatic context propagation in Jakarta EE
environments
•
Seamless integration with OpenTelemetry collectors
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Focus on Tracing (Current Spec Scope)
•
Emphasis on distributed tracing as initial
implementation
•
Support for common Jakarta EE use cases
•
Automatic instrumentation of Jakarta EE components
•
Trace context propagation across Jakarta EE
boundaries
•
Extension points for custom instrumentation
The key difference between these approaches lies in their scope and
target audience:
•
OpenTelemetry provides a comprehensive, language­
agnostic solution suitable for any application
architecture.
•
MicroProfile Telemetry focuses specifically on Jakarta
EE applications, providing integrated observability
features that align with Jakarta EE development
practices.
Both options provide solutions for implementing observability in
Jakarta EE applications, and they can be used together in many cases.
OpenTelemetry offers broader ecosystem compatibility, while MicroProfile
Telemetry provides a more integrated experience for Jakarta EE
developers. The rest of this chapter covers using MicroProfile Telemetry in
Jakarta EE applications.
417
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
MicroProfile Telemetry Deep Dive
MicroProfile Telemetry provides three distinct approaches to
instrumenting Jakarta EE applications for observability: automatic,
manual, and agent-based instrumentation. Each approach serves different
needs and can be used independently or in combination to achieve
comprehensive system observability.
Basic Setup and Configuration
MicroProfile Telemetry is disabled by default in Jakarta EE applications to
prevent any unexpected impact on systems. To begin collecting telemetry
data, you'll need to explicitly enable it through configuration. The most
fundamental configuration property is otel.sdk.disabled, which must be
set to false in any config source (mostly the microprofile-config.properties
file) to activate telemetry collection:
otel.sdk.disabled=false
You'll also want to configure where your telemetry data is sent. By
default, MicroProfile Telemetry uses the OTLP to export traces to http://
localhost:4317. For development purposes, you can quickly set up a local
OpenTelemetry backend through docker (or podman) to receive these
traces through the docker-otel-lgtm project as shown in Listing 9-20.
Listing 9-20. docker command to pull an OpenTelemetry backend
docker run \
- -name lgtm \
- p 3000:3000 \
- p 4317:4317 \
- p 4318:4318 \
- -rm \
- ti \
418
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
- v $PWD/container/grafana:/data/grafana \
- v $PWD/container/prometheus:/data/prometheus \
- v $PWD/container/loki:/loki \
- e GF_PATHS_DATA=/data/grafana \
docker.io/grafana/otel-lgtm:latest
Automatic Instrumentation
MicroProfile Telemetry automatically instruments your Jakarta REST
endpoints and client calls once enabled. This means your application
immediately begins collecting distributed traces without any code
changes. For example, when a REST endpoint processes a request, you'll
see spans that include important metadata like HTTP method, status
codes, and request paths, with trace context properly propagated between
services. Of course not all applications are built purely on Jakarta REST.
Manual Instrumentation
When you need more fine-grained control over telemetry data collection
as well as instrumenting custom components in an application, manual
instrumentation offers two primary approaches. The first is the @WithSpan
annotation, which can be added to any CDI-aware bean methods. This
declarative approach allows for the naming of spans and to configure their
kind and capture method parameters as span attributes. For example,
Listing 9-21 shows the RateService convertCurrency annotated.
Listing 9-21. Instrumented method
@WithSpan("convert-currency")
public ConvertCurrencyResponse convertCurrency(@SpanAttribute
("convertCurrencyRequest") final ConvertCurrencyRequest
convertCurrencyRequest) {
return convert(convertCurrencyRequest);
}
419
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
The @WithSpan annotation marks this method as instrumented.
Invocations of this method will produce observable spans that can be
monitored. The annotation takes a name that will be assigned as the name
of the span. @SpanAttribute marks the method parameter as instrumented
with the custom name passed to the annotation. Using annotations is the
more straightforward way to instrument Jakarta CDI components.
However, for cases requiring even more control, you can directly
interact with the OpenTelemetry Tracer API. This approach gives complete
control over span lifecycle and attributes. The Tracer can be injected via
CDI as shown in Listing 9-22.
Listing 9-22. The use of the Tracer
@ApplicationScoped
public class RateService {
@Inject
Tracer tracer;
public ConvertCurrencyResponse convertCurrency( final
ConvertCurrencyRequest convertCurrencyRequest) {
// Create a new span for the currency conversion
operation
Span span = tracer.spanBuilder("convert-currency")
.setSpanKind(SpanKind.INTERNAL)
.setAttribute(AttributeKey.
stringKey("sourceCurrency"),
convertCurrencyRequest.getSourceCurrency())
.setAttribute(AttributeKey.
stringKey("targetCurrency"),
convertCurrencyRequest.getTargetCurrency())
420
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
.setAttribute(AttributeKey.stringKey("amount"),
convertCurrencyRequest.getAmount().
toPlainString())
.startSpan();
try (Scope scope = span.makeCurrent()) {
// Perform the currency conversion
return convert(convertCurrencyRequest);
} catch (Exception e) {
// Record the exception in the span
span.recordException(e);
span.setStatus(StatusCode.ERROR, "Currency
conversion failed");
throw e; }
finally {
// End the span
span.end();
}
}
}
The RateService injects a Tracer to manually create a span for the
convertCurrency method, providing detailed insights into the process.
This span includes attributes like source currency, target currency, and
amount and records any exceptions during conversion. This manual
instrumentation, along with the error handling, shows how you can
manually instrument Jakarta CDI components in an end-to-end way.
A sample trace from the above will be something like the following in
Listing 9-23.
421
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Listing 9-23. Sample trace
• Span Name: convert-currency
• Span Kind: INTERNAL
• Attributes:
• sourceCurrency: USD
• targetCurrency: EUR
• amount: 100.00
• Status: OK (if successful) or ERROR (if an exception occurs)
• Events: Exception details (if an error occurs)
You can also access and manipulate the current span, either through
CDI injection or the Span.current() API. This is particularly useful
when you need to add attributes to spans created by the automatic
instrumentation.
Agent-Based Instrumentation
When you need to add observability without modifying application code,
MicroProfile Telemetry implementations may support agent­
based instrumentation. This approach uses a Java agent that attaches
to the running JVM and automatically instruments a wide range of
common libraries and frameworks. The agent can be configured through
properties and can work alongside other instrumentation approaches.
While optional, when implemented according to the OpenTelemetry Java
Instrumentation project guidelines, it provides a powerful way to gather
telemetry data with minimal setup overhead.
This flexibility in instrumentation approaches gives you the flexibility
to choose the most appropriate method for your specific needs, whether
you’re just starting with observability or need detailed control over your
telemetry data collection. The coverage of agent instrumentation is beyond
the scope of this book.
422
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Advanced Configuration
As your observability needs to grow, MicroProfile Telemetry offers various
configuration options to fine-tune your telemetry collection. Sampling is
a core aspect of production deployments, letting you control how much
telemetry data you collect. The default sampler (parentbased_always_on)
captures all traces, but you can adjust this using the otel.traces.sampler
property as shown in Listing 9-24.
Listing 9-24. Trace sampler property
# Sample 10% of traces
otel.traces.sampler=traceidratio
otel.traces.sampler.arg=0.1
The above configuration tells the runtime to sample 10% of traces.
Consult the spec for the full list of supported samplers.
Resource attributes help identify your service in the observability
backend. You can set these through configuration as shown in Listing 9-25.
Listing 9-25. Resource attributes
otel.service.name=rate-service
otel.resource.attributes=deployment.environment=production,
team=commerce
This configuration assigns the name rate-service to the instrumented
service, ensuring that any telemetry data (like traces or metrics) is
associated with that service. It also provides additional context via
resource attributes, specifying that the service is running in the production
environment (deployment.environment=production) and is managed
by the commerce team (team=commerce). These attributes help in
organizing, filtering, and analyzing telemetry data across different services
or environments.
423
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
For performance optimization, you can configure how spans are
batched and exported as shown in Listing 9-26.
Listing 9-26. Batching of spans
# Adjust batch export settings
otel.bsp.schedule.delay=5000
otel.bsp.max.queue.size=2048
otel.bsp.max.export.batch.size=512
otel.bsp.export.timeout=30000
This configuration adjusts the batch span processor (bsp)
settings, which control how telemetry data (spans, metrics) is buffered
and exported. The otel.bsp.schedule.delay=5000 sets the delay (in
milliseconds) between export attempts to 5 seconds, ensuring regular
batching of data. otel.bsp.max.queue.size=2048 defines the maximum
buffer size for spans, allowing up to 2,048 spans to be queued before they
are exported. otel.bsp.max.export.batch.size=512 limits the number of
spans sent in each batch to 512, promoting efficient data exports. Lastly,
otel.bsp.export.timeout=30000 sets the export timeout to 30 seconds,
meaning that if the export process fails to complete within this time frame,
it will be aborted, ensuring export operations remain timely.
Export configuration is important for production environments,
especially when sending data to secure endpoints as shown in Listing 9-27.
Listing 9-27. Export configuration
otel.exporter.otlp.endpoint=https://telemetry.production.
com:4317
otel.exporter.otlp.protocol=grpc
otel.exporter.otlp.headers=api-key=secret,tenant=team1
424
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
The otel.exporter.otlp.endpoint=https://telemetry.production.
com:4317 specifies the target endpoint (URL and port) where the telemetry
data will be sent, in this case, a server at telemetry.production.com on
port 4317. The otel.exporter.otlp.protocol=grpc sets the communication
protocol to gRPC, a high-performance RPC (Remote Procedure Call)
framework commonly used for efficient and reliable data exchange. The
otel.exporter.otlp.headers=api-key=secret,tenant=team1 sets custom
headers, including an API key (api-key=secret) used for authentication
and a tenant identifier (tenant=team1) to segregate data by team or
project. These configurations ensure secure, structured, and authenticated
telemetry data exports from applications.
Through these configuration options, MicroProfile Telemetry provides
a flexible foundation for implementing observability in your Jakarta EE
applications. Whether you're just starting with basic tracing or need
sophisticated telemetry collection in production, the specification offers
the tools needed to understand your distributed systems better.
Summary
Modern cloud-native applications require reliable observability for
effective monitoring and troubleshooting. This chapter discussed how
MicroProfile facilitates observability in Jakarta EE applications, primarily
focusing on tracing through MicroProfile Telemetry and the widely used
MicroProfile Metrics. While MicroProfile is moving toward OpenTelemetry
integration, existing applications rely heavily on MicroProfile Metrics
as it offers multiple annotations (@Counted, @Timed, etc.) and
programmatic APIs.
425
CHAPTER 9
METRICS FOR JAKARTA EE APPLICATIONS: MONITORING AND OBSERVABILITY
Key Takeaways
1. Cloud-native observability relies on metrics, logs, and
traces. (This is accurate and needs no change.)
2. MicroProfile Metrics (still widely used) provides
annotations and APIs for application metrics
collection.
3. MicroProfile Telemetry, aligning with the
industry-standard OpenTelemetry, provides three
instrumentation approaches: automatic, manual, and
agent-based.
4. Telemetry data export, sampling, and batching are
configurable.
5. Performance is a critical consideration when
implementing observability.
Looking Ahead
While observability helps you understand application behavior, it's only
one part of maintaining reliable cloud-native applications. In the next
chapter, we'll explore another aspect—implementing health checks.
You'll learn how MicroProfile Health helps cloud platforms determine
application health and make informed decisions about scaling and
failover. This complements the observability capabilities we've discussed,
providing a complete picture of application reliability and performance in
cloud environments.
426
CHAPTER 10
Taking a Pulse
with Health Check
In modern cloud environments, applications are deployed as containers
and managed by orchestration platforms like Kubernetes. These platforms
need to continuously monitor application health to maintain service
availability and reliability. The Eclipse MicroProfile Health specification
provides a standardized way for Jakarta EE applications to expose their
health status to these orchestration systems.
By the end of this chapter, you will be able to
•
Understand the importance of health checks in cloud­
native environments.
•
Implement readiness, liveness, and startup probes in
Jakarta EE applications.
•
Configure health check responses for Kubernetes
integration.
•
Use CDI to create modular and maintainable health
check procedures.
•
Apply best practices for cloud-native health
monitoring.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_10
427
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Health Checks in Cloud Environments
Applications packaged as container images and deployed to the cloud are
mostly managed by automated scheduling and deployment systems like
Kubernetes. These systems will
•
Kill unhealthy containers and spawn new ones.
•
Route requests only to healthy instances.
•
Monitor application startup state.
•
Manage rolling updates based on health status.
For these automated systems to work effectively, applications must be
able to answer three critical questions:
•
Have you started? (Startup probe)
•
Are you alive? (Liveness probe)
•
Are you ready to accept requests? (Readiness probe)
The MicroProfile Health specification provides the API constructs
to implement these probes in a standardized way that integrates with
Kubernetes and other cloud platforms.
Health API Structure
The Health API revolves around two types: the HealthCheck interface and
the HealthCheckResponse class.
428
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Accessing Health Check Procedures
The /health context path provides a starting point for querying health check
procedures. An HTTP GET request to this path returns all health checks
configured in the application, formatted in JSON. The specific procedures
invoked and the resulting status codes depend on the type of health check.
Here are the health check statuses:
•
Liveness probes (/health/live) are used to
determine if the application is running. If the
application is running, the probe will return an HTTP
200 status code. If the probe determines the application
is not running, it will return an HTTP 503 status code.
•
Readiness probes (/health/ready) indicate if the
application is ready to handle requests. If ready, the
probe will return an HTTP 200 status code. If not ready,
it will return an HTTP 503 status code.
•
Startup probes (/health/started) verify if the
application has completed its startup process. If the
application has started, the probe will return an HTTP
200 status code. If not yet started, it will return an HTTP
503 status code.
In cases where multiple probes are invoked, the response will include
an overall status that reflects the aggregate result of all the probes.
The HealthCheck Interface
The HealthCheck interface is a functional interface with the single method
call() that returns a HealthCheckResponse. This interface is the entry point
to the Health API. A class that wants to respond to health check probes will
extend the HealthCheck interface, implementing the call() method in an
application-specific way, eventually returning a HealthCheckResponse.
429
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
The HealthCheckResponse
The HealthCheckResponse is a class that encapsulates the response that
a health check probe returns. It has three simple fields, namely, name,
status, and data. The first two fields are of type String, and the last one is an
Optional< Map<String, Object>> type. The data field can be used to return
free-form additional data that a health check implementation would like
to return to a calling client. It has a convenient builder method for building
the response. The name field is mandatory and must be provided for every
instance of the HealthCheckResponse.
After a health check component performs some kind of application­
specific check, it can build the HealthCheckResponse and return an
instance that tells the caller if the particular health check is up or down
and also pass some optional data.
Health andCDI
The Health API is built on the Jakarta CDI (covered in Chapter 4).
This makes all health check components CDI beans. As health check
components are required to implement the HealthCheck interface, all
health check components are bean types of at least HealthCheck.
However, as mentioned in the opening section, the Health API allows
an application to respond to two simple questions. As there can be
more than one bean type of HealthCheck, the API comes with three CDI
qualifiers to distinguish HealthCheck beans from each other.
430
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Health Check Qualifiers
The three health check qualifiers for identifying which beans respond to
which health probe are
•
@Readiness
•
@Liveness
•
@Startup
@Readiness
The @Readiness qualifier, used on a HealthCheck bean, creates a
readiness health check procedure. This health check allows the caller
to know if the application is ready to accept requests. Readiness health
checks can be queried from the resource /health/ready. To create a
readiness health check, annotate a bean of type HealthCheck with @
Readiness as shown in Listing 10-1.
Listing 10-1. A @Readiness health check
@ApplicationScoped
@Readiness
public class HelloReadiness implements HealthCheck {
CountDownLatch countDownLatch = new CountDownLatch(2);
@Override
public HealthCheckResponse call() {
countDownLatch.countDown();
return countDownLatch.getCount() == 0
? HealthCheckResponse.up("rate-readiness")
: HealthCheckResponse.down("rate-readiness");
}
}
431
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Listing 10-1 shows the HelloReadiness bean implementing the
HealthCheck interface. This bean is an @ApplicationScoped bean
that bears the @Readiness qualifier. Since a health check probe covers
the entire application, a single application-scoped instance of the
HealthCheck implementation suffices. The @Readiness annotation marks
this bean as a readiness health check and will be called by the Health
runtime if the /health root health resource or the specific /health/ready
endpoint is queried.
For this example, the call method implementation uses a simple
CountDownLatch to simulate some form of countdown. As the bean is a
CDI bean, you can inject any dependency into it and carry out any custom,
application-specific task to determine the readiness of the application. The
only requirement is to return the HealthCheckResponse object.
A sample readiness probe to the path /health/ready returns the health
data as shown in Listing 10-2.
Listing 10-2. The JSON representation of the HealthCheckResponse
object
{
"checks": [
{
"data": {},
"name": "rate-readiness",
"status": "UP"
}
],
"status": "UP"
}
With the @Readiness probe, the health check procedure reports that it
is UP and ready. This means the rate module of jwallet is up and ready to
accept requests.
432
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
@Liveness
The @Liveness qualifier on a HealthCheck bean creates a health check
to determine if the application is running. In a cloud environment, if this
call fails with a DOWN status, for instance, Kubernetes could then use
this information to discard that container instance and replace it with a
healthier one. To create a @Liveness health check, annotate a HealthCheck
bean with @Liveness as shown in Listing 10-3.
Listing 10-3. A @Liveness health check implementation
@ApplicationScoped
@Liveness
public class HelloLiveness implements HealthCheck {
LocalDateTime init = LocalDateTime.now(ZoneOffset.UTC);
@Override
public HealthCheckResponse call() {
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
Duration upDuration = Duration.between(init, now);
return HealthCheckResponse.builder()
.up()
.name("rate_service_live")
.withData("up_since", upDuration.toMinutes())
.build();
}
}
Listing 10-3 shows a @Liveness health check implementation in the
HelloLiveness bean. This implementation simply returns the UP status and
a free-form data showing the number of minutes that the service has been
433
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
live. The free-form data can be anything the health check implementation
would like to return to the client. A sample call to this @Liveness
implementation returns the data shown in Listing 10-4.
Listing 10-4. A liveness health check response
{
"checks": [
{
"data": {
"up_since": 2
},
"name": "rate_service_live",
"status": "UP"
}
],
"status": "UP"
}
Listing 10-4 shows the HealthCheckResponse JSON representation
from the @Liveness check. With this information and the HTTP status
code 200, Kubernetes will know that the application instance is up and
running.
@Startup
@Startup is a health check that allows applications to create custom startup
health checks that can be used for some form of application­
specific verification before the liveness probe takes over. This health
check procedure, in a cloud environment, will be mapped to the startup
Kubernetes probes. @Startup is suitable for situations where an application
needs some initialization during startup. In such cases, it is good to ensure
initialization has completed before the application is put into service. Listing
10-5 shows a startup health check implementation in the HelloStartup bean.
434
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Listing 10-5. @Startup health check implementation
@ApplicationScoped
@Startup
public class HelloStartup implements HealthCheck {
CountDownLatch countDownLatch = new CountDownLatch(5);
LocalDateTime upSince = LocalDateTime.now(ZoneOffset.UTC);
@Override
public HealthCheckResponse call() {
countDownLatch.countDown();
return countDownLatch.getCount() == 0
? HealthCheckResponse.named("rate-startup")
.withData("up_since", upSince.toString())
.up()
.build()
: HealthCheckResponse.down("rate-startup");
}
}
Listing 10-5 shows a @Startup health check implementation that
simply counts down to 5 and returns UP after. A sample call to the /health/
started endpoint returns the data shown in Listing 10-6.
Listing 10-6. The returned data for the startup health probe
{
"checks": [
{
"data": {
"up_since": "2022-08-14T17:26:33.363745328"
},
435
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
"name": "rate-startup",
"status": "UP"
}
],
"status": "UP"
}
Combining Health Checks
The health checks seen so far have all been implemented by separate
beans. However, they can all be combined and implemented by a single
bean. In this case, the single HealthCheck bean will be annotated with all
the required health check qualifiers. Such a HealthCheck implementation
will be used to resolve all health checks for which it is annotated. Listing
10-7 shows a single health check implementation for @Liveness, @
Readiness, and @Startup.
Listing 10-7. A single health check implementation
@ApplicationScoped
@Liveness
@Readiness
@Startup
public class HelloHealth implements HealthCheck {
LocalDateTime upSince = LocalDateTime.now(ZoneOffset.UTC);
@Inject
ApiLayer apiLayer;
@Override
public HealthCheckResponse call() {
JsonObject currencySymbols = apiLayer.
getCurrencySymbols();
436
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
boolean success = currencySymbols.
getBoolean("success", false);
return success
? HealthCheckResponse.named("rate-service")
.withData("up_since", upSince.toString())
.withData("rate_api_provider", "up")
.up()
.build()
: HealthCheckResponse.down("rate-service");
}
}
Listing 10-7 shows a single health check implementation for liveness,
readiness, and startup. For this implementation, an external call is made
to the rate service provider for the application. The only time we want to
return an UP health check response is when the external service provider
is available. Since we delegate rate conversion to that service, there is
not much point in putting our application into service when the external
provider we depend on is down. A call to /health, /health/live, /health/
ready, and health/started will all be routed to this single implementation.
A sample call to /health returns the data shown in Listing 10-8.
Listing 10-8. Data for the single health check implementation
{
"checks": [
{
"data": {
"up_since": "2022-08-14T17:59:26.592292658",
"rate_api_provider": "up"
},
437
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
"name": "rate-service",
"status": "UP"
}
],
"status": "UP"
}
Producing Health Checks
As discussed in Chapter 4, producers are a construct for creating
CDI beans. As HealthChecks are CDI beans, they can be produced
using the CDI producer method construct. Listing 10-9 shows the
WalletHealthCheckProducer bean with three producer methods, each with
a qualifier for the three health checks of liveness, readiness, and startup.
Listing 10-9. HealthCheck creation with producer methods
@ApplicationScoped
public class WalletHealthCheckProducer {
CountDownLatch readinessCountdown = new CountDownLatch(2);
CountDownLatch startupCountdown = new CountDownLatch(5);
@Inject
@ConfigProperty(name = "free.memory.limit")
Integer freeMemoryLimit;
@Produces
@Liveness
HealthCheck livenessCheck() {
String healthCheckName = "wallet-livenesshealth-check";
return () -> {
438
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
long totalMemory = Runtime.getRuntime().
totalMemory();
long freeMemory = Runtime.getRuntime().
freeMemory();
boolean adequateMemory = (((float) freeMemory /
totalMemory) * 100) > freeMemoryLimit;
return adequateMemory ?
HealthCheckResponse
.builder()
.name(healthCheckName)
.up()
.build() :
HealthCheckResponse
.named(healthCheckName)
.down()
.build();
};
}
@Produces
@Readiness
HealthCheck readinessCheck() {
return () -> {
readinessCountdown.countDown();
return readinessCountdown.getCount() == 0 ?
HealthCheckResponse
.up("wallet-liveness") :
HealthCheckResponse
.down("wallet-liveness");
};
}
439
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
@Produces
@Startup
HealthCheck startupCheck() {
return () -> {
startupCountdown.countDown();
return startupCountdown.getCount() == 0 ?
HealthCheckResponse
.up("wallet-started") :
HealthCheckResponse
.down("wallet-startup-failed");
};
}
}
Listing 10-9 shows the @ApplicationScoped
WalletHealthCheckProducer with three methods. Each method is
annotated with the CDI @Produces and a health check qualifier. The
first method is a @Liveness check that returns a status if the free memory
relative to the total memory available in the JVM is more than the
passed configured value. In the sample code, the MicroProfile config
value passed in the microprofile-config.properties is 40. So if the free
memory in the JVM is more than 40%, then the liveness check returns
a HealthCheckResponse object with status up. Otherwise, it returns a
down status.
The second method is a @Readiness check that simply counts down to
2 and returns an up status. The third method is @Startup check that also
counts down to 5 and then returns an up status. Listing 10-10 shows the
returned data for a sample call to the /health endpoint for this module.
440
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Listing 10-10. The returned health check data for the produced
health checks
{
"checks": [
{
"data": {},
"name": "wallet-readiness",
"status": "UP"
},
{
"data": {},
"name": "wallet-liveness-health-check",
"status": "DOWN"
},
{
"data": {},
"name": "wallet-started",
"status": "UP"
}
],
"status": "DOWN"
}
Listing 10-10 shows the response for the /health probe for the wallet
module of jwallet. In the sample call, the JVM reports the available free
memory to be less than 40% of total memory, resulting in the @Liveness
check returning a down status. It is important to note that the response
isn’t necessarily returned in any given order. Even though in the code the
liveness call is declared before the readiness check, the call to the base /
health endpoint returns the result of the readiness check first before the
liveness check.
441
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Best Practices for Cloud Health Checks
When implementing health checks for cloud-native applications, following
established best practices can help ensure an application integrates well
with container orchestration platforms and provides meaningful health
information.
Separate Concerns with Different Health
Check Types
Even though a single bean can implement all the health check types, it’s
better to always implement separate checks for different aspects of an
application's health:
•
Use liveness probes only for detecting if an application
is running and responding. Keep these checks
lightweight and focused on basic functionality.
•
Use readiness probes for verifying if an application can
handle requests. These can be more comprehensive
and include dependency checks.
•
Use startup probes for applications with longer
initialization times to prevent premature restarts.
Keep Checks Fast and Efficient
In cloud environments, health checks are called frequently—sometimes
multiple times per second. Poorly implemented health checks can
significantly impact an application's performance and resource usage.
The following are principles and examples for implementing efficient
health checks.
442
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Quick Execution (Under 1 Second)
Health checks are typically executed frequently, sometimes multiple
times per second. Therefore, it's important that they complete quickly to
avoid impacting application performance and resource usage. Slow health
checks can delay container orchestration decisions, consume excessive
resources, and hinder efficient traffic routing. Listing 10-11 shows an
example of a good and bad resource use health check implementation.
Listing 10-11. Good and bad health check implementation
// Inefficient Health Check: Full table scan impacts
performance
@ApplicationScoped
@Readiness
public class SlowHealthCheck implements HealthCheck {
@Inject
EntityManager em;
@Override
public HealthCheckResponse call() {
// Avoid: Full table scan is resource-intensive
List<User> users = em.createQuery("SELECT u FROM User
u", User.class)
.getResultList();
return HealthCheckResponse.up("database-check");
}
}
// Optimized Health Check: Efficient database
connectivity check
@ApplicationScoped
@Readiness
public class OptimizedDatabaseCheck implements HealthCheck {
443
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
@Inject
EntityManager em;
@Override
public HealthCheckResponse call() {
// Recommended: Simple query for connection
verification
boolean isConnected = em.createNativeQuery("SELECT 1")
.setMaxResults(1)
.getResultList()
.size() > 0;
return HealthCheckResponse.status("database-check",
isConnected);
}
}
In the inefficient example in Listing 10-11, the health check performs a
full table scan using SELECT u FROM User u, which can be computationally
expensive, especially for large tables. This approach consumes significant
database resources and increases the execution time of the health check.
Note also the result wasn’t used anywhere in the health check.
Conversely, the optimized example replaces the full table scan with a
lightweight query SELECT 1 that simply verifies the database connection.
By fetching only a single row, this approach minimizes resource usage and
ensures rapid execution.
Light Resource Usage
Design health checks to minimize their resource footprint, including
memory allocation, CPU utilization, I/O operations, and network calls.
Excessive resource consumption by health checks can lead to performance
degradation and resource contention, particularly in high-traffic scenarios.
Listing 10-12 shows an example demonstrating resource-efficient checks.
444
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Listing 10-12. An example resource-efficient health check
implementation
@ApplicationScoped
@Liveness
public class EfficientResourceCheck implements HealthCheck {
private final AtomicReference<HealthCheckResponse>
cachedResponse =
new AtomicReference<>();
private final AtomicLong lastCheck = new AtomicLong();
private static final long CACHE_DURATION_MS = 5000; //
5 seconds
@Override
public HealthCheckResponse call() {
// Utilize cached response if within cache duration
long now = System.currentTimeMillis();
if (now - lastCheck.get() < CACHE_DURATION_MS) {
return cachedResponse.get();
}
// Perform expensive check only if cache expired
HealthCheckResponse response = performExpensiveCheck();
cachedResponse.set(response);
lastCheck.set(now);
return response;
}
private HealthCheckResponse performExpensiveCheck() {
// Your resource-intensive check logic here
}
}
445
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
This example introduces a caching mechanism to reduce the
frequency of resource-intensive checks. The cachedResponse stores the
result of the previous health check, and the lastCheck timestamp tracks
when the check was last performed. If the current time is within the
CACHE_DURATION_MS (5 seconds in this case), the cached response is
returned, avoiding the need to execute the expensive check repeatedly.
Free of Side Effects
Health checks should be non-intrusive, meaning they should not modify
the application state, trigger business operations, write to databases, or
send external notifications. Side effects introduced by health checks can
lead to unexpected behavior and data inconsistencies.
Idempotent Implementation
Health checks must be idempotent, meaning they can be safely called
multiple times without causing unintended side effects. This is important
because orchestration platforms often invoke health checks repeatedly,
and non-idempotent checks can lead to unpredictable behavior.
Provide Meaningful Information
Include relevant diagnostic information in your health check responses.
Listing 10-13 shows an example of returning meaningful information as
part of the health check response.
Listing 10-13. Meaningful health check information example
@ApplicationScoped
@Readiness
public class ServiceHealthCheck implements HealthCheck {
@Override
446
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
public HealthCheckResponse call() {
return HealthCheckResponse.named("external-service")
.withData("endpoint", serviceUrl)
.withData("latency_ms", connectionLatency)
.withData("status", connectionStatus)
.status(isHealthy)
.build();
}
}
Implement Proper Error Handling
Always handle exceptions gracefully and provide meaningful failure
information. Listing 10-14 shows an example of error handling in the
health check implementation.
Listing 10-14. Proper error handling in a health check
implementation
@ApplicationScoped
@Liveness
public class RobustHealthCheck implements HealthCheck {
@Override
public HealthCheckResponse call() {
try {
// Perform health check
return HealthCheckResponse.up("robust-check");
} catch (Exception e) {
return HealthCheckResponse.named("robust-check")
.down()
.withData("error", e.getMessage())
447
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
.withData("timestamp", System.
currentTimeMillis())
.build();
}
}
}
Configure Appropriate Check Intervals
When deploying to Kubernetes, configure appropriate probe intervals and
thresholds. Listing 10-15 shows an example of Kubernetes health check
definition.
Listing 10-15. Example K8s health check definition
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 20
periodSeconds: 30
timeoutSeconds: 1
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 30
periodSeconds: 60
timeoutSeconds: 2
448
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Use CDI Scopes Appropriately
The CDI scope of health check beans directly impacts their behavior,
performance, and resource usage in cloud environments. @
ApplicationScoped beans maintain a single instance throughout an
application's lifecycle, making them ideal when the application needs to
cache health check results or maintain state between invocations—for
example, tracking the history of dependency availability or implementing
circuit breaker patterns. This scope helps reduce resource usage and
improve response times for frequently called health checks.
The @Dependent scope, in contrast, creates a new instance for each
injection point or lookup, making it suitable for stateless health checks
that perform simple verifications. This scope is particularly useful when
a health check needs to inherit the lifecycle of the injecting component
or when you need independent instances of the same check running in
different contexts.
CDI producers offer additional flexibility when your health checks
require complex initialization or need to adapt their behavior based on
runtime conditions. They allow you to programmatically create health
check instances with different configurations or implementations based
on deployment environments, making them valuable for managing
environment-specific health check requirements in cloud deployments.
For instance, you might use producers to adjust timeout values or
dependency checks based on whether you're running in development,
staging, or production environments.
Monitor Health Check Performance
Implement monitoring for your health checks:
•
Track response times of health checks.
•
Monitor failure rates.
449
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
•
Set up alerts for repeated health check failures.
•
Log significant health status changes.
Health checks are critical infrastructure components in cloud
environments. They directly impact an application's availability and
scaling behavior. Regular testing and monitoring of health check
implementations ensure applications remain reliable and responsive in
cloud environments and production.
Common Health Check Patterns
A well-designed cloud-native application typically implements several
distinct types of health checks, each serving a specific purpose in
maintaining system reliability and availability.
Startup State Verification
Applications with complex initialization requirements should implement
startup health checks that verify essential resources are properly
initialized. This pattern is particularly valuable for applications that load
large datasets, warm up caches, or require connection pool establishment.
The startup check prevents premature exposure to traffic while ensuring
the application reaches a fully operational state, thus avoiding failed
requests during initialization.
Dependency Chain Validation
Multi-tier applications should implement layered health checking that
respects the dependency hierarchy. Start with fundamental infrastructure
checks (database connectivity, message queues), then progress to
dependent service validations, and finally verify application-specific
450
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
functionality. This layered approach helps pinpoint issues in complex
architectures and prevents the "cascade" effect where a single dependency
failure masks other problems.
Resource Health Monitoring
Applications should monitor critical system resources like memory usage,
thread pool status, and connection pool health. The key is to identify
leading indicators of potential problems—for example, a gradually
increasing memory usage trend or a shrinking connection pool—before
they impact service. These checks should include threshold warnings that
trigger before actual failures occur.
Self-Healing Status
When applications implement self-healing mechanisms (like retry logic,
circuit breakers, or fallback caches), health checks should accurately
reflect both the current state and the self-healing status. For instance,
if a service is operating in degraded mode with a fallback mechanism,
the health check should indicate this state while continuing to report as
operational. This pattern helps operators distinguish between complete
failures and degraded states.
Asynchronous Health State
For operations that are too expensive to check in real time, implement an
asynchronous health check pattern. Maintain a background process that
periodically validates complex dependencies or performs expensive health
validations, while the health check endpoint simply reports the most
recent status. This pattern is particularly useful for checks that involve
complex database queries or remote service calls.
451
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Composite Health Status
Large applications should aggregate multiple health checks into a
meaningful overall status. Rather than simply using a binary up/
down status, implement a more nuanced health reporting system that
can express partial availability or degraded states. This pattern helps
operations teams make better decisions about service routing and
maintenance.
Progressive Detail Level
Implement health checks that can provide different detail levels based
on the caller's needs. The base health check endpoint might return a
simple status, while additional parameters or separate endpoints can
provide more detailed diagnostics. This pattern is particularly useful in
production environments where you need to balance security concerns
with troubleshooting capabilities.
Each of these patterns serves a specific purpose in maintaining
system health, and most applications will implement several of them in
combination. The key is selecting and implementing patterns that align
with your application's architecture and operational requirements while
maintaining the performance and reliability characteristics necessary for
cloud-native environments.
Kubernetes Integration
Kubernetes uses health checks to make critical decisions about
container lifecycle management, service availability, and traffic routing.
Understanding how MicroProfile Health integrates with Kubernetes probes
ensures your Jakarta EE applications behave predictably in containerized
environments.
452
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Understanding Probe Mapping
MicroProfile Health provides endpoints that can be used with Kubernetes
probes. Think of it like this:
•
/health/ready tells Kubernetes if your application
is ready to handle requests. This is like a doorman
checking if the restaurant is open and ready for diners.
•
/health/live tells Kubernetes if your application is
still healthy. This is like a waiter checking in to see
if you need anything or if everything is alright with
your meal.
•
/health/started tells Kubernetes that the application
has finished starting up. This is like the chef making
sure the oven is preheated before putting the dish in.
While these endpoints are designed to work with Kubernetes probes,
you still need to configure your Kubernetes setup to actually use them. It's
not automatic, but it's a very convenient way to integrate the health of an
application with how Kubernetes manages it.
Probe Configuration Strategy
Configure probe timing based on an application's characteristics. Set
initialDelaySeconds to account for the application's startup time, ensuring
probes don't begin checking too early. The periodSeconds setting
determines check frequency—more frequent checks provide faster failure
detection but increase system load. The timeoutSeconds parameter should
align with your application's health check timeout configuration, typically
set to 1-2 seconds for readiness and liveness checks.
453
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Failure Handling
Kubernetes uses failureThreshold to determine how many consecutive
probe failures trigger action. For liveness probes, consider a higher
threshold (like 3-5) to prevent premature restarts due to temporary
glitches. Readiness probes can use lower thresholds since they only affect
traffic routing. The successThreshold parameter, particularly important for
readiness probes, determines how many consecutive successes are needed
to mark a pod as healthy.
Startup Probe Optimization
For applications with variable startup times, startup probes prevent premature
liveness checks from killing containers before initialization completes.
Configure startup probes with a longer failureThreshold that accounts for your
maximum expected startup time. Once the startup probe succeeds, liveness
probes take over with their more stringent timing requirements.
Resource Considerations
Health check frequency impacts resource usage. Each probe request
consumes CPU and memory, so balance check frequency against resource
constraints. In resource-constrained environments, consider using longer
periodSeconds values and implementing response caching in your health
checks. For clusters with many pods, stagger probe timings to prevent
thundering herd problems.
Zero-Downtime Deployments
Proper health check configuration is important for zero-downtime
deployments. Readiness probes should fail fast when the application
begins shutdown, preventing new traffic while existing requests complete.
454
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
During rolling updates, ensure readiness probes accurately reflect when
new versions can accept traffic, preventing premature pod termination
and maintaining service availability.
Production Best Practices
Implement gradual rollouts using Kubernetes deployment strategies like
rolling updates, combined with properly configured health checks. Use
pod disruption budgets to ensure minimum service availability during
cluster operations. Consider implementing custom health check logic for
blue-green deployments or canary releases, where health status might
need to account for deployment-specific criteria.
Monitoring andDebugging
Configure appropriate logging for health check failures to aid
troubleshooting. Use Kubernetes events and container logs to track
probe failures. Consider implementing custom metrics to track health
check performance and reliability. In production environments, monitor
probe timing and failure rates to identify potential configuration issues or
performance problems.
Health checks are part of an application's contract with Kubernetes.
They determine how the application scales, heals, and updates in
production. Take time to tune probe configurations for your specific use
case, and test different failure scenarios before deploying to production.
Well-configured health checks contribute significantly to application
reliability and maintainable operations in Kubernetes environments.
455
CHAPTER 10
TAKING A PULSE WITH HEALTH CHECK
Summary
This chapter covered the implementation of health checks in cloud-native
Jakarta EE applications using the MicroProfile Health specification. Health
checks are critical for container orchestration platforms like Kubernetes to
manage application lifecycle and maintain service availability.
Key Takeaways
1. MicroProfile Health provides three types of probes:
startup, liveness, and readiness checks, each serving
distinct purposes in application health monitoring.
2. Health checks can be implemented through the
HealthCheck interface and HealthCheckResponse
class, with CDI qualifiers distinguishing between
check types.
3. Integration with Kubernetes requires proper
configuration of probe timing, thresholds, and
intervals.
4. Best practices include keeping checks fast (under 1
second), implementing proper error handling, and
using appropriate CDI scopes.
5. Regular monitoring and testing of health checks
ensures reliable operation in cloud environments.
The chapter provided both theoretical understanding and practical
implementation guidance for creating effective health checks that enable
robust application management in cloud-native environments. With
application health monitoring in place, let’s explore how to secure them
using JSON Web Tokens (JWT)—a modern approach to cloud-native
authentication.
456
CHAPTER 11
Security with JWT
Introduction
Security is one of the most important aspects of application development.
There are so many things that can go wrong so fast with security. A rapidly
evolving domain, there are constantly new threats, exploits, and breaches
happening at all times. From the largest public-facing applications to the
smallest, every application is at risk of security breaches.
By the end of this chapter, you will
•
Understand token-based authentication and JWT
structure.
•
Know how to implement MicroProfile JWT for securing
REST resources.
•
Be able to validate and handle JWTs programmatically.
•
Learn to propagate security contexts across
microservices.
•
Master techniques for retrieving claims from JWTs.
•
Understand how to integrate Keycloak for identity
management.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_11
457
CHAPTER 11
SECURITY WITH JWT
Application security is a complex field that should be handled by
security experts. This chapter discusses how to use the Eclipse MicroProfile
JWT Propagation API to secure RESTful web services. This chapter is NOT
about the how of security. But rather with the how of security in place, the
goal of the chapter is to show how the MicroProfile JWT API can be used to
make use of the security infrastructure to secure REST resources.
As application developers, we the authors trust the management of
the entire process to security experts. As such, this chapter uses Keycloak
as the security framework, from which the MicroProfile JWT can be used
to secure REST clients. Keycloak is an open source identity and access
management (IAM) framework. It provides user federation, strong
authentication, user management, fine-grained authorization, and more.
This chapter delegates the process of creating users to Keycloak and
focuses on using JWT to secure web resources.
Token-Based Authentication
RESTful web services are stateless by nature. This means every request is
independent of the previous request. The server will need to be given the
same security-related information with each request. The most efficient
way to achieve this form of stateless security is through the use of tokens.
A token is a long string that can be verified to ascertain the veracity of the
claim of a calling client. It allows systems to authenticate, authorize, and
verify the identity of a client. Token-based security does not rely on the
HTTP session, making it much more scalable, performant, and reliable.
The token is mostly added to the request header. This will then be
grabbed by the service and validated, introspective to extract information
about the calling client and then create a security context that can then
be propagated to all parts of the protected service. The MicroProfile
458
CHAPTER 11
SECURITY WITH JWT
JWT API is a token-based authentication, authorization, and role-based
access control (RBAC) mechanism that can be used for token-based
application security. Json Web Tokens or JWT is a token-based standard1
that has emerged as the most popular standard for creating lightweight
security tokens.
A JWT is usually signed1
2 so the service can verify the token. The
information contained in a token is called claims. The claims can also be
encrypted3 so they are not passed as plain text in the header. A typical JWT
is made up of the header, the claims (or body), and the signature.
The Header
The JWT section of a JWT typically contains the type of algorithm used
to sign the JWT (RS256, ES256, HS256, etc.), the type of the token (e.g.,
JWT), the key ID, and other metadata depending on the issuer of the
token. Signing the JWT only enables receiving service to verify that the
information has not been tampered with. It does not make the token
unreadable. For that, a token will need to be encrypted, in addition to the
signing.
The Claims (or Body)
The claims or body of the JWT is all the information that the client would
like to pass to the server. A lot of the time the body contains the roles that
a given client is assigned. Roles determine the extent to which a client can
carry out different operations in an application.
1 JWT—https://datatracker.ietf.org/doc/html/rfc7519
2 JWS—https://datatracker.ietf.org/doc/html/rfc7515
3 JWE—https://datatracker.ietf.org/doc/html/rfc7516
459
CHAPTER 11
SECURITY WITH JWT
The Signature
The signature is optional with highly recommended information that
allows the service to verify that the token has not changed or been
tampered with along the way.
A JWT is a base64 encoded string of the header, claims, and signature
information. Listing 11-1 shows a sample JWT.
Listing 11-1. Sample JWT
eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJEMkdxY
mxJU3YzY1Jpdmh2ZFR0YmpaVDg2VkFGeUFpT29wZGlvZHYtQllJIn0.eyJleHA
iOjE2NjE2MzY5MDksImlhdCI6MTY2MTYzNjYwOSwianRpIjoiOTAxOGVlZmEtZ
Dc2Ni00ODI4LTgwMmUtYjFkNjMwOTQ5ODUxIiwiaXNzIjoiaHR0cDovL2xvY2Fs
aG9zdDo1MDUwL3JlYWxtcy9qd2FsbGV0IiwiYXVkIjoiYWNjb3VudCIsIn
N1YiI6ImY2OTU0YTRkLTFmZmEtNGNkMC05YmRhLTM4NmVkOWQwNzQ3ZCIsInR
5cCI6IkJlYXJlciIsImF6cCI6Imp3YWxsZXQtc2VydmljZSIsInNlc3Npb25f
c3RhdGUiOiJlOTY1ZWQ3YS00OTI3LTQ5MzItODQyOS1jNWNhMjNmYzQ5NzMiLC
JhY3IiOiIxIiwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbIm9mZmxpbmVfYWNj
ZXNzIiwiZGVmYXVsdC1yb2xlcy1qd2FsbGV0IiwidGVsbGVyIiwidW1hX2F1d
Ghvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJv
bGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3Mi
LCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6InByb2ZpbGUgZW1haWwi
LCJzaWQiOiJlOTY1ZWQ3YS00OTI3LTQ5MzItODQyOS1jNWNhMjNmYzQ5NzMiL
CJ1cG4iOiJtYXgiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImdyb3VwcyI6
WyJvZmZsaW5lX2FjY2VzcyIsImRlZmF1bHQtcm9sZXMtandhbGxldCIsInRl
bGxlciIsInVtYV9hdXRob3JpemF0aW9uIl0sInByZWZlcnJlZF91c2VybmFtZSI
6Im1heCJ9.lG6zEr-BEMQwyEUswIgCM5InWAH4ljAu8JK6Zc0naHD8kcaGAssxs
XHzf315n--cysYJzeAQBfDmzsJr_Roe0io2nN4CZ61T6Vz4YnE_5_RRn9n6cl2
rG_1oIsLknqKVseNQ4itZZjKfIGVUYxURxKmO6gsCH8FCHN1hu7rmq4jwPC0aO7
Ypvjg2IpExsIociprXk7_1iyfllZ4XnlHYBADOpkNOduJgMyojQwBgTz-xa9sBb-eoKys1gBD3nbV8STNbKAGzOUiQaq28T4x3pIn6JNfw2JbBu6_cxKXhzghoPukboLhn2C_MYJt4OiycxuprsbDRKoxAIjus_9yoA
460
CHAPTER 11
SECURITY WITH JWT
Listing 11-2 shows the decoded JWT. It shows the three parts, namely,
header, claims, and signature.
Listing 11-2. Decoded JWT
{
"alg": "RS256",
"typ": "JWT",
"kid": "D2GqblISv3cRivhvdTtbjZT86VAFyAiOopdiodv-BYI"
}
{
"exp": 1661636909,
"iat": 1661636609,
"jti": "9018eefa-d766-4828-802e-b1d630949851",
"iss": "http://localhost:5050/realms/jwallet",
"aud": "account",
"sub": "f6954a4d-1ffa-4cd0-9bda-386ed9d0747d",
"typ": "Bearer",
"azp": "jwallet-service",
"session_state": "e965ed7a-4927-4932-8429-c5ca23fc4973
"acr": "1",
"realm_access": {
"roles": [
"offline_access",
"default-roles-jwallet",
"teller",
"uma_authorization"
]
},
461
CHAPTER 11
SECURITY WITH JWT
"resource_access": {
"account": {
"roles": [
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
"scope": "profile email",
"sid": "e965ed7a-4927-4932-8429-c5ca23fc4973",
"upn": "max",
"email_verified": false,
"groups": [
"offline_access",
"default-roles-jwallet",
"teller",
"uma_authorization"
],
"preferred_username": "max"
}
{
"e": "AQAB",
"kty": "RSA",
"n": "3buUZWr0Fp9Rm85GPIAoYfiqNapj2DxW8gjMWOjPEgg4KUqg3tSC6G0
kAzPJ70zMmfe-b3CWBQvmNXWIUZCXPlnBuVKyWcowBQk7QRnEkOuw5vL6bYU5I2D
A_1CPIn4v3g4ox0GmjOwDflrlb2vlPw76BpHIKd-EUI-mkm-Yv6H60BZmo7
iRyVF7TNGVYgIg0xrVFPIvTDV2yvZKO4qG6qYWk2khMPqXm-725QBp2wgWDhowi
bjuoOCW1S5BCr5qc3N-uaPej7Nbcub80v1XGJ7feHqg4TXtNDCSikTAGCa0geW3
eP1wRoE_9QYzKlN45LI8LxhncUl58WpdulgblQ"
}
462
CHAPTER 11
SECURITY WITH JWT
The MicroProfile JWT
The MicroProfile JWT API provides a standard, mostly opinionated way of
verifying a JWT, authorizing the client, and propagating the resulting security
context to the rest of the application. It achieves these objectives by requiring
that JWTs be signed with RSA-based digital signature algorithms. All that
the JWT runtime needs is the public key of the authorizing server that
creates the JWT to verify the token. It also mandates certain information to
be available within the claims of the JWT. These are
•
exp: The expiration of the JWT. This ensures old,
expired tokens are rejected.
•
iss: The issuer of the token.
•
iat: The issued at, identifies when the token was issued.
•
upn: This is the user principal or the preferred
username of the currently logged-in user.
It also has recommended claims as follows:
•
sub: Who is being represented by this token?
•
jti: A unique identifier for this claim.
•
aud: Identifies the MP JWT endpoint(s) that can be
accessed by JWT.
These requirements allow a Jakarta EE application to be fully stateless.
The sub claim will be mapped to a java.security.Principal instance. The
groups will be used to determine if the Principal is in a given role required
by a given resource method. The client will send the token with each
request; the JWT runtime will validate and propagate the security context
with each call.
463
CHAPTER 11
SECURITY WITH JWT
MicroProfile JWT Security Process
MicroProfile JWT allows the creation of stateless microservices by
delegating the session information about users to the client. Each call by the
client contains all the information needed to construct a security context.
This security context is then plugged into existing Jakarta EE infrastructure
that is available to all parts of the application. There are three steps in the
MicroProfile JWT security process.
Authenticate theClient
The MicroProfile JWT runtime automatically validates the passed JWT on
the request header using the available public key of the issuing server or
authority. This is where Keycloak comes in, in our context. We use Keycloak,
an open source, freely available identity and access management (IAM)
solution as the issuing authority to issue the JWTs on our behalf. Alternatively,
you can sign up for a free plan with Auth0, an identity management platform
that offers similar features to Keycloak.
A typical enterprise application will have two tiers: the client or UI tier,
which can be written in, for instance, Angular or Vue, and the server or
resource tier, which is what we have seen so far in this book. The client tier
is the “user” or client of the server or resource tier. An end user will typically
interact with the UI tier. When the end user clicks a button in the UI to, for
instance, make a currency conversion, the UI sends a request to the backend
or server. This request by the UI to the server is what will contain the
JWT. But how does the UI get the token?
When an application uses Keycloak like we are doing (and
recommending), when a user clicks to sign up through the UI, that user
creation process will be delegated to Keycloak. So the user credentials will
be stored in Keycloak. When the user logs in through the UI, the UI redirects
the user to Keycloak to log in. Keycloak authenticates the user and
redirects them back to the UI. From this point, any operation made by the
464
CHAPTER 11
SECURITY WITH JWT
logged-in user that entails calling the backend server, the UI can go to Key­
cloak for a JWT, which will be forwarded to the server with each request
that the logged-in user performs.
This architecture fully decouples the backend server, or in this case our
Jakarta EE application, from knowing anything about the user. Our resources
simply require a valid token, and respective methods will require the currently
executing user to have certain roles. All of this will be sent to the server with
each call. This way, the UI tier and the backend server tier are fully decoupled
and stateless. There is no state sharing between them. Every security information
needed by the server is sent with each client request.
The bundled Keycloak has a sample user called max with the password
max that can be used to obtain JWTs. The sample cURL call in Listing 11-3
can be made to the open-id/connect endpoint in Keycloak to obtain a
JWT. This is the call that was used to generate the JWT shown in Listing 11-1.
Listing 11-3. Sample Keycloak call
curl --request POST --url http://localhost:5050/realms/jwallet/
protocol/openid-connect/token \
--header 'Content-Type: application/x-www-form-urlencoded' \
- -data realm=jwallet \
- -data grant_type=password \
- -data client_id=jwallet-service \
- -data username=max \
- -data password=max
Providing the Public Key
The MicroProfile JWT runtime will validate and authenticate the passed
JWT automatically by using the public key of the issuing server, in this
case Keycloak. The MicroProfile JWT spec requires the provision of the
public key or a URL for getting the public key. The specification defines
465
CHAPTER 11
SECURITY WITH JWT
two MicroProfile Config properties for passing the public key of the issuing
authority or server to the MicroProfile JWT runtime. These properties are
mp.jwt.verify.publickey and mp.jwt.verify.publickey.location.
The first property allows the passing of the public key text itself as the
value of the property. The second property allows specifying a URL from
which the public keys can be downloaded. Specifying both properties
results in a deployment exception. The mp.jwt.verify.issuer property is also
used to verify the value of the iss or issuer claim. The passed value in the
JWT must match the passed value in the property.
Listing 11-4 shows the public key and issuer properties as used in
jwallet. Because Keycloak is bundled as a container with the application,
we supply a URL to the Keycloak resource for loading the public keys.
Listing 11-4. Passing a public key URL
mp.jwt.verify.publickey.location= http://keycloak:5050/realms/
jwallet/protocol/openid-connect/certs
mp.jwt.verify.issuer=http://localhost:5050/realms/jwallet
A call to http://localhost:5050/realms/jwallet/protocol/openidconnect/certs returns the sample public keys shown in Listing 11-5.
Listing 11-5. Sample public keys
{
"keys": [
{
"kid": "D2GqblISv3cRivhvdTtbjZT86VAFyAiOopdiodv-BYI",
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"n": "3buUZWr0Fp9Rm85GPIAoYfiqNapj2DxW8gjMWOjPEgg4KUqg3t
SC6G0kAzPJ70zMmfe-b3CWBQvmNXWIUZCXPlnBuVKyWcowBQk7QRnEkOuw5vL6b
466
CHAPTER 11
SECURITY WITH JWT
YU5I2DA_1CPIn4v3g4ox0GmjOwDflrlb2vlPw76BpHIKd-EUI-mkm-Yv6H
60BZmo7iRyVF7TNGVYgIg0xrVFPIvTDV2yvZKO4qG6qYWk2khMPqXm-725QBp2
wgWDhowibjuoOCW1S5BCr5qc3N-uaPej7Nbcub80v1XGJ7feHqg4TXtNDCSikTA
GCa0geW3eP1wRoE_9QYzKlN45LI8LxhncUl58WpdulgblQ",
"e": "AQAB",
"x5c": [
"MIICnTCCAYUCBgGC2NIn1TANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdqd
2FsbGV0MB4XDTIyMDgyNjA2MjIwN1oXDTMyMDgyNjA2MjM0N1owEjEQMA4GA1
UEAwwHandhbGxldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAN27
lGVq9BafUZvORjyAKGH4qjWqY9g8VvIIzFjozxIIOClKoN7UguhtJAMzye9MzJn
3vm9wlgUL5jV1iFGQlz5ZwblSslnKMAUJO0EZxJDrsOby+m2FOSNgwP9QjyJ+L9
4OKMdBpozsA35a5W9r5T8O+gaRyCnfhFCPppJvmL+h+tAWZqO4kclRe0zRlWICI
NMa1RTyL0w1dsr2SjuKhuqmFpNpITD6l5vu9uUAadsIFg4aMIm47qDgltUuQQq+
anNzfrmj3o+zW3Lm/NL9Vxie33h6oOE17TQwkopEwBgmtIHlt3j9cEaBP/UGMy
pTeOSyPC8YZ3FJefFqXbpYG5UCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAuuo6
yFASkSWDLh9kyMTZhhcfV87ZEoC4kmkNn/2N2d0gypqxxLWPDG7rk2QLqocNT0I
P6wh+cr9TO/oAUdIc1vAJuLWsw/XiGbPjTVmxw9r1eg3tMphrw+wG4CrRNsKTs1
xgDDMnAyTA7zNZylSwAJ2YBy/7WAb1DzPdpwxuERY3Bn1U9pTV6Tth+SY3n0DVW
Yl9ik2eyv/UoTCLdf9gInxHxoyl6moIH944UZXdVnZ9s+TONtVu278fQNUJMbvu
fN1+IQQkZLH5zehVd8IY/vX1q9ROjFeaHjYEYSoggo3tCT93KVFYGA6UCm2
ADQfluMxNwkIIdvfRVzqIuCKZuw=="
],
"x5t": "uej9O_JH-rlIpJVQMTBiD6kf-1k",
"x5t#S256": "szj37ByL-T6Plrmzbgb7Bnq32KsYtGp_B_dDOYGEWcI"
},
{
"kid": "B5uP6pwSkS-wvKmh31ZeEmeXNKU_UaO9EfTOeut00NY",
"kty": "RSA",
"alg": "RSA-OAEP",
"use": "enc",
467
CHAPTER 11
SECURITY WITH JWT
"n": "sR3wZR9t35zM_sftCb2EbX6_tZo1boubrmnuj8YZ1utCOl2pQGX7v
3uz_YHGsAbp-3J3iCt94KliRKA2yYCVi2Ozqd-EEz6GAYxF1HzYghWO-j9jMr
Nu1N-O8LXVEp21wPdIDsIuCLkqYWZGgoOzY2yyWkVjiHcAu3_LokwufVu-BM9i
RY2FZrvgYEHPGZOk5a8hTIHSIx6dXUcU6oZ0etiGdidrIWH5GFXLSZt
pcuya-w01_o1Khm97dCtGY3pVasnLgDK6Vguzul1MdpTQHwFI7m3O7uQB0CR
tqe8qPnNxVLal_Ow5b5N7YNw5fufEqvLk5Dz-au4TPuFwSSvVrw",
"e": "AQAB",
"x5c": [
"MIICnTCCAYUCBgGC2NIoXjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdq
d2FsbGV0MB4XDTIyMDgyNjA2MjIwN1oXDTMyMDgyNjA2MjM0N1owEjEQMA4GA1
UEAwwHandhbGxldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALEd
8GUfbd+czP7H7Qm9hG1+v7WaNW6Lm65p7o/GGdbrQjpdqUBl+797s/2BxrAG
6ftyd4grfeCpYkSgNsmAlYtjs6nfhBM+hgGMRdR82IIVjvo/YzKzbtTfj
vC11RKdtcD3SA7CLgi5KmFmRoKDs2NsslpFY4h3ALt/y6JMLn1bvgTPYkWNhW
a74GBBzxmTpOWvIUyB0iMenV1HFOqGdHrYhnYnayFh+RhVy0mbaXLsmvsNNf6NS
oZve3QrRmN6VWrJy4AyulYLs7pdTHaU0B8BSO5tzu7kAdAkbanvKj5zcVS2pfzs
OW+Te2DcOX7nxKry5OQ8/mruEz7hcEkr1a8CAwEAATANBgkqhkiG9w0BAQs
FAAOCAQEAXW0wtyu6Tmv6i9rEvly5jvNcsNsvHVpW9tSV0KVWFP0YgvQ0dIQo
RhygpvVfZMrlXW5EQ0uKnvZCbt/BzEPMl3G6DfsaTssw1GeaquMgw1osNqG7HC
HGqQX8+EG5U3Neov4+YsSCtYYCWsYqO8OYK6lqp8TQ0+Ok6u9aTpFvH233Gd9Z
mM72fN8omfR2X5dwlwL6uNAKiGc6rqavklV0qK3/TpSbYXG8oPGuAFmJMGmSJ9
Xr1+x0gr3ncsYQnHf7jjTx7y3BG+AB2G7y3uez2fXDBktjBUiAV+31N4fh99Wnb
OPiVkhM2lWFMeuL1jg+vDgL/+PDziAGo2R5tgJM1w=="
],
"x5t": "rU2BclI4blvOQgymzyX0GHmm_Tk",
"x5t#S256": "Vkv7YeizaqHS23BlvZCJwTSpjpvp55J1PCmE2LtREos"
}
]
}
468
CHAPTER 11
SECURITY WITH JWT
With the provided keys, the MicroProfile JWT runtime will automatically
validate and authenticate each REST call to all protected resources in
application. By default, the runtime will look for the key in the HTTP
Authorization header. This can be configured to something else through
the Config property mp.jwt.token.header. We recommend leaving the
default unless you have a very specific architectural reason to change that.
JWT Validation Error Handling
MicroProfile JWT implementations will automatically reject tokens with a
401 (Unauthorized) response in these cases:
1. Missing or invalid signature algorithm
2. Missing issuer (iss) claim
3. Missing issuance time (iat) claim
4. Missing expiration time (exp) claim
5. Missing principal name (no upn, preferred_username, or sub claim)
6. Failed signature verification
7. Failed token decryption (for encrypted tokens)
Authorization
When the client is authenticated, the MicroProfile JWT then maps the
passed groups in the claims of the JWT to client roles. For each protected
resource, the runtime will automatically check if the currently executing
client has the role declared by the server.
469
CHAPTER 11
SECURITY WITH JWT
Security Context Propagation
After a client has successfully undergone authentication and the presented
token has been verified, the MicroProfile JWT API provides the functionality
to retrieve the raw, unparsed token. This raw token can then be forwarded to
other backend services that exist within the same microservice cluster. This
architecture facilitates a trust relationship between services; for instance, if
Service A depends on data or functionality provided by Service B, and both
of these services are secured using the MicroProfile JWT, Service A can use
the raw token extracted from the client's initial authentication to make calls
to Service B. In essence, this propagates the JWT and its inherent security
context throughout the microservices architecture.
This propagation of the JWT eliminates the need for each individual
service to re-authenticate the client. Once the client has been authenticated
by one service, the trust established by the JWT can be extended to other
services within the cluster, streamlining the authentication process and
reducing overhead. However, it's crucial to ensure that all services within the
cluster share the same trust domain and cryptographic keys for JWT validation
to maintain security and prevent unauthorized access.
MicroProfile JWT Usage
The first step to protecting resources with MicroProfile JWT is through the
use of @LoginConfig on a Jakarta REST jakarta.ws.rs.core.Application class.
Listing 11-6 shows the RootResourceConfiguration class, which extends
Application, annotated with @LoginConfig with the MP-JWT auth method.
470
CHAPTER 11
SECURITY WITH JWT
Listing 11-6. JWT configuration
@ApplicationPath("api")
@LoginConfig(authMethod = "MP-JWT")
public class RootResourceConfiguration extends Application {
}
The @LoginConfig annotation tells the runtime that all resources in
the application should be protected and thus all client requests will need
to pass a valid JWT for verification and authentication. With the configuration
in place, securing a web resource is as simple as annotating the resource
class or methods with @RolesAllowed. Listing 11-7 shows the WalletResource
requiring only authenticated users with the role teller. User roles are
completely managed in Keycloak. In enterprise applications, the product
owner together with the business team will determine the requisite role
for each user of an application. All of this can be done fully in Keycloak.
Our backed service is simply consuming what is configured in the security
framework.
Listing 11-7. WalletResource secured
@Produces(MediaType.APPLICATION_JSON)
@Path("wallets")
@RolesAllowed("teller")
public class WalletResource {
}
The @RolesAllowed annotation, from the jakarta.annotation.security.
RolesAllowed package, will cause a 401 HTTP status code to be returned to
clients that make calls to any resource in this class without a valid token.
Listing 11-8 shows the response of a sample unsecured call.
471
CHAPTER 11
SECURITY WITH JWT
Listing 11-8. Response from a call with no token
http://localhost:3001/wallet/api/wallets
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="MP-JWT", error="invalid_token"
Content-Language: en-US
Content-Length: 0
Date: Sun, 28 Aug 2022 00:13:24 GMT
Getting Information from Tokens
When a user successfully verified and authenticated, the application might
want to get hold of some information contained in the claims of the token.
The API provides two primary ways of accessing the claims in the body
of the JWT. These are the JsonWebToken bean and the injection of claim
values using the @Claim qualifier.
JsonWebToken
The JsonWebToken interface extends the java.security.Principal and contains
methods for getting the claims in the JWT. It also has a method for getting the
raw token. This can be used to get the raw token for onward propagation to
other services. This is our recommended approach to consuming the claims
of the JWT because the JsonWebToken instance does not require the bean
into which it is injected to be @RequestScoped. Listing 11-9 shows the
injection of the JsonWebToken into the @ApplicationScoped WalletService.
Listing 11-9. Injection of JsonWebToken
@ApplicationScoped
public class WalletService {
@Inject
JsonWebToken jsonWebToken;
472
CHAPTER 11
SECURITY WITH JWT
public BalanceResponse createWallet(CreateWalletRequest
request){
Wallet wallet = new Wallet();
wallet.setBalance(BigDecimal.ZERO);
wallet.setCurrency(request.getCurrency());
wallet.setAuthUserId(jsonWebToken.getSubject());
wallet = walletRepository.save(wallet);
return getBalance(wallet.getId());
}
}
The WalletService is an application-scoped bean that has the
JsonWebToken injected into it. The MicroProfile JWT runtime will provide
an implementation of the interface for us. The injected JsonWebToken can
be used to obtain the claims of the token. The createUser method calls the
getSubject method on the jsonWebToken to get the subject of the token.
The subject of the token returned by Keycloak is the IAM ID of the user.
This way, we link wallet database records to the users in Keycloak
without both services knowing anything about each other. The WalletService
is not a Jakarta REST artifact. It is a plain CDI bean, but through the
MicroProfile JWT API, we are able to access the claims in the token passed
through the HTTP header in the service layer of our application. We
believe this is the cleanest way to access claims from the JWT and thus
recommend this approach. Even if an endpoint is not secured, resulting in
no token passed, an empty instance of the JsonWebToken will be created.
All method invocations on the empty instance will return null.
With this, we can also refactor the AbstractEntityListener to finally set
the createdBy audit field for persisted entities. Listing 11-10 shows the
updated AbstractEntityListener using the JsonWebToken to set the
createdBy and updatedBy fields.
473
CHAPTER 11
SECURITY WITH JWT
Listing 11-10. Using the JsonWebToken
@ApplicationScoped
public class AbstractEntityEntityListener {
@Inject
JsonWebToken jsonWebToken;
@PrePersist
void init(final Object entity) {
final AbstractEntity abstractEntity = (AbstractEntity)
entity;
abstractEntity.setCreated(LocalDateTime.now
(ZoneOffset.UTC));
abstractEntity.setCreatedBy(jsonWebToken.getClaim
(Claims.upn));
}
@PreUpdate
void update(final Object entity) {
final AbstractEntity abstractEntity = (AbstractEntity)
entity;
abstractEntity.setUpdated(LocalDateTime.now
(ZoneOffset.UTC));
abstractEntity.setEditedBy(jsonWebToken.getClaim
(Claims.upn));
}
}
The @PrePersist and @PreUpdate Jakarta Persistence callback
methods use the getClaim method of the JsonWebToken to get a specific
claim. The org.eclipse.microprofile.jwt.Claims enum contains constants of
all claims in the JWT.
474
CHAPTER 11
SECURITY WITH JWT
Injecting into Raw Types and ClaimValue
JWT claims can also be injected into simple Java types through @Inject
and the use of the @Claims qualifier. We generally do not recommend this
way of getting the tokens because some of the field types into which claims
can be injected require the beans into which they’re being injected to be
@RequestScoped. Effectively to be able to fully utilize injecting claim values
this way, the bean should be @RequestScoped. Listing 11-11 shows the injection
of claims using these two constructs.
Listing 11-11. Injecting into simple types
@Action
public class WalletService {
@Inject
@Claim(standard = Claims.sub)
private String subject;
@Inject
@Claim(standard = Claims.raw_token)
private ClaimValue<String> rawToken;
}
The subject field is a simple String type annotated @Inject and the
qualifier @Claim. The standard parameter of the @Claim qualifier is
passed the name of the claim to inject into this field. The Claims enum
is used to pass the sub or subject claim as the claim of interest. The org.
eclipse.microprofile.jwt.ClaimValue is an interface that extends the
Principal interface. It has two methods, getName and getValue. getName
returns the name of the claim, and getValue returns the value of the claim
in the token.
475
CHAPTER 11
SECURITY WITH JWT
MicroProfile JWT and the SecurityContext
The jakarta.ws.rs.core.SecurityContext interface is a Jakarta REST artifact
that can be injected into resource artifacts through the @Context annotation.
It has methods for getting the Principal, checking if the currently logged-in
user is in a given role, if the request was made through an HTTPS connection,
and the authentication scheme. In a MicroProfile JWT application, the is
UserInRole method will map the role set to the passed groups of the claims
in the token. The getPrincipal method will also return a Principal, which
is also an instance of JsonWebToken. Effectively the MicroProfile JWT
propagates all the information passed through the token to all parts of the
application and existing security infrastructure within Jakarta EE. Listing 11-12
shows injecting the SecurityContext into the WalletResource.
Listing 11-12. Injecting SecurityContext
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("wallets")
@RolesAllowed("teller")
public class WalletResource {
@Context
SecurityContext securityContext;
}
Summary
This chapter covered using the MicroProfile JWT API for securing Jakarta
EE REST resources. Following best practices, we offloaded user credential
handling to Keycloak. You learned how to activate MicroProfile JWT with
@LoginConfig and secure resources using @RolesAllowed.
476
CHAPTER 11
SECURITY WITH JWT
Key Takeaways
1. JWTs contain headers, claims, and signatures that
enable stateless security.
2. The MicroProfile JWT runtime automatically
validates tokens using public keys.
3. The JsonWebToken interface provides
programmatic access to JWT claims.
4. Security contexts can be propagated across
microservices using raw tokens.
5. Keycloak integration separates credential
management from application logic.
6. The SecurityContext interface enables role-based
access control in resources.
Remember that security is complex and fast-changing, with new
exploits emerging daily. The hybrid approach discussed here—delegating
credential handling to Keycloak while our application consumes generated
tokens—helps mitigate security risks.
With security fundamentals in place, let's explore how to verify our
secured endpoints and other components through automated testing
using TestContainers.
477
CHAPTER 12
Testing with
TestContainers
Testing forms a core part of application development, whether for
monolithic or microservices applications. While testing is universally
acknowledged as essential, there's no single "right" approach. The testing
methods chosen typically depend on the application and its domain.
The application development platform often determines available
testing options. The Jakarta EE platform, built on Java SE, offers many
testing possibilities. This chapter explores testing Jakarta EE applications
using JUnit and TestContainers libraries, starting with basic testing
theories, then examining unit testing of Jakarta EE components, and finally
demonstrating integration tests with TestContainers.
By the end of this chapter, you will
•
Understand fundamental testing concepts and
principles.
•
Know how to write effective unit tests for Jakarta EE
components using JUnit and Mockito.
•
Be able to implement integration tests using
TestContainers.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_12
479
CHAPTER 12
TESTING WITH TESTCONTAINERS
•
Have practical knowledge of setting up test
environments for Jakarta EE applications.
•
Be equipped to choose appropriate testing strategies
for different scenarios.
The Theory of Application Testing
Testing can be defined as the process of establishing the general
correctness and reliability of an application through a combination of
different test types. The term “general” is important because testing does
not guarantee that an application has no defects. It only surfaces possible
defects in the application. There are two broad categories of tests, namely,
manual and automated tests. Then there are different types of tests that
can be run under each of these categories. Some test types transcend both
categories. Below is a list of the general types of application tests.
Types ofTests
Unit Tests
A unit test is an automated test that tests a single component in isolation
to verify if the component is working as expected. Unit tests are the most
atomic tests in any test suite. Depending on the particular component
being unit-tested, its dependencies might be mocked in order to be able to
unit-test just that component in isolation. Unit tests are generally very fast
to run because of their isolated nature.
480
CHAPTER 12
TESTING WITH TESTCONTAINERS
Integration Tests
An integration test is a test for asserting that different components of the
application that together carry out a specific function work correctly.
Integration tests span more than one component or microservice. For
example, an integration test to assert the successful creation of a wallet
can first assert the creation of a user before asserting for the creation
of a wallet. In this case, an actual call will be made to both modules.
Integration tests tend to be much more time-consuming to run because
they can span several components and most likely include several network
calls. Integration tests are also automated.
Functional Tests
A functional test focuses on the business aspect of an application.
Functional tests will normally verify the results of the operation under
test. There is a slim difference between functional and integration tests
because both tests will cause different components of the application to be
invoked. In some organizations, functional and integration tests are one
and the same. However, technically, functional tests assert the output of an
operation to verify that it equals a preset, expected value. Integration tests,
however, generally check if the components are working. Functional tests
can be manual or automated.
Performance Tests
A performance test checks how the application behaves when subjected
to different workloads. Performance tests can help unearth bottlenecks
because they measure things like the speed of the application, the
reliability of a site, and how scalable a component is, among others. This
kind of test can help optimize applications based on the data gathered
from the tests. Performance tests are automated.
481
CHAPTER 12
TESTING WITH TESTCONTAINERS
Smoke Tests
A smoke test is mostly a manual test that checks if the basic functionality of
an application is working as expected. Smoke tests generally follow a new
build or release of the application and precede other types of checks.
Other Tests
There are other tests, like end-to-end and acceptance testing that are
different variations of integration and functional tests. Furthermore, while
this chapter primarily focuses on backend component and integration
testing, comprehensive application testing often includes verifying the
user interface.
Frontend automated testing, using tools such as Selenium, simulates
user interactions within a web browser to ensure the user interface
functions correctly. In the end, every organization will have a mix of
different test types and modes based on the domain. The test types
enumerated above are in no way an exhaustive list or all the test types
out there. But these are the most common that cut across all types of
organizations.
Principles ofTesting
As important as software application testing is, there are no universal
criteria for determining what comprise good testing practices. The
plethora of programming languages and application development
frameworks out there mean testing is a highly heterogeneous activity that
differs from one platform to the other and from one application to the
other. The American Software Testing Qualifications Board (ASTQB) has
identified seven principles that can help guide the creation of an effective
testing regime. These principles are as follows.
482
CHAPTER 12
TESTING WITH TESTCONTAINERS
Testing Shows the Presence of Defects, Not
Their Absence
Tests can help surface bugs in an application. However, tests cannot
guarantee that an application is bug-free. All the tests in a test suite
passing does not mean there are no defects that can be unearthed. This
notwithstanding, having extensive tests can give reasonable assurance that
the application will not fail under conditions that have been tested.
Exhaustive Testing Is Impossible
Enterprise applications are very large and complicated. It is not possible
to have tests that cover every possible permutation of an application.
Attempting any such activity will prove expensive. An analysis of different
core features should be made and test efforts focused on critical areas.
Early Testing Saves Time and Money
A quick smoke test of a new application release can help identify
showstopper bugs that could have required the running of the entire
test suite to unearth. This also applies to implementing test-driven
development as much as possible.
Defects Cluster
A small number of components in an application will be responsible for
the majority of bugs. Testing should then focus on these components that
are responsible for the majority of the bugs. This is essentially applying the
pareto principle to testing application components.
483
CHAPTER 12
TESTING WITH TESTCONTAINERS
Beware of the Pesticide Principle
The same set of tests repeated over a long period of time may end up not
catching new defects. This principle is a simile to the ineffectiveness of
pesticide applied to the same area over a long period in killing insects.
Tests will need to be updated, refactored with new input data and
permutations to keep them effective at identifying application defects.
Testing Is Contextual
Testing is a highly context-dependent activity. The tests applied to a
business application will differ from the tests applied to an aerospace
computer control application. This is important to keep in mind when
taking inspiration for creating testing systems.
Absence of Errors Is a Fallacy
As elucidated in the first principle, tests do not guarantee the absence of
errors. As such, it is a mistaken notion to assume an application is free of
defects if tests do not unearth any. Also identifying and fixing defects does
not guarantee the system cannot fail.
Testing in Jakarta EE
Jakarta EE, as an application development platform, does not have a
testing specification or API of its own. However, as it is built on Java SE, the
gamut of testing libraries and frameworks available on Java SE can be used
to test Jakarta EE applications. However, testing a Jakarta EE application
presents some challenges.
A modern Jakarta EE application, like the one discussed so far in this
book, makes heavy use of the Jakarta Contexts and Dependency Injection
API. Almost all components are managed by one runtime or the other. For
instance, a CDI bean might declare a dependency on another bean that in
turn has a dependency on a JPA managed artifact like the EntityManager.
484
CHAPTER 12
TESTING WITH TESTCONTAINERS
Unit-Testing Jakarta EE Components
Unit-testing Jakarta EE components can be achieved with a little bit
of refactoring of the component under test. A component under test
that uses field injection can be refactored to use constructor injection
for its dependencies. This way, the component under test can have
its dependencies passed to it by CDI during application runtime and
manually instantiated during testing through its constructor, passing in
mocked instances of its dependencies.
Before diving into specific testing libraries, let's look at a practical
example of unit-testing a CDI component. Consider a UserService that
handles user creation and sends welcome emails as shown in Listing 12-1.
Listing 12-1. Sample unit testing of a CDI component
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private EmailService emailService;
private UserService userService;
@BeforeEach
void setup() {
userService = new UserService(userRepository,
emailService);
}
@Test
void shouldCreateNewUser() {
CreateUserRequest request = new
CreateUserRequest("john@example.com", "John Doe");
485
CHAPTER 12
TESTING WITH TESTCONTAINERS
User user = new User(1L, "john@example.com",
"John Doe");
when(userRepository.save(any(User.class))).
thenReturn(user);
UserResponse response = userService.
createUser(request);
assertNotNull(response);
assertEquals("John Doe", response.getName());
verify(emailService).sendWelcomeEmail(eq("john@
example.com"));
}
}
This example shows key unit testing principles—isolating the
component, mocking dependencies, and verifying behavior. Now, let's
examine the specific tools that make this possible.
JUnit
JUnit is a Java testing library for making assertions on test artifacts. It has
a number of callbacks for setting up and tearing down test data. It also has
an extension API that other testing libraries have built on top of to extend
testing for different purposes. JUnit is arguably the most popular testing
library in enterprise Java.
Mockito
Mockito is a Java library for creating mocked objects in unit tests. A
component under test that has dependencies on other components will
have those dependencies mocked. Mocking allows predictable values on
the mocked objects to be returned and later asserted.
486
CHAPTER 12
TESTING WITH TESTCONTAINERS
To test the WalletService CDI bean of jwallet, we first refactor it to
use constructor injection for its two CDI-managed other application
components. This way, in a unit test, the WalletService can easily pass
mocked objects. Listing 12-2 shows the refactored WalletService.
Listing 12-2. Refactored WalletService
@Action
@NoArgsConstructor
public class WalletService {
WalletRepository walletRepository;
TransactionRepository transactionRepository;
RateService rateService;
@Inject
public WalletService(WalletRepository wallet,
TransactionRepository txn,
RateService rate) {
this.walletRepository = wallet;
this.transactionRepository = txn;
this.rateService = rate;
}
}
The WalletService has a dependency on the WalletRepository,
TransactionRepository, and RateService. It has been refactored out to use
constructor injection, with a single constructor annotated @Inject, passing
in the three dependencies and initializing the class field with those. With
this simple refactor, the WalletService is now ready to be unit-tested.
Listing 12-3 shows the WalletService unit test class, WalletServiceTest.
487
CHAPTER 12
TESTING WITH TESTCONTAINERS
Listing 12-3. WalletServiceTest
@ExtendWith(MockitoExtension.class)
public class WalletServiceTest {
@Mock
WalletRepository walletRepository;
WalletService walletService;
static String walletCurrency;
static BigDecimal balance;
@BeforeAll
public static void initAll() {
walletCurrency = "GHS";
balance = new BigDecimal("50");
}
@BeforeEach
void init() {
walletService = new WalletService(walletRepository,
null, null);
when(walletRepository.findById(anyLong())).
thenAnswer(i -> {
Wallet wallet = new Wallet();
wallet.setId(i.getArgument(0));
wallet.setCurrency(walletCurrency);
wallet.setBalance(balance);
return wallet;
});
}
488
CHAPTER 12
TESTING WITH TESTCONTAINERS
@Test
void shouldFindWallet() {
BalanceResponse response = walletService.
getBalance(1L);
assertNotNull(response);
assertEquals(1L, response.getData().getWalletId());
assertEquals(balance, response.getData().getBalance());
assertEquals(walletCurrency, response.getData().
getCurrency());
}
}
The class is annotated by @ExtendWith and passed the
MockitoExtension.class. This registers the MockitoExtension with the JUnit
runtime. The @Mock annotation is used to mock the WalletRepository.
Specifically, @Mock is an annotation provided by the Mockito library that
instructs Mockito to create a mock object (a test double) for the annotated
field. This allows you to simulate the behavior of the dependency (like
WalletRepository here) and isolate the WalletService for focused unit
testing.
The @BeforeAll callback method sets up some expected data that
the component under test, in this case the WalletService method to be
tested, should return. The WalletService object is instantiated, passing in
the mocked WalletRepository and null for the other two parameters. We
could equally have mocked the two other parameters of the WalletService
constructor.
The static Mockito when method is called to mock a call to the
WalletRepository.findById method. The mock simply captures the passed
ID and constructs a Wallet with it. We now have everything in place to
unit-test the getBalance method of the WalletService.
489
CHAPTER 12
TESTING WITH TESTCONTAINERS
The shouldFindWallet test method calls the getBalance method on the
WalletService and proceeds to use the JUnit assertion methods to assert
the expected data. This is generally how you craft unit tests in Jakarta EE
for application components. Note that nothing significantly different was
needed apart from the small refactoring of the component under test to
use constructor injection to initialize dependent fields.
This kind of test is incredibly fast and can be run multiple times on the
CI/CD pipeline. It is important to note that the WalletServiceTest is tested
as a POJO that has nothing to do with Jakarta EE. Its method is tested and
asserted to be acting as expected. As much as possible, you should unit­
test core components of your application.
Integration Testing in Jakarta EE
Unlike unit testing, integration testing requires different components
to talk to each other. This requires having a running instance of the
application within the test context. Jakarta EE integration testing,
depending on the application, entails making a call to an entry point in
the application that will then result in the call to all constituent units of
interest. This entry point is mostly a REST endpoint.
Deploying a running application in the test context had always
been a little cumbersome in Jakarta EE. Frameworks like Arquillian
helped in this regard. But even that was difficult to set up and required
significant plumbing for the various compatible runtimes. As more and
more applications are being developed to be cloud-native first, the use
of containers means a given environment can be replicated in different
contexts as long as there is support for containers within that context.
TestContainers is a library for deploying applications as Docker
containers in a test environment. As jwallet is packaged as Docker
containers, spawning a running instance for integration testing requires
only a docker-compose file. This docker-compose file will be used by the
490
CHAPTER 12
TESTING WITH TESTCONTAINERS
TestContainers library to create a running application instance in the test.
With a running application instance, we can then proceed to fire REST
calls to the application.
With TestContainers, there is no difference between the application
running in the test and the deployed one because they are both created
from the same Docker containers. TestContainers has different modules
for different stacks. The DockerComposeContainer module is for running
containers from docker-compose files. Listing 12-4 shows the setup of
DockerComposeContainer to create containers from the wallet module’s
docker-compose file.
Listing 12-4. DockerComposeContainer
try (DockerComposeContainer composeContainer = new
DockerComposeContainer(new File("docker-compose.yaml")).
withExposedService("wallet", 3001)) {
composeContainer.start();
walletServiceUrl = String.format(walletServiceUr
lTemplate,
composeContainer.getServiceHost
("wallet", 3001),
composeContainer.getServicePort
("wallet", 3001));
client = ClientBuilder.newClient();
target = client.target(walletServiceUrl);
}
The DockerComposeContainer is instantiated in a try-with-resources
block so it can be auto-closed for us (it is AutoClosable). It is passed the
docker-compose file and the service to expose from it, along with the
port. The start method is called on the instance. The getServiceHost and
491
CHAPTER 12
TESTING WITH TESTCONTAINERS
getServicePort methods are called to get the host and port of the service as
created in the running container. This is then passed to the target method
of the Jakarta REST Client object. With this setup in place, we have a full
running instance of the wallet module against which REST calls can be
made and test assertions carried out on the responses. Listing 12-5 shows
the createWallet JUnit test in the WalletResourceIT class.
Listing 12-5. createWallet test
class WalletResourceIT extends AbstractWalletIT {
@Test
void createWallet() {
CreateWalletRequest createWalletRequest = new
CreateWalletRequest();
createWalletRequest.setCurrency("USD");
BalanceResponse balanceResponse = target.
path("wallets").request()
.post(Entity.json(createWalletRequest),
BalanceResponse.class);
assertEquals("0", balanceResponse.getResponse().
getResponseCode());
assertEquals("OK", balanceResponse.getResponse().
getResponseMessage());
assertEquals(createWalletRequest.getCurrency(),
balanceResponse.getData().getCurrency());
assertEquals(BigDecimal.ZERO, balanceResponse.
getData().getBalance());
}
}
492
CHAPTER 12
TESTING WITH TESTCONTAINERS
The WalletResourceIT class extends AbstractWalletIT, which contains
the TestContainers instantiation code. The createWallet method is a JUnit
test that fires a REST call to the wallet resource to create a wallet and then
makes some assertions on the returned data. Unlike the unit test, this test
could take some time because the wallet creation process involves a call
to the database. With just a few lines of code, we have a fully containerized
application runtime from which we can make calls to create integration
tests. We highly recommend you take a look at TestContainers for your
Jakarta EE testing.
While the previous example showed a basic wallet creation test, realworld integration tests often need to handle multiple related operations
and database states. Listing 12-6 shows a complete user management flow,
including both creation and retrieval, while managing test containers for
both the application and its database.
Listing 12-6. A comprehensive end-to-end test
@Testcontainers
public class UserResourceIT {
@Container
private static final PostgreSQLContainer<?> postgres = new
PostgreSQLContainer<>("postgres:14")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
private static String apiBaseUrl;
private static Client client;
@BeforeAll
static void init() {
postgres.start();
System.setProperty("DB_URL", postgres.getJdbcUrl());
493
CHAPTER 12
TESTING WITH TESTCONTAINERS
DockerComposeContainer<?> app = new
DockerComposeContainer<>(
new File("src/test/resources/docker-composetest.yml"))
.withExposedService("app", 8080);
app.start();
apiBaseUrl = String.format("http://%s:%d/api",
app.getServiceHost("app", 8080),
app.getServicePort("app", 8080));
client = ClientBuilder.newClient();
}
@Test
void shouldCreateAndRetrieveUser() {
CreateUserRequest createRequest = new
CreateUserRequest("jane@example.com", "Jane Doe");
Response createResponse = client.target(apiBaseUrl +
"/users")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(createRequest));
assertEquals(201, createResponse.getStatus());
UserResponse userResponse = createResponse.
readEntity(UserResponse.class);
Response getResponse = client.target(apiBaseUrl + "/
users/" + userResponse.getId())
.request(MediaType.APPLICATION_JSON)
.get();
assertEquals(200, getResponse.getStatus());
494
CHAPTER 12
TESTING WITH TESTCONTAINERS
UserResponse retrievedUser = getResponse.
readEntity(UserResponse.class);
assertEquals("Jane Doe", retrievedUser.getName());
}
}
Listing 12-6 shows using Testcontainers to manage a PostgreSQL
database and a custom Docker Compose environment. The test initializes
a PostgreSQL container and a Docker Compose setup defined in dockercompose-test.yml, exposing the application on port 8080. It then verifies
the creation and retrieval of a user via the application's REST API, ensuring
the system behaves as expected in a production-like environment. This
approach provides isolated, consistent, and automated testing, making it
ideal for enterprise applications with complex dependencies.
This expanded example shows how TestContainers can manage
multiple containers, handle configuration, and support end-to-end
testing of REST endpoints. It builds upon the simple wallet creation test by
showing a full workflow that mirrors real application usage.
Summary
This chapter provided a comprehensive exploration of testing in Jakarta
EE applications. We began with core testing theories and principles that
form the foundation of effective testing strategies. The discussion then
moved to practical implementations, showing how to create unit tests
by isolating components and mocking dependencies with JUnit and
Mockito. The chapter concluded with an examination of integration testing
using TestContainers, demonstrating how to create containerized testing
environments.
495
CHAPTER 12
TESTING WITH TESTCONTAINERS
Key Takeaways
1. Testing strategies should align with application
domain requirements.
2. Constructor injection simplifies unit testing of
Jakarta EE components.
3. Mockito enables effective isolation of components
for unit testing.
4. TestContainers provides a practical solution for
integration testing.
5. A combination of unit and integration tests offers
comprehensive test coverage.
6. Domain-specific analysis helps determine the
optimal mix of test types.
7. Container-based testing environments ensure
consistency between test and production
environments.
With a solid testing foundation in place, let's explore how to deploy
Jakarta EE applications in modern cloud environments using Kubernetes
and other cloud-native technologies.
496
CHAPTER 13
Jakarta EE Cloud­
Native Deployment
and Operations
This chapter explores deploying and operating Jakarta EE applications in
modern cloud-native environments, with a particular focus on Kubernetes.
While Jakarta EE has traditionally been deployed in application server
environments, the shift to cloud computing and containerization has
introduced new patterns, paradigms, and considerations for deploying
enterprise Java applications.
By the end of this chapter, you will
•
Understand cloud-native deployment patterns for
Jakarta EE applications, including containerization,
immutable infrastructure, and distributed architecture.
•
Use Kubernetes resources for Jakarta EE workloads,
including Services, StatefulSets, ConfigMaps, and
Ingress controllers.
•
Apply scaling and high availability strategies, including
session management, cache synchronization, and pod
disruption budgets.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_13
497
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
•
Work with deployment strategies including rolling
updates, blue-green deployments, and canary releases.
•
Set up monitoring, logging, and debugging practices for
containerized Jakarta EE applications.
•
Plan backup, recovery, and maintenance procedures
for cloud-native Jakarta EE deployments.
•
Learn how Jakarta EE application servers have adapted
to containerized environments.
The chapter begins with core concepts of cloud-native architectures
and how they apply to Jakarta EE applications. We then explore
containerization strategies tailored for enterprise Java workloads,
including optimizing container images, managing dependencies, and
configuring application servers.
Next, we dive into Kubernetes-specific deployment patterns, covering
topics like StatefulSets, service discovery, configuration management,
and persistent storage. The chapter also addresses scaling strategies,
including both horizontal and vertical scaling approaches, along with state
management considerations unique to Jakarta EE applications.
Finally, we examine operational aspects like monitoring, logging,
troubleshooting, and maintenance in distributed cloud environments.
Throughout the chapter, practical examples demonstrate how to apply
these concepts using common tools and technologies in the cloud-native
ecosystem.
Cloud-Native Architecture for Jakarta EE
The shift toward cloud-native architectures represents a significant
evolution in how we deploy and manage Jakarta EE applications. While
the core principles of Jakarta EE remain unchanged, the surrounding
infrastructure and operational patterns have transformed to meet modern
deployment needs.
498
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Core Concepts
Traditional Jakarta EE deployments centered around application servers
in relatively static environments. Cloud-native architectures introduce
new paradigms that fundamentally change how we package, deploy, and
operate these applications.
Containerization
When moving Jakarta EE applications to cloud platforms, containers
become the fundamental deployment unit. Instead of deploying WAR or
EAR files into a pre-installed application server, cloud-native Jakarta EE
applications package both the application and its runtime environment
into containers. Popular containerization technologies like Docker
or Podman are commonly used to build these container images. This
approach provides consistency across environments and eliminates the
"works on my machine" problem.
Container image optimization plays a key role in deployment
efficiency. By using multi-stage builds, the final image contains only the
components needed for production. Careful structuring of image layers
ensures that rebuilds remain efficient, touching only the layers that have
changed. Resource limits and health checks built into the container
definition help maintain application reliability in production.
Immutable Infrastructure
Cloud-native practices introduce the concept of immutable infrastructure,
marking a significant departure from traditional update patterns. Rather
than modifying running containers, teams deploy entirely new containers
with updated versions of the application. This immutable approach
improves reliability and reproducibility.
499
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
For Jakarta EE applications, immutability requires careful
consideration of several factors. Configuration moves outside the
container using mechanisms like environment variables or configuration
services. State management becomes more critical as containers may be
replaced at any time. Applications need proper startup and shutdown
procedures to handle replacement gracefully without disrupting service.
Distributed Architecture
Cloud deployments inherently distribute Jakarta EE applications across
multiple instances. This distribution introduces several technical
challenges that applications must address. Session management across
instances requires careful design, especially for applications that rely
on session state. Cache consistency becomes important when multiple
application instances share data. Distributed transactions need proper
handling to maintain data integrity across service boundaries.
Additionally, service discovery and load balancing mechanisms
become essential components of the architecture. Applications must
integrate with platform-provided services while maintaining the reliability
expected of enterprise systems.
Application Server Evolution
The move to cloud-native deployment has sparked evolution in Jakarta
EE application servers. Major implementations now offer distributions
specifically optimized for container environments.
Cloud-Optimized Distributions
Application server vendors have responded to cloud requirements with
specialized distributions. Open Liberty, WildFly, Payara Micro, and
TomEE all provide versions designed for containerized deployment. These
distributions start faster, use less memory, and include built-in features for
cloud environments like health checks and metrics endpoints.
500
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Modern Configuration Approaches
Configuration management has adapted to meet cloud-native needs.
Application servers now support sourcing configuration from environment
variables (Chapter 7—Jakarta EE config), handling secrets through secure
mechanisms, and updating settings dynamically. They expose health
(Chapter 10—health checks) and metrics endpoints that integrate with
container orchestration platforms and monitoring systems.
These cloud-optimized servers maintain compatibility with Jakarta
EE specifications while adding features that support modern deployment
patterns. Their evolution demonstrates how the Jakarta EE ecosystem
continues to adapt to changing infrastructure requirements.
The transformation of architecture and deployment patterns requires
a shift in how we approach Jakarta EE application development and
operations. In the following sections, we'll explore specific deployment
strategies and operational practices that help realize the benefits of cloud­
native architecture while maintaining enterprise-grade reliability.
While understanding cloud-native principles provides the foundation
for modern Jakarta EE deployments, putting these concepts into practice
requires specific platform knowledge. Kubernetes has emerged as the
primary platform for orchestrating containerized applications, including
Jakarta EE workloads. Let's explore how to effectively deploy and manage
Jakarta EE applications in Kubernetes environments.
Kubernetes Deployment Patterns
Kubernetes (abbreviated to K8s) offers several deployment options
for Jakarta EE applications, each suited to different requirements and
constraints. Choosing the right deployment pattern impacts application
reliability, scalability, and maintainability.
501
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Deployment Types
The default Kubernetes Deployment resource works well for stateless
Jakarta EE applications. It manages the rollout of new versions and handles
pod scheduling across the cluster. However, Jakarta EE applications
often maintain session state or require ordered startup and shutdown
procedures. In these cases, StatefulSets provide better control over pod
identity and lifecycle.
When using StatefulSets, each pod receives a predictable hostname
and maintains its identity across restarts. This stability helps manage
distributed caching, session replication, and database connections. For
example, a Jakarta EE application using Infinispan for distributed caching
can reliably form cache clusters using the predictable pod names.
Kubernetes StatefulSets are particularly useful for Jakarta EE
applications that require stable network identities, persistent storage, and
ordered scaling. These features are essential for managing session state,
coordinating distributed systems, and ensuring data consistency.
502
•
Stable Network Identity: Each pod in a StatefulSet
maintains a unique and persistent hostname, even
across rescheduling and restarts. This allows for
reliable communication and coordination between
pods, which is crucial for applications that rely on
session replication or distributed caching.
•
Persistent Storage: StatefulSets can be configured to
use persistent volumes, ensuring that data is preserved
across pod failures and restarts. This is essential for
applications that store session data or other stateful
information.
•
Ordered Scaling: StatefulSets provide guarantees
about the order in which pods are created, scaled,
and terminated. This allows for graceful startup
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
and shutdown procedures, which are important for
applications that require coordination between pods or
that need to perform cleanup tasks before termination.
Service Discovery and Load Balancing
Jakarta EE applications typically expose multiple endpoints, including
HTTP interfaces, management ports, and potentially JMX or debug ports.
Kubernetes Services provide a powerful abstraction for these endpoints,
enabling stable networking and service discovery within the cluster.
For web applications, the standard pattern involves using a ClusterIP
Service for internal communication and an Ingress resource for
external access:
•
ClusterIP Service: Assigns a stable internal IP address
to a group of pods, enabling seamless communication
between microservices within the cluster. This internal
IP remains consistent even if pods are rescheduled
or replaced, providing a reliable way for services to
interact without exposing them to the outside world.
•
Ingress Resource: Acts as a reverse proxy or "gateway"
for external access to services within the cluster. It
routes incoming traffic to the appropriate service based
on rules defined in the Ingress configuration, such as
hostnames, paths, and ports.
Consider this typical configuration for a Jakarta EE web application
shown in Listing 13-1.
503
CHAPTER 13
Note
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
The following YAML examples illustrate Kubernetes resource
definitions. These configuration files are typically applied to a
Kubernetes cluster using command-line tools like kubectl apply -f
<filename>.yaml. The specific placement and overall environment
setup depend heavily on your Kubernetes distribution and cluster
configuration. For comprehensive details on managing Kubernetes
resources, cluster setup, and command-line usage, please refer to
the official Kubernetes documentation.
Listing 13-1. A sample K8s service definition
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
ports:
- name: http
port: 8080
- name: management
port: 9990
This service definition, named myapp-service, targets pods with
the label app: myapp. It exposes two ports: http on port 8080 for the
main application traffic and management on port 9990 for accessing the
application server's management interface.
To route external traffic to this service, you'd typically use an Ingress
resource like the one defined in Listing 13-2.
504
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Listing 13-2. Ingress resource definition
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp-ingress
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp-service
port:
name: http
This Ingress definition routes traffic for myapp.example.com to
the myapp-service on the http port (8080). This configuration ensures
that external requests reach your Jakarta EE application running on the
specified port.
While service and ingress configurations establish basic networking,
Jakarta EE applications often require more extensive configuration beyond
network endpoints. Kubernetes offers robust configuration management
features to address these needs, which we'll explore next.
505
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Configuration Management
Traditional Jakarta EE applications often scatter configuration across
various locations, including server configuration files, deployment
descriptors, and application properties. Kubernetes simplifies
configuration management by centralizing these settings in ConfigMaps
and Secrets.
ConfigMaps for Application Settings
A ConfigMap is a Kubernetes object that stores configuration data as key­
value pairs. This data can be made available to pods and other Kubernetes
objects, providing a centralized and manageable way to handle application
configuration.
For Jakarta EE applications, ConfigMaps typically hold settings that are
not sensitive, such as
•
server.xml files for Open Liberty
•
standalone.xml for WildFly
•
domain.xml for Payara (and GlassFish)
•
microprofile-config.properties for MicroProfile
applications
Organizing configuration into separate ConfigMaps based on their
function (e.g., one for server settings, one for application properties)
improves clarity and maintainability.
An example ConfigMap defining the server.xml entries is shown in
Listing 13-3.
506
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Listing 13-3. Sample server.xml ConfigMap definition
apiVersion: v1
kind: ConfigMap
metadata:
name: server-config
data:
server.xml: |
<server>
<featureManager>
<feature>jakartaee-11</feature>
</featureManager>
< !-- Additional server configuration -->
</server>
This ConfigMap, named server-config, stores the content of a server.
xml file in the data section. This configuration can then be mounted as a
volume or exposed as environment variables to your Jakarta EE application
pods, allowing you to manage server settings independently of the
application deployment.
Secrets for Sensitive Data
While ConfigMaps handle general configuration, sensitive information
requires special treatment. Kubernetes Secrets are a secure object that
stores sensitive data like passwords, tokens, and certificates. This prevents
the exposure of such confidential information directly within application
code or configuration files.
Kubernetes Secrets can be mounted as volumes within a pod. This
allows the application server running inside the pod to access the secret
data. The application server then makes this data available to the Jakarta
EE application using standard mechanisms such as JNDI and MicroProfile
507
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Config. Through Kubernetes Secrets, Jakarta EE applications can securely
retrieve and use sensitive information without directly exposing the data
within the application code.
Persistent Storage
Configuration management addresses application settings, but Jakarta EE
applications often need persistent storage for data, logs, and other state
information. Kubernetes provides several storage options through its
persistent volume system.
Volume Types
The choice of volume type depends on both application requirements
and infrastructure capabilities. Cloud providers offer their native storage
services, while on-premises deployments might use Network File
System (NFS) or other storage systems. The key is selecting a storage
type that provides the performance and reliability characteristics your
application needs.
For Jakarta EE applications, common storage needs include
•
Transaction logs
•
File-based artifacts
•
Uploaded content
•
Backup data
Kubernetes offers a reliable system for managing persistent storage
through persistent volumes (PVs) and Persistent Volume Claims (PVCs).
508
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Persistent Volumes (PVs)
A persistent volume (PV) represents a piece of storage in the cluster,
provisioned by an administrator. This can be a network-attached storage
(NAS) like Network File System (NFS), cloud-provided storage, or local
storage. The choice of PV type depends on your application needs and
infrastructure capabilities.
Persistent Volume Claims (PVCs)
A Persistent Volume Claim (PVC) is a request for storage by an application.
It acts as an abstraction layer, allowing applications to request storage
resources without needing to know the underlying details of the PV. Listing
13-4 shows a sample Persistent Volume Claim definition.
Listing 13-4. PVC definition
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: app-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
In this example, the PVC named app-data requests 10 gigabytes of
storage with ReadWriteOnce access mode, which means the volume can
be mounted by only one node at a time. Kubernetes will automatically
find a suitable PV that matches the PVC's requirements and bind it
to the PVC. This separation between PVCs and PVs simplifies storage
management and improves application portability
509
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
While proper storage configuration ensures data durability, enterprise
applications must also handle varying workloads and maintain high
availability. The dynamic nature of cloud environments makes scaling and
resilience particularly important for Jakarta EE applications. Let's examine
how to implement these capabilities in Kubernetes.
Scaling and High Availability
Jakarta EE applications have traditionally scaled through cluster
configurations in application servers. Kubernetes provides a different
approach to scaling, offering automated scaling capabilities that
complement existing Jakarta EE clustering features.
Horizontal Pod Autoscaling
Kubernetes can automatically adjust the number of application instances
based on metrics like CPU utilization or custom metrics. For Jakarta EE
applications, this requires careful consideration of session handling and
cache consistency. The following sections offer general suggestions on
how to effectively implement scaling in Kubernetes.
Session Management
When scaling Jakarta EE applications horizontally, maintaining user
sessions across multiple pods requires careful consideration. Here are the
primary strategies to manage user sessions effectively when scaling Jakarta
EE applications horizontally across multiple pods.
510
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Sticky Sessions with Session Replication
In this approach, a load balancer consistently routes a user's requests to
the same pod throughout their session. This ensures that the pod handling
the request has access to the necessary session data. To mitigate the risk
of data loss if a pod becomes unavailable, session replication techniques
can be employed to copy session data across multiple pods. While this
approach offers good performance, it can limit scaling flexibility.
Centralized Session Storage
This strategy involves storing session data in a centralized data store, such
as a Redis cache or a database. Any pod can access and modify session
data from this central location, providing greater scaling freedom. Jakarta
EE applications can use technologies like JCache (JSR 107) to interact with
these centralized caches. This approach offers improved scaling flexibility
and reliability but may introduce additional infrastructure complexity and
potential performance overhead.
Session-Less Architectures
Session-less architectures eliminate the need for server-side session
storage altogether. Instead, the user's state is encoded into JSON Web
Tokens (JWTs), which are signed and passed with each request. This allows
any pod to verify the user's identity and access rights without relying
on server-side sessions. This approach offers excellent scalability and
resilience but may increase complexity in managing and securing JWTs.
The choice of session management strategy depends on factors
such as application requirements, scaling needs, and infrastructure
considerations. Each approach offers a unique set of trade-offs between
complexity, performance, and reliability.
511
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Cache Synchronization
Caching is a crucial technique for improving performance in enterprise
Java applications. However, when these applications are deployed in a
scaled environment with multiple instances, ensuring cache consistency
across those instances becomes essential. Jakarta EE offers several
approaches to address this challenge.
Distributed Caching Solutions
Distributed caching solutions like Infinispan and Hazelcast provide a
clustered approach to caching, where data is distributed across multiple
nodes. These solutions offer features like data replication, automatic
failover, and sophisticated cache management capabilities, ensuring high
availability and data consistency. They are particularly well-suited for
applications requiring strong consistency and fault tolerance.
Cache Invalidation Messaging
This approach relies on asynchronous messaging systems to propagate
cache invalidation events across application instances. When data is
updated in one instance's cache, an invalidation message is sent to other
instances, prompting them to remove or update the corresponding entries
in their caches. This approach offers good flexibility and scalability but
requires careful management of messaging infrastructure and potential
handling of eventual consistency scenarios.
Read-Through Caching with Shared Backing Stores
In this strategy, a shared backing store, such as a database or a centralized
cache, serves as the source of truth. Application instances use a readthrough cache, where data is fetched from the backing store if not found in
512
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
the local cache. This approach simplifies cache management and ensures
consistency but may introduce performance overhead due to increased
reads from the backing store.
The choice of cache synchronization mechanism depends on various
factors, including consistency requirements, network overhead tolerance,
operational complexity, and the specific needs of the application.
High Availability Configuration
While scaling contributes significantly to application availability,
Kubernetes provides additional features to ensure consistent uptime,
especially when combined with Jakarta EE reliability mechanisms.
Pod Disruption Budgets (PDBs)
During cluster maintenance or scaling events, it's crucial to prevent
disruptions that might render your application unavailable. PDBs allow
you to specify the minimum number of pod instances that must remain
available at any given time. This ensures that your application can
continue serving requests even when some pods are being terminated or
rescheduled. Listing 13-5 shows a sample PDB definition.
Listing 13-5. Sample pod disruption budget definition
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: myapp-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: myapp
513
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
This PDB, named myapp-pdb, ensures that at least two pods with the
label app: myapp are available at all times. This prevents disruptions that
might occur if, for example, a node undergoes maintenance or a rolling
update is performed.
Readiness and Liveness Probes
Jakarta EE applications often have complex startup sequences
involving dependency injection, resource initialization, and connection
establishment. Kubernetes probes help ensure that your application is not
only running but also ready to serve requests. They also detect unhealthy
instances that may need to be restarted.
•
Liveness probes check if the application is running
correctly. If a liveness probe fails, Kubernetes restarts
the container.
•
Readiness probes check if the application is ready to
serve traffic. If a readiness probe fails, Kubernetes stops
sending traffic to the pod until the probe succeeds.
Listing 13-6 shows a sample health check Kubernetes definition.
Listing 13-6. Sample health check definition
spec:
containers:
- name: myapp
livenessProbe:
httpGet:
path: /health
port: 9990
initialDelaySeconds: 20
readinessProbe:
514
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
httpGet:
path: /health/ready
port: 9990
In this configuration
•
The livenessProbe performs an HTTP GET
request to the /health endpoint on port 9990. It
waits for 20 seconds before starting the checks
(initialDelaySeconds). This allows the application
sufficient time to start up.
•
The readinessProbe also performs an HTTP GET
request, but to the /health/ready endpoint on port
9990. This endpoint should return a success status only
when the application is fully initialized and ready to
handle requests.
These probes ensure that Kubernetes only directs traffic to healthy and
ready instances of your Jakarta EE application, maximizing uptime and
reliability.
While proper scaling and high availability configurations ensure
application reliability, operating these distributed systems requires
comprehensive visibility into their behavior. Modern cloud platforms
demand a different approach to monitoring and observability than
traditional Jakarta EE deployments. Let's explore how to implement
effective monitoring strategies for cloud-native Jakarta EE applications.
Monitoring andObservability
Traditional server-based monitoring approaches fall short in containerized
environments. To gain insights into application health and performance,
it's essential to expose internal state and behavior through standardized
interfaces that integrate with cloud-native monitoring systems.
515
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Metrics Collection
Jakarta EE applications offer several mechanisms for exposing metrics.
MicroProfile Metrics aligns particularly well with Kubernetes monitoring
systems, providing a standardized way to instrument applications and
expose both application-specific and runtime metrics.
Application Metrics
Application metrics provide crucial insights into business-relevant
information. These can include
516
•
Transaction Throughput: The number of transactions
processed per unit of time, indicating application
performance and load
•
Response Times: The time taken to process requests,
helping identify performance bottlenecks and areas for
optimization
•
Business Process Completion Rates: The rate at which
key business processes are successfully completed,
reflecting overall application effectiveness
•
Error Rates by Type: Categorized error rates, aiding
in identifying specific issues and their impact on
application functionality
•
Custom Business Metrics: Metrics tailored to
specific business needs, providing insights into
key performance indicators (KPIs) and operational
efficiency
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Runtime Metrics
Understanding the runtime behavior of Jakarta EE applications requires
monitoring the application server itself. Modern application servers
expose a wealth of metrics, including
•
JVM Memory Usage: Heap and non-heap memory
consumption, helping identify potential memory leaks
or inefficient resource utilization
•
Thread Pool Utilization: Active and idle threads,
indicating thread pool health and potential bottlenecks
in request processing
•
Connection Pool Status: Active, idle, and total
connections, reflecting the efficiency of database
connections and potential resource contention
•
Garbage Collection Statistics: Frequency, duration,
and reclaimed memory, providing insights
into garbage collection efficiency and potential
performance impacts
•
Request Processing Times: Time spent processing
individual requests, helping pinpoint performance
bottlenecks within the application server
These metrics seamlessly integrate with Kubernetes monitoring
systems through the Prometheus format, which has emerged as the
standard for cloud-native monitoring.
517
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Distributed Tracing
In cloud environments, transactions often span multiple services, making
it critical to understand the flow of requests and identify potential
bottlenecks or issues across service boundaries. Jakarta EE applications
can use MicroProfile Telemetry (Chapter 9) to implement distributed
tracing.
Distributed tracing provides valuable insights into
•
Cross-Service Request Flows: Visualizing how
requests traverse different services, helping identify
dependencies and potential points of failure
•
Latency Between Components: Measuring the time
spent in each service or component, pinpointing
performance bottlenecks and areas for optimization
•
Error Propagation: Tracking errors across service
boundaries, facilitating root cause analysis and faster
resolution of issues
•
Service Dependencies: Mapping the relationships
between services, aiding in understanding the impact
of changes or failures on the overall system
Combining comprehensive metrics collection with distributed tracing,
you gain deep visibility into the behavior and performance of your Jakarta
EE applications in Kubernetes, enabling proactive monitoring, efficient
troubleshooting, and optimized performance.
Metrics and tracing offer valuable insights into application behavior,
but effective troubleshooting often necessitates detailed logging
information. However, log management in cloud-native environments
presents unique challenges compared with traditional Jakarta EE
deployments. Let's explore how to implement robust logging strategies for
containerized Jakarta EE applications.
518
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Logging andDebugging
Traditional Jakarta EE applications typically write logs to files on the
server's filesystem. However, containers are ephemeral, meaning their
local storage vanishes when they stop. This necessitates a different
approach to logging and debugging in a containerized environment.
Log Management
Cloud-native logging strategies treat logs as event streams rather than
static files. This shift affects both how applications generate logs and how
they are collected and analyzed.
Log Generation
Jakarta EE applications running in containers should output logs to stdout
(standard output) and stderr (standard error) instead of files. This aligns
with cloud-native principles and allows the container runtime to handle
log collection and aggregation. Most modern application servers support
this configuration natively.
Structured Logging
Beyond redirecting log output, structured logging enhances log processing
in cloud environments. Formatting logs in JSON makes them easily
parsable by log management tools, enabling efficient querying, filtering,
and analysis.
Remote Debugging
While remote debugging is rarely permitted in production due to
potential performance impacts, it remains essential for development and
staging environments. Kubernetes and container platforms offer various
approaches to troubleshoot Jakarta EE applications running in containers.
519
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Development-Time Debugging
During development, port forwarding allows developers to connect their
IDEs directly to running containers. Listing 13-7 shows a Kubernetes CLI
command for port forwarding.
Listing 13-7. Kubectl port forwarding command
kubectl port-forward pod/myapp-pod 5005:5005
This command forwards local port 5005 to port 5005 of the myapp-pod
pod. This enables the use of familiar IDE debugging tools. However, be
sure the application is started with debugging enabled.
Production Troubleshooting
Production environments require debugging approaches that don't
impact application performance. Thread dumps and heap dumps provide
snapshots of application behavior without requiring a direct debugging
connection. These dumps can be analyzed offline to diagnose issues and
identify root causes.
Deployment Strategies
With monitoring, logging, and debugging capabilities in place, let's
examine how to safely deploy updates to running applications. Kubernetes
supports several deployment strategies that minimize disruption while
updating Jakarta EE applications.
520
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Rolling Updates
Rolling updates gradually replace old pods with new ones, ensuring
continuous service availability. This strategy works well for Jakarta EE
applications that handle graceful shutdown properly. Listing 13-8 shows a
snippet of a rolling update definition in Kubernetes.
Listing 13-8. Rolling update definition
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
This configuration specifies a rolling update strategy where maxSurge
allows for one additional pod during the update and maxUnavailable
ensures that no pods are unavailable during the update process. This
guarantees a smooth transition with no downtime.
Blue-Green Deployments
For more critical applications, blue-green deployments provide additional
safety by maintaining two complete environments. This strategy
particularly suits Jakarta EE applications with complex state management
or database migration requirements.
For critical applications, blue-green deployments offer increased
safety by maintaining two complete environments: a "blue" environment
(live) and a "green" environment (new). Traffic is switched from blue to
green once the green environment is validated. This strategy is particularly
suitable for Jakarta EE applications with complex state management or
database migration requirements. It minimizes risk and allows for quick
rollback if issues arise.
521
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Canary Releases
While blue-green deployments offer safety by duplicating the entire
environment, canary releases provide a more granular approach to rolling out
changes. This strategy is particularly well-suited for Jakarta EE applications
with diverse user populations or complex feature sets where it's beneficial to
test new features with a small subset of users before a full rollout.
In a canary deployment, a small portion of traffic is routed to the new
version of the application, while the majority of users continue accessing
the current version. This allows for real-world testing and feedback
gathering before widespread deployment. For Jakarta EE applications,
implementing canary releases often requires coordination between the
application server, load balancer, and Kubernetes ingress.
Listing 13-9 shows a sample canary-style deployment definition.
Listing 13-9. Canary Kubernetes definition
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/canary: "true"
nginx.ingress.kubernetes.io/canary-weight: "20"
This configuration enables canary deployments for the Ingress
resource. The nginx.ingress.kubernetes.io/canary-weight annotation
specifies that 20% of the traffic should be directed to the canary version,
while the remaining 80% goes to the stable version.
522
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Maintenance andOperations
Successful deployment strategies enable application updates, but long­
term success requires effective maintenance practices. Let's explore key
operational considerations for Jakarta EE applications running in Kubernetes.
Health Management
Regular health checks are crucial to prevent service degradation and
enable automated recovery. Jakarta EE applications should implement
comprehensive health checks using MicroProfile Health or similar
mechanisms. These health checks should cover various aspects of the
application, including database connectivity, resource availability, and
critical dependencies.
Backup andRecovery
Cloud-native deployments require rethinking traditional backup strategies.
For Jakarta EE applications, a comprehensive backup strategy addresses
both data and configuration state.
Data Protection
Database backups remain critical in containerized environments.
However, the approach differs based on database deployment. Listing
13-10 shows a sample cron job Kubernetes definition.
Listing 13-10. Cron job definition
apiVersion: batch/v1
kind: CronJob
metadata:
name: database-backup
523
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
spec:
schedule: "0 2 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: backup-utility
volumeMounts:
- name: backup-storage
mountPath: /backups
This CronJob definition schedules a daily backup job at 2:00 a.m. The
job uses a container with a backup-utility image and mounts a persistent
volume named backup-storage to store the backups.
Disaster Recovery
Disaster recovery planning for cloud-native applications requires
a different approach than traditional on-premises setups. The
distributed nature of cloud deployments introduces new challenges and
considerations. Here's a breakdown of some key aspects.
Regular Testing of Restore Procedures
Regularly testing your restore procedures is paramount to ensure that
your backups are valid and your recovery processes function as expected.
These tests should simulate various disaster scenarios and verify that you
can recover your application and its data within the defined recovery time
objectives (RTOs). For example, you might simulate a database failure and
test restoring from a backup or simulate an entire region failure and test
your ability to failover to a different region.
524
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Documentation of Recovery Processes
Thorough documentation of your recovery processes is essential to guide
recovery efforts in case of a disaster. This documentation should include
step-by-step instructions for restoring data, configuring applications, and
bringing services back online. It should also include contact information
for key personnel and escalation procedures. This ensures that even if key
personnel are unavailable, others can follow the documented procedures
to recover the system.
Automated Recovery Scripts
Automating your recovery processes through scripts can significantly
streamline and expedite recovery efforts. These scripts can automate
tasks such as provisioning infrastructure, restoring data from backups,
configuring network settings, and deploying applications. Automation
reduces the risk of human error and ensures consistent and repeatable
recovery procedures.
Recovery Time Objective (RTO) Monitoring
Recovery time objectives (RTOs) define the maximum acceptable
downtime for your application in case of a disaster. Monitoring your
RTOs helps ensure that your recovery processes meet your business
requirements. This involves tracking the time it takes to recover from
different failure scenarios and identifying areas for improvement.
Regularly reviewing and updating your RTOs ensures they remain aligned
with your business needs and risk tolerance.
525
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
Summary
Deploying Jakarta EE applications in cloud-native environments requires
a shift from traditional practices. This chapter explored core concepts like
containerization, immutability, and distributed architectures, emphasizing
the evolution of application servers and the importance of Kubernetes
patterns. We learned about containerizing Jakarta EE workloads,
configuring applications in Kubernetes, managing persistent storage, and
implementing scaling strategies. We also examined operational aspects
like monitoring, logging, debugging, and implementing high availability.
Key Takeaways
1. Containerization: Optimize Jakarta EE applications
for container environments using techniques like
multi-stage builds and resource limits.
2. Kubernetes Deployment: Leverage Kubernetes
features like StatefulSets, service discovery,
configuration management, and persistent storage
for Jakarta EE applications.
3. Configuration Management: Utilize ConfigMaps
and Secrets for managing application settings and
sensitive data securely.
4. Scaling and Resilience: Implement horizontal
scaling strategies, considering session management
and cache consistency. Utilize PDBs and probes for
high availability.
526
CHAPTER 13
JAKARTA EE CLOUD-NATIVE DEPLOYMENT AND OPERATIONS
5. Monitoring and Logging: Integrate Jakarta EE
applications with cloud-native monitoring
systems using MicroProfile Metrics and Telemetry.
Implement structured logging for efficient log
management.
6. Deployment Strategies: Employ rolling updates,
blue-green deployments, or canary releases for safe
and efficient updates to Jakarta EE applications.
These takeaways highlight the key considerations and best practices
for deploying and managing Jakarta EE applications in modern cloud­
native environments. With the operational aspects of cloud-native
deployments covered, let's shift our focus to architectural considerations.
The next chapter dives into architectural patterns for Jakarta EE
applications, exploring monoliths, moduliths, and microservices.
527
CHAPTER 14
Monoliths, Moduliths,
and Microservices
with Jakarta EE:
Architectural Patterns
Enterprise applications come in various shapes and sizes, each with
unique requirements and constraints. Some need to handle massive user
loads, others prioritize rapid development, while others require strict
isolation between components. These diverse needs have given rise to
different architectural patterns in enterprise applications.
This chapter explores three main architectural patterns that can be
implemented using Jakarta EE: monolithic, modulithic, and microservices
architectures. Each pattern offers distinct advantages and challenges,
and choosing the right one depends on various factors including team
size, application complexity, scalability requirements, and development
constraints.
Jakarta EE, with its comprehensive set of specifications and APIs,
provides great support for implementing all three patterns. Whether
you’re building a simple monolithic application, a modular system with
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_14
529
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
clear boundaries, or a distributed microservices architecture, Jakarta
EE offers the constructs needed to implement your chosen pattern
effectively.
By the end this chapter, you will be able to
•
Compare and contrast monolithic, modulithic, and
microservices architectural patterns.
•
Implement each architectural pattern using Jakarta EE
technologies.
•
Evaluate the advantages and disadvantages of each
pattern.
•
Select the most appropriate architecture for your
specific use case.
•
Apply effective strategies for evolving between different
architectural patterns.
Architectural Patterns in Jakarta EE
Software architecture in the enterprise world has undergone a remarkable
transformation over the years, driven by the ever-changing demands of
businesses, advancements in technology, and valuable lessons learned from
developing and deploying real-world applications. Jakarta EE, as a robust
platform for enterprise Java development, has kept pace with these shifts,
offering comprehensive support for a variety of architectural patterns.
Evolution of Enterprise Architecture Patterns
Enterprise architecture has progressed significantly from its early days of
monolithic applications, where all components were tightly interwoven
within a single deployable unit. This approach, while suitable for smaller
530
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
applications, revealed its limitations as applications grew in size and
complexity, leading to challenges in maintainability, scalability, and
development velocity.
To address these challenges, the industry saw the rise of the modulithic
pattern. This approach strikes a balance between the deployment
simplicity of monoliths and the need for clearer separation of concerns.
By introducing well-defined modules within a monolithic structure,
modulithic architecture allows teams to manage complexity effectively
while avoiding the operational overhead associated with distributed
systems.
Further evolution led to the emergence of microservices, an
architectural pattern designed to meet the demands of large-scale,
distributed systems. Microservices decompose applications into small,
independent services, each focused on a specific business capability. This
approach promotes agility, scalability, and independent deployments,
but also introduces complexities in inter-service communication, data
consistency, and operational management.
Jakarta EE's Role in Supporting
Different Architectures
Jakarta EE offers a modular approach to cater to various architectural
patterns and application needs through its defined profiles. These
profiles provide curated sets of specifications, allowing developers to
choose the functionalities required for their specific use cases. This
approach streamlines development, reduces footprint, and optimizes
resource usage.
Table 14-1 shows how Jakarta EE caters to diverse architectural needs.
531
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-1. Jakarta EE Profiles
Profile
Description
Key Specifications
Suitable for
Core
Foundation for
CDI, JSON-P, JSON-B,
Microservices,
Profile
lightweight server-side
Interceptors, RESTful Web
resource-
applications
Services
constrained
applications
Web
Extends the Core Profile All Core Profile specs plus
Profile
with web-specific
Servlets, JSF, JSP, JPA,
functionalities
Expression Language,
Web applications,
REST APIs
Security, Validation,
WebSockets, Transactions
Full
The most
All Core and Web Profile
Complex, large-
Platform
comprehensive profile,
specs plus Enterprise
scale enterprise
Profile
including all Core and
Beans, Messaging,
applications
Web Profile features
Transactions (full)
plus enterprise
capabilities
This table provides a quick reference for understanding the different
Jakarta EE profiles and their suitability for various application types.
You can use this information to guide your technology choices when
architecting your next Jakarta EE project.
Common Architectural Considerations
When selecting an architectural pattern for your Jakarta EE application, it’s
important to consider several key factors. Table 14-2 shows some of these
factors for the different architectural patterns.
532
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-2. Common Architectural Considerations
Modulithic
Consideration
Monolithic
Scalability
Replicate the entire Scale at the module
Fine-grained scaling
application
level
of individual services
Simple for small
Manageable
Distributed complexity
applications,
complexity through
across smaller
complex for large
clear boundaries
services
Maintainability
Microservices
ones
Development
Rapid in early
Balanced speed and
Enables parallel
velocity
stages
maintainability
development but
requires initial setup
Team structure
Centralized teams
Multiple teams with
Autonomous, cross­
clear responsibilities functional teams
Deployment
Simple deployment, Simple deployment,
complexity
full application
partial updates
deployments, requires
updates
possible
orchestration
Independent
Understanding these considerations will guide you in choosing the
most appropriate architectural pattern for your specific needs and context.
In the subsequent sections, we will dig deeper into each pattern, exploring
their implementation details and best practices within the Jakarta EE
ecosystem.
Monolithic Architecture
Now that we understand the evolution of architectural patterns and Jakarta
EE’s role in supporting them, let’s examine each pattern in detail, starting
with the most traditional approach: the monolithic architecture.
533
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
A monolithic architecture represents the traditional approach to
building enterprise applications, where all components are packaged and
deployed as a single unit. In Jakarta EE applications, this typically means
packaging all components into a single WAR or EAR file. While often
viewed as outdated in today’s cloud-native world, monolithic architectures
remain a valid and often advantageous choice for many enterprise
applications.
Structure andCharacteristics
In a monolithic Jakarta EE application, all functional components reside
within a single deployable unit. This means the web layer responsible
for handling user interfaces, the service layer containing business logic,
and the data access layer managing persistence are all packaged together.
These components share the same memory space and resources, enabling
them to communicate through direct method calls, eliminating the
overhead of network communication.
While this inherent simplicity can be advantageous, especially for
smaller applications, it’s important to understand the underlying structure
and how Jakarta EE supports this architectural style.
Typical Structure of a Monolithic Jakarta
EE Application
A typical monolithic Jakarta EE application follows a layered architecture,
often consisting of the following.
Web Layer
This layer is the user’s entry point into the application. It handles user
interaction and presentation logic by receiving HTTP requests, processing
them, and generating responses. Jakarta EE provides robust support for
this layer through key technologies:
534
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
•
Jakarta Servlets: These provide the foundation for
handling HTTP requests and responses. They manage
sessions and control the application’s flow, ensuring a
smooth user experience.
•
Jakarta Server Faces (JSF): This offers a component­
based framework to build user interfaces. With server­
side state management and event handling, JSF allows
for dynamic and interactive web pages.
Service Layer
This layer is the heart of the application, encapsulating its core business
logic. It defines the rules and processes that govern how the application
functions and interacts with data. The service layer often relies on
•
CDI Beans: These manage the lifecycle and
dependencies of application components. By promoting
modularity and reusability, CDI beans contribute to
a more maintainable and scalable application. This
specification is covered in Chapter 4 of this book.
Data Access Layer
This layer acts as a bridge between the application and its data sources,
such as databases. It abstracts the complexities of data persistence,
allowing the service layer to focus purely on business logic. Key
technologies in this layer include
•
Jakarta Persistence (JPA): This provides an objectrelational mapping (ORM) framework for managing
persistent data in relational databases. JPA simplifies
database interactions by allowing developers to
work with objects instead of raw SQL queries. This
specification is covered in detail in Chapter 6.
535
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Shared Utilities and Cross-Cutting Concerns
This layer houses components and functionalities used across the
application. Think of it as the supporting infrastructure that ensures
smooth operation and consistency. This includes
•
Jakarta Security: This provides a standard mechanism
for authentication, authorization, and secure
communication, safeguarding the application and
its data.
•
Jakarta Transactions: This ensures data consistency
and integrity by managing transactions across multiple
resources. It guarantees that operations are completed
reliably, preventing data corruption.
Advantages
Monolithic applications offer several advantages that make them a strong
choice in specific situations.
Development Simplicity
Monolithic applications are known for their straightforward development
process.
536
•
Unified Codebase: Teams work within a single
codebase, streamlining collaboration and code sharing.
•
Consistent Patterns: Maintaining consistency in design
and implementation is easier within a unified structure.
•
Ideal for Smaller Teams: The simplicity of a monolith
makes it manageable for smaller teams or projects with
limited resources.
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Consistent Data Management
Managing data within a monolith is often simpler due to the centralized
nature of the database.
•
Shared Database: All components access the same
database, simplifying data consistency and integrity
and allowing for higher levels of normalizations.
•
Simplified Transactions: Transactions can easily
span multiple operations without the complexities of
managing distributed transactions.
Performance
Monoliths can offer performance advantages, especially in applications
with intricate internal interactions.
•
Efficient Communication: Component interaction
happens through direct method calls, avoiding network
latency and the overhead of serialization. This leads to
faster processing and response times.
Testing andDebugging
Testing and debugging in a monolithic environment is generally more
straightforward.
•
Simplified Testing: End-to-end testing is easier because
all components reside within the same application.
•
Streamlined Debugging: Developers can debug
through the entire call stack without the challenges of
navigating a distributed system.
537
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Challenges
While monolithic architectures offer advantages, they also come with
challenges, especially as applications grow in size and complexity.
Codebase Complexity
One of the main challenges of monolithic applications is managing the
codebase as it expands.
•
Increased Complexity: As features are added, the
codebase naturally becomes larger and more intricate.
This can make it difficult for developers to understand
the entire system and navigate the codebase,
potentially leading to errors and unexpected behavior
when making changes.
•
Higher Risk of Side Effects: In a large, interconnected
codebase, even small modifications can have
unintended consequences in other parts of the
application.
Deployment Constraints
Deploying a monolithic application can become cumbersome as it grows.
538
•
Frequent Redeployments: Any change, regardless of
size, necessitates redeploying the entire application.
This can lead to extended deployment times, disrupting
availability and potentially impacting users.
•
Increased Risk: With each deployment, the entire
application is at risk. A small error in one component
can bring down the whole system.
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Scaling Limitations
Scaling a monolith can present challenges when different components
have varying resource requirements.
•
Inefficient Scaling: If one component requires more
resources (like memory or processing power), the
entire application must be scaled, even if other
components don’t need those extra resources. This can
lead to inefficient resource usage and increased costs.
Technology Constraints
Monolithic architectures can limit flexibility when it comes to adopting
new technologies.
•
Limited Technology Choices: All components within
a monolith must use the same technology stack and
runtime version. This can make it difficult to adopt new
technologies or upgrade existing ones without affecting
the entire application. This can hinder innovation
and make it challenging to keep up with evolving
technology trends.
When to Choose Monolithic Architecture
While newer architectural patterns have emerged, monolithic architecture
remains a valuable option in several situations.
539
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
New Applications
When starting a new project with evolving requirements, a monolithic
architecture can be a wise choice.
•
Flexibility for Changes: Monoliths offer the agility
to adapt to changing needs quickly, without the
added complexity of managing a distributed system.
This is particularly beneficial in the early stages of
development where requirements might be fluid.
Small to Medium Applications
For applications with a well-defined scope and a smaller development
team, a monolithic architecture often provides the right balance.
•
Simplicity and Functionality: Monoliths offer a
straightforward approach that can be easier to
understand and manage, especially for smaller
teams. This can lead to faster development and easier
maintenance.
Rapid Development
When time to market is a critical factor, a monolithic architecture can help
expedite the development process.
•
540
Focus on Business Value: Monoliths allow teams to
concentrate on delivering core business value without
getting bogged down in the complexities of service
orchestration and distributed systems. This can result
in a faster time to market.
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Limited Operational Resources
For organizations with limited DevOps resources, a monolithic
architecture can simplify deployment and maintenance.
•
Easier Deployment and Maintenance: Monoliths are
generally easier to deploy and maintain compared with
distributed systems, requiring less specialized expertise
and infrastructure. This can be a significant advantage
for organizations with limited operational resources.
While some may consider the monolithic approach “old-school,” it
continues to be a practical and efficient solution for many applications.
Its simplicity, speed, and operational benefits make it a viable choice,
especially when scalability and extreme flexibility are not primary
requirements.
Modulithic Architecture
While monolithic architectures offer clear benefits in simplicity and
efficiency, they can become challenging to maintain as applications
grow. Yet, not every application needs the full distributed complexity of
microservices. Modulithic architecture offers a middle ground.
A modulithic architecture maintains the deployment simplicity of
a monolith while introducing clear boundaries between components.
It addresses many of the scalability and maintainability challenges of
traditional monoliths without incurring the operational complexity of
microservices. For many Jakarta EE applications, this architectural pattern
offers an ideal balance.
541
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Structure andCharacteristics
A modulithic application divides functionality into distinct modules, each
focused on a specific business capability. Unlike microservices, these
modules share the same deployment unit but maintain clear boundaries
through well-defined interfaces and dependencies.
Each module in a modulithic application typically contains
•
Its own set of domain models
•
Dedicated business logic components
•
Internal implementation details hidden from
other modules
•
Clear interfaces for inter-module communication
•
Module-specific configuration and resources
Jakarta EE provides several features that support this modular approach:
•
CDI for dependency management and module
boundaries
•
Events for loose coupling between modules
•
Interceptors for cross-cutting concerns
•
Bean validation for module-specific constraints
•
Jakarta Security controls at module boundaries
Implementation with Jakarta EE
In a modulithic architecture, Jakarta EE helps enforce module boundaries
and manage interactions between modules. Each module acts as a self­
contained unit within the larger application, with its own internal structure
and clearly defined external interfaces.
The modular structure manifests in several ways.
542
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Module Organization
Each module represents a distinct business capability, such as order
management, policy management, customer relations, or inventory
control. These modules maintain their own internal implementations
while exposing only necessary interfaces to other modules.
Interface Boundaries
Modules communicate through well-defined interfaces rather than direct
implementation access. This encapsulation allows modules to evolve
independently as long as their interfaces remain stable.
Event-Based Communication
Jakarta CDI’s events enable loose coupling between modules. Rather than
direct method calls, modules can communicate through events, reducing
dependencies and improving maintainability.
Resource Management
While modules share the application’s resources, Jakarta EE allows for
module-specific configuration of data sources, security settings, and other
resources through MicroProfile Config when needed.
Advantages andDisadvantages
Modulithic architecture, while offering an appealing middle path,
comes with distinct trade-offs that teams must weigh carefully. A clear
understanding of these characteristics helps organizations assess
whether this pattern aligns with their development goals, team structure,
and operational capabilities. Let’s examine the key advantages and
disadvantages that shape the effectiveness of modulithic architecture in
practice.
543
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Advantages
Balanced Complexity
Modulithic architecture provides a middle ground between monolithic
simplicity and microservice flexibility. It helps manage complexity through
clear boundaries while avoiding distributed system challenges.
Evolutionary Development
Teams can evolve modules independently within the shared codebase.
This enables parallel development while maintaining deployment
simplicity.
Selective Refactoring
Individual modules can be refactored or updated without affecting the
entire application, as long as interface contracts are maintained.
Simplified Operations
Unlike microservices, modulithic applications deploy as a single
unit, simplifying operational concerns like monitoring, logging, and
deployment.
Reusability
Modules can be designed for reusability across different projects or parts
of the application, reducing code duplication and promoting consistency.
Testability
Well-defined module boundaries facilitate unit testing. Modules can be
tested independently, ensuring that individual components function
correctly before integration.
544
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Gradual Adoption
Teams can incrementally adopt a modulithic approach, starting with a
monolithic application and gradually extracting modules as needed. This
reduces the risk associated with a complete architectural overhaul.
Disadvantages
Boundary Enforcement
Maintaining strict module boundaries requires discipline and proper
architectural governance. Without careful attention, modules can become
tightly coupled over time.
Shared Resources
Modules still share the same runtime resources, which can lead to
resource contention or affect overall application performance and stability.
Deployment Coupling
While modules can be developed independently, they must still be
deployed together, which can slow down the release cycle for large
applications.
Limited Scalability (Compared with Microservices)
Modulithic applications may not scale as effectively as microservices,
especially for applications with highly independent components or varying
scaling requirements.
545
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
When to Choose Modulithic Architecture
Modulithic architecture is a good choice for different situations, like when
you have growing applications, independent teams working on projects,
or when you might want to use microservices in the future. Table 14-3
provides a summary of pointers to when the modulithic architecture is the
right choice.
Table 14-3. Pointers to When to Adopt the Modulithic Architecture
Benefits
Scenario
Growing applications
Early-stage companies
Simplicity, organized codebase
as the application scales,
manageable growth
Phased migration
Gradual transition to modularity,
improved maintainability
Team structure
Independent teams
Independent module development,
reduced code conflicts, improved
team autonomy
Domain-Driven Design
Clear separation of concerns,
improved communication between
developers and domain experts
(continued)
546
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-3. (continued)
Benefits
Scenario
Future migration
Microservices prep
Excellent stepping stone for
microservices migration,
establishes clear module
boundaries for future extraction
Hybrid approach
Allows for a mix of modules and
microservices, providing flexibility
in architectural choices
Resource constraints
Limited DevOps
Reduced DevOps overhead
compared with microservices,
simpler deployment and
management
Simplified infra
Can be deployed on simpler
infrastructure, reducing costs and
complexity
Faster development
Potentially faster development
compared with microservices,
avoids overhead of inter-service
communication and distributed
data management
547
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Microservices Architecture
While modulithic architecture addresses many challenges of traditional
monoliths, some applications require even greater flexibility, scalability,
and autonomy between components. For these cases, microservices
architecture presents the next evolutionary step.
Microservices take the modular approach further by completely
separating components into independent services, each running in its own
process and typically managing its own data. Jakarta EE, particularly when
combined with MicroProfile, provides comprehensive support for building
and managing microservices architectures.
This architectural pattern represents a significant departure from
both monolithic and modulithic approaches. Instead of maintaining
boundaries within a single application, microservices establish boundaries
between entirely separate applications, each focused on a specific business
capability.
Structure andCharacteristics
In a microservices architecture, each service operates as a fully
independent Jakarta EE application. These services possess several
defining characteristics as listed below.
Independent Deployment
Each service deploys independently, with its own runtime environment
and configuration. This independence allows teams to update services
without coordinating with other service teams.
548
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Service-Specific Data
Services typically maintain their own data stores, choosing the
most appropriate data technology for their specific needs. This data
independence helps prevent the tight coupling often seen in monolithic
applications.
REST-Based Communication
Services communicate primarily through REST APIs, with Jakarta EE’s
Jakarta REST specification providing support for both exposing and
consuming these interfaces.
Bounded Contexts
Each service encapsulates a specific business capability, with clear
boundaries that align with business domains rather than technical layers.
Implementation with Jakarta EE
Jakarta EE and MicroProfile provide a rich set of specifications and
tools that support microservices development. Table 14-4 demonstrates
how Jakarta EE and MicroProfile address fundamental microservices
architecture requirements.
549
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-4. How Jakarta EE and MicroProfile Address Fundamental
Microservices Architecture Requirements
Capability
Jakarta EE /
Description
MicroProfile Feature
REST APIs
Jakarta REST
Provides annotations for defining REST
endpoints (@Path, @GET, @POST, etc.),
handling HTTP requests and responses,
and mapping them to Java methods.
Service
MicroProfile REST
Simplifies communication between
communication
Client
services by generating client
implementations from Jakarta REST
interfaces. This promotes type safety and
reduces boilerplate code when interacting
with other RESTful services.
Configuration
MicroProfile Config
Enables externalized configuration
from various sources (property
files, environment variables, etc.),
allowing services to adapt to different
environments without code changes.
Fault tolerance
MicroProfile Fault
Provides mechanisms for handling
Tolerance
failures in distributed systems. Includes
annotations for timeouts (@Timeout),
retries (@Retry), circuit breakers
(@CircuitBreaker), and bulkheads
(@Bulkhead) to improve resilience and
prevent cascading failures.
(continued)
550
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-4. (continued)
Capability
Jakarta EE /
Description
MicroProfile Feature
Metrics
MicroProfile Telemetry Allows services to collect and expose
observability metrics about their
performance (request count, response
time, error rate, etc.). These metrics can
be consumed by monitoring tools for
observability.
Health checks
MicroProfile Health
Defines a standard way for services to
report their health status. Services can
expose health endpoints that check
dependencies or internal resources,
enabling monitoring systems to track their
availability.
Distributed
tracing
MicroProfile Telemetry Integrates with distributed tracing
systems to track requests across service
boundaries. This helps in understanding
service interactions, identifying
performance bottlenecks, and debugging
issues in a distributed environment.
Advantages andDisadvantages
Like any architectural pattern, microservices come with distinct benefits
and challenges that shape their effectiveness in different contexts.
Teams considering this approach must weigh these trade-offs against
their organizational capabilities, technical requirements, and business
objectives.
551
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Advantages
Independent Scaling
Services can scale independently based on their specific requirements,
allowing for more efficient resource utilization.
Technology Flexibility
Teams can choose different technologies for different services, adopting
the most appropriate tools for each business capability.
Team Autonomy
Separate services enable teams to work independently, releasing updates
on their own schedules without coordinating with other teams.
Focused Codebases
Each service maintains a smaller, more focused codebase, making it easier
to understand and maintain.
Disadvantages
Operational Complexity
Managing multiple independent services requires sophisticated
deployment, monitoring, and orchestration capabilities.
Distributed System Challenges
Teams must handle network latency, partial failures, and eventual
consistency inherent in distributed systems.
552
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Data Management
Maintaining data consistency across services becomes more challenging,
often requiring careful consideration of transaction boundaries and
eventual consistency patterns.
Infrastructure Requirements
Successful microservices implementations typically require significant
infrastructure investment in container orchestration, service discovery,
and monitoring systems.
When to Choose Microservices Architecture
The decision to adopt microservices architecture requires careful
evaluation of specific organizational needs, technical requirements, and
business objectives. Table 14-5 outlines key scenarios and features that
indicate when microservices might be the right architectural choice.
Table 14-5. Pointers to When Microservices Architecture Is a
Good Fit
Description
Example
Large scale and
Applications with a large
Ecommerce platform with
complexity
codebase, complex business separate services for product
Feature/
Scenario
logic, or high traffic.
catalog, shopping cart, order
processing, payments, and
recommendations
(continued)
553
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-5. (continued)
Description
Example
Independent
Multiple teams working
A company with teams dedicated
teams
on different parts of the
to user authentication, search
application, requiring
functionality, and billing, each
autonomy and independent
responsible for their respective
release cycles.
services
Variable
Different parts of the
A social media platform where
scalability
application have different
the newsfeed service needs to
scaling requirements (e.g.,
scale more than the user profile
some services handle much
service
Feature/
Scenario
higher traffic than others).
Technology
Need to use different
A service needing a graph
diversity
programming languages,
database for social connections,
databases, or frameworks
another needing a relational
for different parts of the
database for transactional data
application.
Continuous
Need for frequent and
Releasing updates to a
delivery
independent deployments
recommendation engine service
with minimal downtime.
independently without impacting
the rest of an ecommerce
platform
(continued)
554
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Table 14-5. (continued)
Feature/
Description
Example
The application needs to be
A financial application where
highly available and resilient
the payment processing service
to failures.
needs to be highly available,
Scenario
High availability
even if other services experience
issues
Domain-Driven
Aligning software design with A ride-sharing app with services
Design (DDD)
specific business domains or representing drivers, riders, trips,
bounded contexts.
and payments, each reflecting a
distinct business domain
Polyglot
Different data storage
Using a document database for
persistence
needs for various parts of
storing product information and
the application (relational,
a relational database for storing
NoSQL, graph, etc.).
order details
The need to experiment
Trying out a new message queue
with new technologies,
technology in a non-critical
frameworks, or architectural
service before rolling it out to
patterns without impacting
more important parts of the
the whole system.
system
Avoid vendor lock-in and
Migrating from a monolithic
be able to adapt to new
application to a microservices
technologies and changing
architecture to gain more
business needs.
flexibility and avoid being tied to a
Experimentation
Future-proofing
single vendor
Security
Different security
Separating a high-security service,
requirements and needs for
such as a payment gateway, from
isolation.
a less critical service
555
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
The microservices pattern represents the most distributed approach
to application architecture. While it brings significant benefits in terms of
scalability and team autonomy, it also introduces substantial complexity.
For organizations prepared to handle this complexity, microservices can
provide the flexibility and scalability needed for large-scale enterprise
applications.
Choosing the Right Pattern
Having explored monolithic, modulithic, and microservices architectures
in detail, the question remains: which pattern best suits your specific
needs? The choice of architecture significantly impacts development
velocity, operational complexity, and long-term maintainability of your
Jakarta EE applications.
No single pattern serves as a universal solution. Each organization’s
context—including team structure, business requirements, and technical
constraints—plays a role in determining the most appropriate architectural
approach. Let’s examine a structured approach to making this important
decision.
Decision Framework
Figure 14-1 presents a pictorial view of a decision framework that can help
guide the choice of development architecture.
556
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Figure 14-1. Architectural choice decision framework
The choice of an architectural pattern should reflect three primary
contexts as shown in Figure 14-1.
Application Context
The nature of the application itself plays a crucial role. A complex
application with distinct functional areas might suggest a microservices
architecture, where each area is built and deployed as an independent
service. Simpler applications could be more effectively implemented with
a monolithic architecture, where all components reside within a single
unit. Performance requirements also heavily influence architectural
choices. High-performance applications might require event-driven
architectures or other patterns that support high throughput and low
latency. Additionally, the need for data consistency shapes the selection of
patterns, with some patterns prioritizing strong consistency while others
allow for eventual consistency.
557
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Team Context
The structure and skills of the development team are key factors. Large,
geographically dispersed teams often favor microservices to enable
independent work and parallel development. Smaller, co-located teams might
find a monolithic architecture or a modular monolith easier to manage. The
team’s technical expertise also plays a role. For instance, a team comfortable
with asynchronous programming might lean toward event-driven
architectures. The team’s development processes and release coordination
requirements further inform the choice of architecture, with agile teams
potentially favoring the independent deployability of microservices.
Organizational Context
The broader organizational context imposes constraints on architectural
choices. Available infrastructure, such as cloud-based or on-premises,
can significantly influence the available options. The organization’s
operational capabilities, including monitoring, management, and scaling,
are also important considerations, especially for complex architectures like
microservices. Budget limitations and time-to-market requirements can sway
decisions toward more cost-effective or faster-to-implement architectures.
Finally, compliance needs, such as data security and privacy regulations,
might necessitate specific architectural patterns to ensure adherence.
The choice of architectural pattern sets the foundation for an
application’s future evolution. While it’s possible to change patterns
as the needs evolve, such transitions require significant effort. Taking
time to make an informed decision based on the specific context can
save substantial resources in the long run. The following section looks
at strategies for managing these architectural transitions, focusing on
common migration paths and practical implementation approaches that
minimize risk while maintaining system stability.
558
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Migrating Architectural Patterns
Each architectural pattern presents unique advantages and challenges,
and choosing the right pattern depends on the specific needs of the given
project. However, as projects evolve and requirements change, it often
becomes necessary to migrate between these patterns.
Monolithic toModulithic
This transition involves breaking down a monolithic application into smaller,
more cohesive modules. This modularization improves maintainability and
testability without completely overhauling the architecture.
Modulithic toMicroservices
This path involves further decomposition of modules into independent
services. Each service has its own data store and can be deployed and
scaled independently.
Monolithic toMicroservices
This direct transition is less common but possible with careful planning
and execution. It requires meticulous planning, including careful service
boundary definition and data dependency management.
Figure 14-2 provides a visual guide to understanding common
migration paths discussed above and key considerations for a successful
transition.
559
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
Figure 14-2. Architectural pattern migration guide
Figure 14-2 illustrates the potential transitions between monolithic,
modulithic, and microservices architectures.
Implementation Strategies
To successfully navigate these transitions, it’s important to understand the
strategies that facilitate the migration process as discussed in the following
sections.
560
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Strangler Fig Pattern
This strategy involves gradually replacing specific functionalities of the
existing monolithic system with new microservices. Over time, the new
system “strangles” the old system, taking over its functionality until the
monolith is completely replaced. This approach is particularly useful for
large, complex applications where a complete migration is not feasible or
desirable. It allows for incremental modernization and reduces the risks
associated with a big-bang migration.
Branch by Abstraction
This strategy introduces an abstraction layer between the existing
system and new functionalities. This layer acts as an interface, allowing
the new and old components to interact without being tightly coupled.
This decoupling enables independent development and deployment
of new components while the old system continues to operate. As new
functionality is developed, it is routed through the abstraction layer,
gradually replacing the old system’s functionality.
Parallel Run
This strategy involves running the old and new systems concurrently
for a period. This allows for thorough testing and comparison of the two
systems in a real-world environment. It also provides a fallback option in
case of issues with the new system. Once the new system is proven to be
stable and reliable, the old system can be decommissioned.
These implementation strategies provide a foundation for successful
architectural transitions. However, their effectiveness depends heavily on
how well organizations address key operational and technical considerations
during the migration process. Let’s examine these factors next.
561
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Key Considerations
As teams undertake architectural migrations, several key factors
require careful consideration to ensure a successful transition. These
considerations span technical, operational, and organizational domains,
each playing a role in the migration’s outcome.
Data Management
The migration of data represents one of the most challenging aspects
of architectural transitions. Teams must maintain data integrity while
potentially restructuring their entire data model. This process involves the
following:
562
•
Data consistency becomes particularly complex when
managing transitions between different architectural
patterns. Teams need to implement careful
synchronization strategies, especially when dealing
with distributed data stores. The challenge often lies in
maintaining transactional integrity while data exists in
both old and new systems.
•
Replication strategies play a key role during
migration phases. Organizations must decide
between synchronous and asynchronous replication
approaches, each offering different trade-offs
between consistency and performance. This decision
significantly impacts the migration timeline and system
behavior during the transition.
CHAPTER 14
•
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Database restructuring often becomes necessary when
moving between architectural patterns. This might
involve breaking down monolithic databases into
service-specific data stores or implementing new data
access patterns. Sometimes it may involve moving
from a relational database management system to
a NoSQL system altogether. Teams must carefully
manage schema evolution while maintaining system
functionality.
Team Coordination
The human aspect of architectural migrations often proves as challenging
as the technical components. As systems become more distributed, team
coordination takes on new dimensions:
•
Communication patterns must evolve to support
the new architecture. Teams need to establish clear
channels for sharing technical decisions, addressing
cross-cutting concerns, and maintaining architectural
consistency. This often involves implementing new
collaboration tools and practices.
•
Role definition becomes increasingly important as
systems grow more complex. Teams must clearly
delineate responsibilities across different system
components while maintaining a holistic view of the
architecture. This includes establishing ownership
boundaries and decision-making processes. The need
for clearly delineated roles often creates a barrier
preventing smaller teams from adopting microservices
strategies and sticking with monolith.
563
CHAPTER 14
•
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Development processes require adaptation to support
the new architectural approach. This might involve
implementing new code review practices, establishing
API governance, or adopting new testing strategies.
Teams must balance autonomy with consistency across
the system.
Operational Readiness
Successful migrations depend heavily on operational capabilities that
support both existing and target architectures:
564
•
Testing strategies must evolve to cover new
architectural complexities. Teams need to implement
comprehensive testing approaches that address both
individual components and system-wide behavior. This
includes developing new testing tools and frameworks
suited to the target architecture.
•
Deployment processes require significant adaptation
when moving between architectural patterns.
Organizations must establish reliable deployment
pipelines that support both old and new components
during the transition. This includes implementing
appropriate rollback capabilities and monitoring
systems.
•
Performance management takes on new dimensions
in distributed architectures. Teams must implement
effective monitoring and optimization strategies
that account for network latency, data consistency
requirements, and system resource utilization across
components.
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Monitoring andSecurity
The evolution of system architecture demands corresponding advances in
monitoring and security capabilities:
•
Monitoring infrastructure must adapt to track system
health across increasingly distributed components.
This involves implementing comprehensive logging
systems, distributed tracing capabilities, and effective
alerting mechanisms. Teams need to maintain visibility
into system behavior throughout the migration process.
•
Security considerations become more complex in
distributed systems. Organizations must implement
appropriate authentication and authorization
mechanisms across system boundaries while
maintaining security during the transition. This includes
managing secrets, implementing secure communication
channels, and ensuring appropriate access controls.
•
Compliance requirements often influence architectural
decisions and migration approaches. Teams must
ensure that both the migration process and the
resulting architecture satisfy regulatory requirements
and industry standards. This might involve
implementing new audit capabilities or adapting
existing compliance processes.
Evolving between architectural patterns requires significant effort
and careful planning. However, when done correctly, such migrations can
significantly improve system maintainability, scalability, and development
efficiency. The key lies in choosing appropriate migration strategies and
executing them in a way that maintains system stability while steadily
moving toward the target architecture.
565
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
Summary
Throughout this chapter, we explored the evolution of enterprise
application architectures and their implementation using Jakarta
EE. Beginning with traditional monolithic designs, we examined how
increasing complexity and changing business needs have driven the
emergence of modulithic and microservices patterns. Each architectural
approach offers distinct advantages and challenges, making the selection
process crucial for long-term success.
Jakarta EE’s flexible profile system provides comprehensive support
across these architectural patterns. From the lightweight Core Profile
suited for microservices to the Full Platform Profile powering complex
enterprise applications, Jakarta EE adapts to diverse architectural needs
while maintaining consistency in development approaches.
We looked at implementation strategies, examining how each pattern
uses Jakarta EE specifications differently. The discussion of migration
paths revealed practical approaches for evolving architectures, including
the Strangler Fig pattern and Branch by Abstraction technique. These
strategies help organizations navigate the complexities of architectural
transitions while maintaining system stability.
Key Takeaways
1. Architectural choice significantly impacts
development velocity, operational complexity, and
maintainability.
2. Jakarta EE’s modular approach through profiles
supports various architectural patterns effectively.
3. Migration between patterns requires careful
planning and consideration of data management,
team coordination, and operational readiness.
566
CHAPTER 14
MONOLITHS, MODULITHS, AND MICROSERVICES WITH JAKARTA EE:
ARCHITECTURAL PATTERNS
4. No single architecture suits all scenarios—context
drives the optimal choice.
5. Successful implementations depend on clear
boundaries, appropriate testing strategies, and
evolved security practices.
Looking ahead to Chapter 15, we shift our focus to an emerging
frontier in enterprise development: the integration of artificial intelligence
and large language models with Jakarta EE applications. As AI and LLMs
reshape the technology landscape, understanding how to effectively
combine these powerful tools with Jakarta EE’s enterprise capabilities
becomes increasingly important. We’ll explore how to integrate these
emerging technologies into Jakarta EE applications.
567
CHAPTER 15
AI, LLMs, and Jakarta
EE: The Next Frontier
Artificial intelligence (AI) and machine learning have emerged as
transformative technologies with a profound impact on numerous
domains. Healthcare, manufacturing, retail, education, and banking
and finance are all areas that have been impacted and continue to be
impacted by the rise of AI. The rapid advancement in the field has created
opportunities for developers to tap into, whether you are building a pet or
enterprise project.
But what is AI? What about machine learning (ML)? How can you
harness the power of AI in your Jakarta EE applications? Can you even
develop AI applications and solutions on the Jakarta EE platform?
This chapter aims to answer these questions by exploring AI and ML
frameworks on the Java and Jakarta EE platforms. With its mature
ecosystem and extensive libraries, Java provides a solid foundation for
developing AI and ML applications.
By the end of this chapter, you will
•
Understand the history and fundamental concepts of
AI and machine learning.
•
Recognize the advantages and limitations of
implementing AI in applications.
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2_15
569
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
•
Identify different types of machine learning models and
algorithms.
•
Know the key Java frameworks available for AI/ML
development.
•
Be able to integrate AI capabilities into Jakarta EE
applications using appropriate patterns.
•
Understand best practices for managing AI resources in
enterprise applications.
•
Learn how to orchestrate multiple AI techniques to
solve complex business problems.
A Brief History of Artificial Intelligence (AI)
The foundations of AI as we know it today can be traced back to the
seminal work of the British polymath Alan Turing. Turing was convinced
machines could be taught to make decisions, just as humans do, with
available information and reason. Unfortunately the computers of his
time were not ready for his ideas as they could only execute and not store
commands, in addition to being prohibitively expensive.
Not long after, in 1956 at the Dartmouth Summer Research Project
on Artificial Intelligence, computer scientists Allen Newell, Cliff Shaw,
and Herbert Simon presented the Logic Theorist, a program that mimics
how humans solve problems, funded by Research and Development
Corporation. It was at this event that the term “artificial intelligence” was
coined by host John McCarthy. This event ushered in the next several
decades of research into the field of AI.
The period between the 1950s and the early 2000s saw a turbulent
trajectory for AI research. The single biggest bottleneck was always
the speed and storage capacity of computers. However, from the 1990s
570
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
onward, the availability of powerful computers meant the research of
previous generations could be put to practice. The defeat of world chess
champion Garry Kasparov by IBM's Deep Blue computer marked a
momentous period in the history of AI. This feat, followed by others like
Dragon Systems’s speech recognition software and Kismet, ushered in the
current era of AI.
Today AI is all around us. From very complex game logic to
conversational systems like ChatGPT, AI has become a big part of our
everyday lives, directly and indirectly. The advent of “big data” means we
are able to collect, store, process, and analyze vast amounts of data that is
fed to computers in the form of training. Now that we set the stage with a
brief history, let us define what AI is.
AI and Machine Learning
John McCarthy, the originator of the term "artificial intelligence," defines
it as “the science and engineering of making intelligent machines,
especially intelligent computer programs. It is related to the similar task
of using computers to understand human intelligence, but AI does not
have to confine itself to methods that are biologically observable.” AI, then,
refers to the development of machines or systems that can perform tasks
requiring human-like intelligence. It encompasses various techniques,
including machine learning, natural language processing, computer
vision, expert systems, and more.
Artificial intelligence encompasses a wide range of techniques
and approaches that enable machines to exhibit intelligent behavior.
It involves tasks such as natural language processing, computer vision,
speech recognition, expert systems, and more. AI has seen significant
advancements in recent years, leading to breakthroughs in autonomous
vehicles, virtual assistants, recommendation systems, and medical
diagnosis.
571
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
AI has two broad categories, namely, weak or narrow AI and strong
AI. Weak AI or Artificial Narrow Intelligence is AI trained to perform
very narrow, specific tasks. Its scope, though narrow, is anything but
weak. Examples of narrow AI are self-driving cars, Google Assistant, and
Amazon Alexa.
Strong AI is broken down into Artificial General Intelligence (AGI) and
Artificial Super Intelligence (ASI). AGI is a theoretical form of AI that aims
at matching the intelligence of humans, while ASI aims at exceeding the
intelligence of humans. Strong AI is currently only theoretical, but that
doesn’t rule out researchers exploring its development.
As with everything, AI and ML have their own unique advantages and
disadvantages that you should consider in adopting them for use in your
own applications.
Advantages ofAI/ML
Automation andEfficiency
AI and ML enable automation of repetitive and time-consuming tasks,
leading to increased efficiency and productivity. Machines can process
and analyze large volumes of data at a speed and scale that surpass human
capabilities, resulting in faster and more accurate decision-making. For
example, AI/ML can be used to optimize supply chains by analyzing
historical records and real-time data to improve demand forecasting,
leading to streamlined operations and savings.
Pattern Recognition and Insight Generation
AI and ML algorithms excel at recognizing patterns and extracting
valuable insights from complex data. They can uncover hidden patterns,
correlations, and trends that we humans may overlook, enabling
572
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
organizations to make data-driven decisions and gain a competitive
edge. For example, Stripe uses ML to help detect and prevent fraud in its
payment system.
Personalization and Recommendation Systems
AI and ML algorithms power recommendation systems that personalize
user experiences by analyzing user preferences and behavior. This enables
businesses to deliver tailored product recommendations, content, and
services, enhancing customer satisfaction and engagement. For example,
Amazon and AliExpress both use ML algorithms to decide what product
to recommend to you based on your past purchase, search, and viewing
history on their platforms.
Handling Complex and Unstructured Data
AI and ML techniques are capable of handling unstructured data types,
such as text, images, and audio. They can extract meaning, sentiment, and
context from unstructured data sources, enabling organizations to derive
actionable insights from diverse datasets. For example, OpenAI’s ChatGPT
and Dall-E apps allow for almost human-like interaction with computers.
Disadvantages of AI and ML
Data Dependency and Quality
AI and ML models heavily rely on large and high-quality training data.
Insufficient or biased data can lead to inaccurate or biased predictions,
making it important to ensure the integrity, quality, diversity, and
representativeness of the training data.
573
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Interpretability andExplainability
Some AI and ML models, such as deep neural networks, are often
considered as black boxes, meaning it can be challenging to interpret their
decision-making process. This lack of interpretability can raise ethical
concerns, especially in high-stakes domains such as healthcare or finance,
where understanding the reasoning behind a decision is crucial. This
problem, however, is being addressed in part by the emergence of socalled reasoning models.
Limited Contextual Understanding
AI and ML models are typically designed to operate within specific
domains or tasks. They lack the broader contextual understanding and
common-sense reasoning abilities that humans possess. Even though
models such as OpenAI’s ChatGPT is said to be “almost sentient,” AI
still has a long way to go to get to the level of human understanding and
processing. This can lead to limitations in handling novel or ambiguous
situations that fall outside the scope of their training data.
Job Displacement and Ethical Considerations
The automation potential of AI and ML raises concerns about job
displacement and socioeconomic impacts. Certain job roles may become
obsolete or transformed, requiring individuals to adapt and acquire new
skills. For example, according to CNN,1 Goldman Sachs predicts about
300 million job losses as a result of AI. Additionally, ethical considerations
arise regarding AI biases, privacy concerns, and the responsible use of AI
technology.
1 https://edition.cnn.com/2023/03/29/tech/chatgpt-ai-automation-jobs-
impact-intl-hnk/index.html
574
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Machine Learning
Machine learning is a subset of AI that focuses on developing algorithms that
enable computers to learn from data and improve performance on specific
tasks without being explicitly programmed. It involves the training of models
using data, allowing them to make predictions, classify information, or
uncover patterns and relationships. Data forms the foundation of machine
learning as it is the building block through which computer models are
“taught” about given subjects. You may be wondering what a model is.
Machine Learning Models
Machine learning models function as mathematical frameworks that
analyze data to find patterns, make predictions, and solve problems. These
computational structures serve as the foundation for AI systems across
various domains. There are different categories of models that each cater
to distinct functions.
Predictive Models
Predictive models specialize in forecasting outcomes based on historical
data. Regression models estimate numerical values such as housing prices
or stock market trends. Classification models categorize data into distinct
classes, powering applications like spam detection and disease diagnosis.
Time series models forecast future values based on historical patterns,
enabling weather predictions and sales forecasting.
Generative Models
Generative models create new content rather than just making predictions.
GANs (Generative Adversarial Networks) produce realistic content by
creating a competitive dynamic between two neural networks. VAEs
(Variational Autoencoders) generate new samples by learning the
575
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
underlying distribution of training data. Diffusion models, a more recent
innovation, gradually transform random noise into coherent data through
an iterative refinement process.
Foundation Models
Foundation models are trained on vast datasets spanning multiple
domains, creating versatile systems that can be adapted to numerous
tasks. These models learn general patterns and relationships that transfer
across different applications. After initial training, they can be fine-tuned
for specific purposes, making them highly adaptable. Examples include
GPT, BERT, T5, and Claude.
Thinking Models
Thinking models represent an advanced category designed to mimic
human reasoning processes. These models implement explicit reasoning
steps before producing answers, allowing them to tackle complex
problems methodically.
The Chain-of-Thought technique breaks complex problems into
sequential reasoning steps, creating a logical path from question to
answer. Tree-of-Thought approaches explore multiple potential reasoning
paths simultaneously, evaluating different solutions before selecting the
optimal one.
Many thinking models employ scratchpad approaches, using
intermediate workspace to work through problems step by step. They may
include verification mechanisms to check their own work, reducing errors
and improving reliability.
Some thinking models incorporate external tools for calculation, fact­
checking, or information retrieval, expanding their capabilities beyond
their internal knowledge. Claude 3.7 Sonnet with extended thinking mode
is an example of this approach, using dedicated reasoning processes
before providing responses.
576
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Domain-Specific Models
Domain-specific models are tailored for particular fields like healthcare,
finance, or scientific research. These specialized systems are trained on
datasets relevant to their application area and often integrate domain
knowledge through their architecture or training approach. Focusing
on a specific domain, these models achieve higher performance in their
intended applications.
Types of ML Algorithms
While models provide the architectural framework for machine learning
systems, the algorithms that train these models determine how they
learn from data. These algorithms form the backbone of modern AI,
each with distinct approaches to extracting knowledge from information.
Understanding these fundamental algorithm types reveals how machines
transition from raw data to intelligent behavior through different learning
paradigms.
Supervised Learning
In supervised learning, models are trained using labeled data, where the
input data and corresponding output labels are provided. The algorithm
learns from the input-output pairs and generalizes to make predictions
or classify new, unseen instances. You can think of supervised learning
as teaching a kid how to draw a given pattern by holding and tracing their
hand over the pattern. Essentially in supervised learning, you “tutor” the
computer by helping it identify patterns in a given dataset. Examples of
supervised learning algorithms include linear regression, decision trees,
support vector machines, and neural networks.
577
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Unsupervised Learning
Unsupervised learning involves training models on unlabeled data,
seeking to discover patterns, structures, or relationships within the
data. Clustering and dimensionality reduction are common tasks in
unsupervised learning. Unlike supervised learning, unsupervised learning
entails leaving the computer model to identify patterns in a given dataset
on its own, without any labels or clues from its human “tutors.” Examples
of unsupervised learning algorithms include k-means clustering,
hierarchical clustering, and principal component analysis (PCA).
Reinforcement Learning
Reinforcement learning focuses on training agents to make sequential
decisions through interactions with an environment. The agent receives
rewards or penalties based on its actions, allowing it to learn optimal
strategies to maximize cumulative rewards. Reinforcement learning is
much like teaching a dog to perform a trick by either giving it some reward
or penalizing it in some way. Reinforcement learning algorithms have
been used successfully in applications such as game playing, robotics, and
autonomous systems.
Java AI/ML Frameworks for Jakarta
EE Applications
The Java platform has maintained its position as a premier choice
for software development across industries for over two decades. Its
combination of readability, robust ecosystem, comprehensive tooling, and
enterprise-grade frameworks has cemented Java's place among the most
trusted technologies for building mission-critical applications. Beyond
578
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
the language itself, the Java Virtual Machine (JVM) provides a versatile
runtime environment capable of executing code written in various
languages beyond Java, including Scala, Kotlin, Clojure, and Groovy.
This powerful combination—the Java language paired with the JVM—
creates an ideal foundation for developing sophisticated AI-powered
applications. As artificial intelligence and machine learning become
increasingly integral to modern software solutions, Java's stability,
performance, and enterprise capabilities make it particularly well-suited
for organizations looking to incorporate these technologies into their
existing systems.
This section explores the various frameworks and libraries available
for building AI and ML applications on the Java platform, with special
attention to their integration within Jakarta EE environments. For clarity,
we categorize these tools into five key domains: machine learning,
neural networks, expert systems, natural language processing, and AI
orchestration.
Machine Learning
Deep Java Library (DJL)
The Deep Java Library (DJL) is a more recent addition to the Java AI
ecosystem. Led by Amazon Web Services as a community project, DJL
provides a high-level API for training, testing, and deploying machine
learning models within Java applications.
Key features of DJL include
•
Engine-agnostic design supporting multiple backend
frameworks
•
Pure Java API with minimal dependencies
•
Simple model training and deployment
•
Comprehensive documentation and examples
579
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
DJL's engine-agnostic approach is particularly useful, allowing
developers to choose from backends like PyTorch, TensorFlow, MXNet,
and ONNX Runtime. This flexibility enables teams to select the most
appropriate framework for their specific use case without changing their
application code.
Integration with Jakarta EE
DJL can be integrated into Jakarta EE applications as a service component
as shown in Listing 15-1.
Listing 15-1. DJL integrated into Jakarta EE applications as a service
component
@ApplicationScoped
public class ImageRecognitionService {
private Predictor<Image, Classifications> predictor;
@PostConstruct
public void initialize() {
// Load pre-trained model
Criteria<Image, Classifications> criteria = Criteria.
builder()
.setTypes(Image.class, Classifications.class)
.optEngine("PyTorch")
.optModelPath(Paths.get("models/resnet50"))
.build();
predictor = ModelZoo.loadModel(criteria).
newPredictor();
}
public Classifications classifyImage(byte[] imageData) {
Image img = ImageFactory.getInstance().
fromInputStream(new ByteArrayInputStream(imageData));
580
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
return predictor.predict(img);
}
}
Listing 15-1 shows an example of an image recognition service using a
pre-trained ResNet50 model from the ModelZoo.
This implementation uses Jakarta CDI’s lifecycle management while
providing a clean API for other components to consume the machine
learning capabilities.
Neural Networks
Neural networks, inspired by the biological neurons in the human brain,
form the foundation of deep learning—a powerful subset of machine
learning. Java offers several mature frameworks for building and deploying
neural network models.
Deeplearning4j
Deeplearning4j (DL4J), now an Eclipse Foundation project, is the most
comprehensive neural network library native to the JVM. It provides a
complete ecosystem for building, training, and deploying deep learning
models in Java environments.
Notable features include
•
Support for various neural network architectures
•
Distributed training capabilities
•
GPU acceleration
•
CPython bindings for interoperability with Python
ecosystems
•
Integration with Apache Spark for large-scale
processing
581
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
DL4J's maturity and enterprise focus make it well-suited for
Jakarta EE environments where reliability and performance are critical
considerations.
Within Jakarta EE applications, DL4J can be used as a service
component as shown in Listing 15-2.
Listing 15-2. The implementation of a fraud detection service using
a pre-trained neural network
@Singleton
@Startup
public class FraudDetectionService {
private MultiLayerNetwork network;
@PostConstruct
public void initialize() {
// Define network configuration
MultiLayerConfiguration conf = new
NeuralNetConfiguration.Builder()
.seed(123)
.activation(Activation.TANH)
.weightInit(WeightInit.XAVIER)
.updater(new Nesterovs(0.01, 0.9))
.list()
.layer(0, new DenseLayer.Builder().
nIn(numInputs).nOut(20).build())
.layer(1, new OutputLayer.
Builder(LossFunctions.LossFunction.
NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX).
nIn(20).nOut(numOutputs).build())
.build();
582
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
// Initialize and train network
network = new MultiLayerNetwork(conf);
network.init();
// Load pre-trained model weights
ModelSerializer.restoreMultiLayerNetwork(new
File("fraud-detection-model.zip"));
}
@Asynchronous
public Future<FraudPrediction> evaluateTransaction
(Transaction transaction) {
INDArray features = Nd4j.create(transaction.
toFeatureArray());
INDArray output = network.output(features);
double fraudProbability = output.getDouble(0);
return new AsyncResult<>(new FraudPrediction
(fraudProbability > 0.7, fraudProbability));
}
}
This implementation takes advantage of Jakarta EE's initialization
capabilities and asynchronous processing to provide fraud detection
services without blocking the main application thread.
ND4J (N-Dimensional Arrays for Java)
While not a neural network framework itself, ND4J deserves mention as
a critical component of the Java deep learning ecosystem. As part of the
Deeplearning4j suite, ND4J provides efficient n-dimensional arrays for
Java, similar to NumPy in Python. This library enables the highperformance tensor operations essential for deep learning.
583
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
ND4J features
•
GPU and CPU acceleration
•
Support for distributed computing
•
Memory-mapped storage for large datasets
•
Integration with DL4J and other JVM libraries
When working with any neural network framework in Java, ND4J
typically provides the underlying computational primitives.
Deep Netts
Another noteworthy Java-native platform in this space is Deep Netts. It
provides a development platform focused on simplifying deep learning for
Java developers, featuring visual tools like a drag-and-drop model builder
and expert wizards alongside a pure Java library. It supports common
network types and aims to streamline the integration and deployment
of ML models within Java environments, also providing a reference
implementation for JSR 381 (Visual Recognition specification).
Expert Systems
Expert systems represent a different branch of artificial intelligence, focusing
on capturing and applying domain-specific knowledge. These systems excel
at solving problems that would normally require human expertise.
OptaPlanner
OptaPlanner specializes in constraint satisfaction problems—a class of
computational challenges that include scheduling, resource allocation,
and optimization tasks. Developed as part of the KIE (Knowledge
Is Everything) Group, OptaPlanner integrates with other business
automation tools in the Java ecosystem.
584
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Its key capabilities include
•
Powerful constraint solving capabilities
•
Flexible scoring system for evaluating solutions
•
Multiple optimization algorithms
•
Real-time planning capabilities
•
Integration with other business rule systems
OptaPlanner's focus on business problems makes it valuable for
enterprise applications built with Jakarta EE.
OptaPlanner can be implemented as a Jakarta CDI service component
as shown in Listing 15-3.
Listing 15-3. The creation of an optimal schedule by defining the
problem, creating a solver, and returning the best solution found
@ApplicationScoped
public class SchedulingService {
public Schedule createOptimalSchedule(List<Employee>
employees, List<Shift> shifts) {
// Define the problem
EmployeeSchedule problem = new EmployeeSchedule();
problem.setEmployeeList(employees);
problem.setShiftList(shifts);
// Create solver
SolverFactory<EmployeeSchedule> solverFactory =
SolverFactory.createFromXmlResource(
"employeeSchedulingSolverConfig.xml");
Solver<EmployeeSchedule> solver = solverFactory.
buildSolver();
585
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
// Solve and return best solution
EmployeeSchedule solution = solver.solve(problem);
return new Schedule(solution.getShiftAssignments());
}
}
Drools
While primarily known as a business rules management system, Drools
serves as a powerful platform for building expert systems in Java. It
provides a rule engine that can represent and reason about complex
domain knowledge using declarative rules.
Drools offers
•
Forward and backward chaining inference
•
Rule authoring in various formats (DRL,
decision tables)
•
Complex event processing capabilities
•
Integration with OptaPlanner and other KIE tools
When combined with Jakarta EE, Drools enables applications to
incorporate sophisticated business logic that can adapt to changing
requirements without modifying application code.
Drools can be integrated into Jakarta EE applications as shown in
Listing 15-4.
Listing 15-4. A Drools rule engine service that evaluates a loan
application and returns a loan decision
@ApplicationScoped
public class RuleEngineService {
private KieSession kieSession;
586
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
@PostConstruct
public void initialize() {
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.
getKieClasspathContainer();
kieSession = kieContainer.newKieSession("underwriting
Session");
}
public LoanDecision evaluateLoanApplication(LoanApplication
application) {
LoanDecision decision = new LoanDecision();
kieSession.insert(application);
kieSession.insert(decision);
kieSession.fireAllRules();
return decision;
}
}
This service encapsulates the rule engine, providing a clean interface
for other components to access expert system capabilities.
Natural Language Processing
Natural language processing (NLP) enables applications to understand,
interpret, and generate human language. Java offers several mature
libraries for NLP tasks.
Stanford CoreNLP
Developed at Stanford University, CoreNLP provides a comprehensive
suite of natural language analysis tools. It offers state-of-the-art algorithms
for various NLP tasks packaged in a cohesive, easy-to-use API.
587
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
CHAPTER 15
CoreNLP capabilities include
•
Tokenization and sentence segmentation
•
Part-of-speech tagging
•
Named entity recognition
•
Dependency parsing
•
Sentiment analysis
•
Coreference resolution
The library's modular design allows you to selectively incorporate the
specific NLP capabilities their applications require.
Within Jakarta EE applications, CoreNLP can be implemented as
shown in Listing 15-5.
Listing 15-5. TextAnalysisService class that is used to analyze a
given text
@ApplicationScoped
public class TextAnalysisService {
private StanfordCoreNLP pipeline;
@PostConstruct
public void initialize() {
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos,
lemma, ner, sentiment");
pipeline = new StanfordCoreNLP(props);
}
public TextAnalysisResult analyzeText(String text) {
Annotation document = new Annotation(text);
pipeline.annotate(document);
588
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
// Extract entities, sentiment, etc.
List<NamedEntity> entities = extractEntities(document);
SentimentClass sentiment = extractSentiment(document);
return new TextAnalysisResult(entities, sentiment);
}
// Helper methods for extraction...
}
This implementation takes advantage of Jakarta CDI’s lifecycle
initialization capabilities to prepare the NLP pipeline once at startup. This
component can then be injected into different parts of the application for
other dependent components to use.
Apache OpenNLP
OpenNLP provides a more lightweight alternative to CoreNLP, focusing
on the most common NLP tasks with an emphasis on simplicity and
ease of use. As an Apache project, it has strong community support and
integration with other Apache technologies.
OpenNLP supports
•
Tokenization and sentence detection
•
Part-of-speech tagging
•
Named entity extraction
•
Chunking and parsing
•
Language detection
•
Maximum entropy models for classification
OpenNLP's modest resource requirements make it suitable for
applications where performance is a priority.
589
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
OpenNLP can be integrated into Jakarta EE applications as shown in
Listing 15-6.
Listing 15-6. The implementation of a
DocumentClassificationService that categorizes documents using a
pre-trained model
@ApplicationScoped
public class DocumentClassificationService {
@Inject
@ConfigProperty(named=”modelsDir”)
private String modelsDirectory;
private DocumentCategorizerME categorizer;
@PostConstruct
public void initialize() {
try (InputStream modelIn = new FileInputStream
(modelsDirectory + "/document-categorizer.bin")) {
DoccatModel model = new DoccatModel(modelIn);
categorizer = new DocumentCategorizerME(model);
} catch (IOException e) {
throw new RuntimeException("Failed to load document
categorization model", e);
}
}
public CategoryPrediction categorizeDocument(String
documentText) {
double[] probabilities = categorizer.
categorize(documentText);
String category = categorizer.getBestCategory(proba
bilities);
590
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
double confidence = probabilities[categorizer.
getIndex(category)];
return new CategoryPrediction(category, confidence);
}
}
This implementation shows how OpenNLP can be incorporated into
the Jakarta EE component model, with model files managed through
MicroProfile Config property.
LangChain4j
LangChain4j represents a new generation of Java NLP tools designed
specifically for working with large language models (LLMs). It is the Java
counterpart to the popular Python library LangChain, benefiting from the
concepts and extensive community knowledge surrounding the original
framework. This library provides a framework for building applications
powered by language models like GPT-4, Claude, and others within the
Java ecosystem.
Key features include
•
Connectors for various LLM providers (OpenAI,
Anthropic, Hugging Face)
•
Context-aware prompt engineering
•
Document processing and embedding
•
Retrieval-augmented generation
•
Agent frameworks for complex workflows
•
Memory mechanisms for stateful conversations
591
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
LangChain4j enables the building of sophisticated AI applications
in Java. It can be integrated into Jakarta EE applications as shown in
Listing 15-7.
Listing 15-7. How to create a customer support service that uses
retrieval-augmented generation (RAG) to provide answers to
customer queries
@RequestScoped
public class CustomerSupportService {
@Inject
private DocumentStore documentStore;
private ChatLanguageModel chatModel;
private RetrievalAugmentor augmentor;
@PostConstruct
public void initialize() {
// Initialize LLM client
chatModel = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4")
.temperature(0.7)
.build();
// Configure RAG
EmbeddingModel embeddingModel = OpenAiEmbeddingModel.
builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("text-embedding-ada-002")
.build();
EmbeddingStore<TextSegment> embeddingStore = new
InMemoryEmbeddingStore<>();
592
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
// Load knowledge base documents
documentStore.getProductDocuments().forEach(doc -> {
TextSegment segment = TextSegment.from(doc.
getContent(), Metadata.from("source", doc.
getTitle()));
embeddingStore.add(embeddingModel.embed(segment).
content(), segment);
});
augmentor = RetrievalAugmentor.builder()
.embeddingModel(embeddingModel)
.embeddingStore(embeddingStore)
.maxResults(3)
.minScore(0.7)
.build();
}
public String generateResponse(String customerQuery) {
AugmentationResult augmentationResult = augmentor.
augment(customerQuery);
String augmentedPrompt = "Based on the following
information, answer the customer's question:\n\n" +
"Context:\n" + augmentationResult.
textSegments().stream()
.map(TextSegment::text)
.collect(Collectors.joining("\n\n")) +
"\n\nCustomer Question: " + customerQuery +
"\n\nProvide a helpful, accurate response using
only the information provided.";
return chatModel.generate(augmentedPrompt);
}
}
593
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
CHAPTER 15
This example shows how LangChain4j, using retrieval-augmented
generation and incorporating product documentation, can be used to
create a customer support system with enhanced responses.
AI Orchestration
Modern AI applications often combine multiple techniques and models to
solve complex problems. AI orchestration frameworks help manage these
integrations.
LangChain4j (Orchestration Capabilities)
Beyond its NLP capabilities, LangChain4j also provides tools for
orchestrating complex AI workflows:
•
Tool integration for external system access
•
Agent frameworks for autonomous decision-making
•
Memory systems for stateful interactions
•
Document processing workflows
These features allow Java applications to coordinate multiple AI
components within a cohesive system.
Spring AI
Though not strictly a Jakarta EE technology, Spring AI deserves mention
as an increasingly popular option for AI integration in Java applications. It
provides
594
•
Abstractions for working with various AI models
•
Integration with the Spring ecosystem
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
•
Prompt engineering capabilities
•
Document processing tools
For organizations using both Spring and Jakarta EE, the two can be
combined through appropriate architectural patterns.
Best Practices for Jakarta EE Integration
When incorporating AI frameworks into Jakarta EE applications, several
architectural patterns and practices can enhance maintainability,
performance, and scalability.
Service Layer Encapsulation
Implement AI capabilities as Jakarta EE service components (CDI beans)
that encapsulate the underlying frameworks. This approach provides
•
Clean separation of concerns
•
Consistent transaction boundaries
•
Security integration
•
Resource pooling
Resource Management in AI Frameworks
AI and machine learning frameworks often demand substantial
computational resources, including memory, CPU, and GPU. To ensure
optimal performance and prevent resource leaks, it's important to
manage these resources effectively within your applications. Here's a
look at resource management strategies, particularly within the context of
Jakarta EE:
595
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Lifecycle Management
•
@ApplicationScoped and @PostConstruct: For
resource-intensive initialization tasks (e.g., loading
large models, establishing database connections),
use the @ApplicationScoped annotation to create a
single instance shared across the application. The @
PostConstruct lifecycle hook ensures that initialization
occurs only once, when the application starts.
•
@PreDestroy: To prevent resource leaks and ensure
proper cleanup, implement the @PreDestroy lifecycle
hook. This method is called when the application is
shutting down or the bean is being destroyed, allowing
you to release resources like file handles, database
connections, and threads.
Concurrency
•
Jakarta EE Concurrency Utilities: Use the
concurrency constructs provided by Jakarta EE
(e.g., ExecutorService, ManagedExecutorService,
CompletableFuture) to execute tasks in parallel. This
can significantly improve performance for AI workloads
that can be parallelized.
•
Thread Pools: Use thread pools to manage the number
of threads used for concurrent tasks. This prevents
thread exhaustion and ensures efficient resource usage.
Timeouts
•
596
Configuring Timeouts: For long-running AI operations
(e.g., model training, inference), configure appropriate
timeouts to prevent the application from hanging
indefinitely.
CHAPTER 15
•
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Fallback Mechanisms: Implement fallback
mechanisms to handle scenarios where operations
exceed their timeouts. This might involve returning
cached results, using a simpler model, or notifying
the user of the delay. This can be done using the
MicroProfile Fault Tolerance API.
Model Lifecycle Management
AI models often need periodic retraining or updating. Implement
•
Version control for models
•
Canary deployment strategies
•
A/B testing capabilities
•
Performance monitoring
Integration Architecture
For complex AI systems, consider
•
Microservices architecture for independent scaling of
AI components
•
Message-driven architecture for asynchronous
processing
•
Event sourcing for tracking model inputs and outputs
•
API gateway patterns for managing client access to AI
services
597
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Example Fraud Detection System
To illustrate these concepts, consider a fraud detection system built with
Jakarta EE and the various AI frameworks mentioned in this chapter in
Listing 15-8.
Listing 15-8. Sample fraud detection system using different AI
frameworks
@ApplicationScoped
public class FraudDetectionOrchestrator {
@Inject
private TransactionRepository repository;
@Inject
private RuleBasedDetector ruleDetector;
expert system
// Drools-based
@Inject
private AnomalyDetector anomalyDetector;
neural network
// DL4J-based
@Inject
private TransactionClassifier classifier;
classifier
// Weka-based
@Inject
private NLPAnalyzer nlpAnalyzer;
analysis
// OpenNLP-based text
@Asynchronous
public Future<FraudAssessment>
assessTransaction(Transaction transaction) {
// 1. Apply rule-based filters (fast, catches
obvious fraud)
598
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
RuleResult ruleResult = ruleDetector.
evaluate(transaction);
if (ruleResult.isDefinitiveFraud()) {
return new AsyncResult<>(new FraudAssessment(true,
1.0, "Rule violation: " + ruleResult.getReason()));
}
// 2. Check for anomalies compared to customer history
List<Transaction> customerHistory = repository.
getCustomerHistory(transaction.getCustomerId());
AnomalyScore anomalyScore = anomalyDetector.
detectAnomaly(transaction, customerHistory);
// 3. Apply ML classification
ClassificationResult classificationResult = classifier.
classify(transaction);
// 4. Analyze transaction description with NLP
TextAnalysisResult textAnalysis = nlpAnalyzer.
analyzeText(transaction.getDescription());
// 5. Combine all signals for final assessment
double combinedProbability =
calculateCombinedProbability(
ruleResult, anomalyScore, classificationResult,
textAnalysis);
String explanation = generateExplanation(
ruleResult, anomalyScore, classificationResult,
textAnalysis);
return new AsyncResult<>(new FraudAssessment(
combinedProbability > 0.8, combinedProbability,
explanation));
}
599
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
// Helper methods for probability calculation and
explanation generation...
}
The FraudDetectionOrchestrator class shows how multiple
AI techniques can be integrated to create a sophisticated fraud
detection system.
The orchestrator follows the Jakarta EE component model, using
@ApplicationScoped to create a singleton instance shared across the
application and @Inject to use dependency injection for its required
components. Each injected dependency represents a different AI
approach:
1. RuleBasedDetector: A Drools-based expert system
that applies business rules to quickly identify
obvious fraud patterns.
2. AnomalyDetector: A neural network implemented
with Deeplearning4j that identifies unusual
transactions compared with customer history.
3. TransactionClassifier: A machine learning classifier
built with Weka that categorizes transactions based
on learned patterns.
4. NLPAnalyzer: A text analysis component using
OpenNLP to extract insights from transaction
descriptions.
The assessTransaction method displays a multi-layered approach to
fraud detection:
600
•
It first applies fast rule-based checks that can
immediately flag clear violations.
•
For transactions that pass initial screening, it performs
deeper analysis using multiple AI techniques.
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
•
It combines signals from different models to calculate a
final fraud probability.
•
It generates an explanation that provides context for the
assessment.
The @Asynchronous annotation ensures this potentially time­
consuming process doesn't block the application thread, returning a
Future<FraudAssessment> that will be completed when processing
finishes.
This orchestration pattern shows how Jakarta EE applications can
combine multiple AI frameworks to solve complex problems while
maintaining enterprise-grade characteristics like dependency injection,
asynchronous processing, and clean separation of concerns. Each AI
component can be independently developed, tested, and maintained,
while the orchestrator provides a unified interface to the combined
intelligence of the system.
The Future of AI in Jakarta EE Applications
Standardization andIntegration
The convergence of Jakarta EE and artificial intelligence is still in its
early stages, with substantial growth and innovation on the horizon. As
enterprise Java applications increasingly incorporate AI capabilities,
we can expect several key developments to shape this landscape in the
coming years.
The Jakarta EE platform itself may evolve to include standardized
APIs specifically for AI integration. Much like how Jakarta Persistence
API standardized database access across different providers, future
specifications could offer consistent approaches to model deployment,
601
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
execution, and lifecycle management across various AI frameworks. This
standardization would reduce vendor lock-in and simplify the integration
of different AI technologies within the same application.
Evolving Deployment Architectures
Deployment architectures for AI-powered Jakarta EE applications are
also likely to transform. The computational demands of sophisticated AI
models often differ significantly from traditional enterprise workloads,
potentially driving adoption of hybrid architectures. In these systems,
AI components might be deployed as separately scalable microservices
or even as serverless functions, while maintaining integration with core
Jakarta EE business logic through well-defined APIs.
Edge Computing and AI
Edge computing represents another frontier where Jakarta EE and AI
will increasingly intersect. As organizations seek to process data closer
to its source, we may see specialized Jakarta EE profiles optimized for
edge deployments with integrated AI capabilities. These systems would
enable real-time intelligence at the network edge while maintaining the
programming model and enterprise features that Java developers value.
Large Language Models in Enterprise
Applications
Large language models (LLMs) will likely become standard components
within many Jakarta EE applications. Beyond powering chatbots and
virtual assistants, these models can enhance existing applications with
capabilities like intelligent document processing, natural language
interfaces to legacy systems, and advanced content generation. The
602
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
LangChain4j framework already points toward this future, providing
Jakarta EE developers with tools to integrate these powerful models into
their applications.
AI-Enhanced Development Experience
The development process itself will be transformed by AI tools designed
specifically for Jakarta EE applications. AI assistants specialized in
enterprise Java patterns, such as GitHub Copilot, Amazon Q Developer,
or Claude CLI, could suggest optimizations, identify potential issues,
and even generate boilerplate code. These tools might analyze existing
codebases to recommend modernization approaches or suggest
architectural improvements based on observed usage patterns.
Autonomous Enterprise Systems
Enterprise systems built on Jakarta EE will incorporate increasingly
autonomous capabilities. Rather than requiring constant human
monitoring and intervention, these systems may detect and resolve
many issues automatically. Performance optimization, security policy
adjustment, and resource allocation could become increasingly self­
managed, allowing development teams to focus on business logic and
innovation rather than operational concerns.
Responsible AI in Enterprise Applications
As AI becomes more powerful and pervasive in enterprise applications,
frameworks for responsible deployment will become essential. Jakarta
EE applications incorporating AI will need mechanisms to ensure
explainability, detect bias, and protect privacy. Organizations may adopt
formal governance processes for AI models similar to those they use for
database schemas or API definitions today.
603
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
The integration of AI with Jakarta EE represents not just a technological
evolution but a fundamental shift in how enterprise applications are
conceived and built. The mature, stable foundation of Jakarta EE combined
with the rapidly advancing capabilities of modern AI has the potential to
create a new generation of intelligent enterprise applications—ones that
not only process transactions and store data but actively assist users, adapt
to changing conditions, and continuously improve their own operation.
As Jakarta EE continues its evolution from traditional enterprise
applications to intelligent systems, developers who understand both
domains will be uniquely positioned to create innovative solutions that
combine the best of both worlds.
Conclusion
The Java ecosystem offers a rich array of frameworks and libraries for
incorporating artificial intelligence into enterprise applications. From
traditional machine learning and neural networks to expert systems and
natural language processing, Java developers have access to tools that can
address virtually any AI use case.
When integrated with Jakarta EE, these frameworks benefit from
enterprise-grade features like component management, dependency
injection, transaction handling, and security. This combination allows
organizations to build sophisticated AI-powered applications that are both
powerful and maintainable.
604
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
Key Takeaways
1. Diverse AI Capabilities: Java provides mature
frameworks across various AI domains, including
machine learning (DJL), neural networks
(Deeplearning4j), expert systems (OptaPlanner,
Drools), and natural language processing (CoreNLP,
OpenNLP, LangChain4j).
2. Enterprise Integration Patterns: AI components in
Jakarta EE applications should follow established
patterns like service layer encapsulation, proper
resource management, and lifecycle-aware
initialization.
3. Resource Management: AI frameworks often
require significant computational resources, making
proper initialization, cleanup, and concurrency
management essential in enterprise applications.
4. Orchestration Approaches: Complex AI systems
benefit from combining multiple techniques, with
each specialized component handling different
aspects of the problem space.
5. CDI Integration: Jakarta's dependency injection
system provides an ideal mechanism for managing
AI component lifecycles and dependencies.
6. Asynchronous Processing: Computationally
intensive AI operations should leverage Jakarta EE's
asynchronous capabilities to maintain application
responsiveness.
605
CHAPTER 15
AI, LLMS, AND JAKARTA EE: THE NEXT FRONTIER
7. Flexible Deployment Models: AI components can
be deployed within monolithic applications or as
independent microservices depending on scaling
and resource requirements.
As AI continues to evolve, the Java ecosystem is likely to remain at
the forefront, combining the stability and performance that enterprises
require with the cutting-edge capabilities that AI applications demand.
By understanding the available frameworks and appropriate integration
patterns, developers can leverage the best of both worlds to create
innovative solutions for their organizations.
606
Index
A, B
ADRs, see Architectural Decision
Records (ADRs)
AGI, see Artificial General
Intelligence (AGI)
AI, see Artificial intelligence (AI)
American Software Testing
Qualifications Board
(ASTQB), 482
AOP, see Aspect-Oriented
Programming (AOP)
API, see Application programming
interface (API)
Application programming
interface (API), 34
documentation, 322
generated documentation,
328, 329
getClasses method, 284-286
health check, 428-430
observability, 390
OpenAPIDefinition config
class, 323
passing parameters, 244
resource documentation,
324-326
schema generation, 326, 327
search object, 245
search type queries, 243
UserSearchRequest, 246
Architectural decision-making
microservices
factors, 82
Architectural Decision
Records (ADRs)
considerations, 79
documentation, 85-87
horizontal/vertical scaling, 80
maintainability, 80
microservices
factors, 81
patterns, 83
trade-offs, 83
minimum viable
product (MVP), 81
performance features, 79
requirements, 81
secure operations, 80
synchronous/asynchronous
communication, 83-85
systems/services, 80
team’s skills and experience, 81
time-to-market, 81
visualization, 86
© Luqman Saeed and Ghazy Abdallah 2025
L. Saeed and G. Abdallah, Pro Cloud-Native Java EE Apps,
https://doi.org/10.1007/979-8-8688-1396-2
607
INDEX
Architectural patterns
abstraction layer, 561
considerations, 533, 534, 562
data management, 562
decision framework
complex application, 557
organizational context, 558
pictorial view, 556, 557
team context, 558
enterprise architecture, 530
implementation strategies, 561
microservices, 548-556
migration, 560, 561
modulithic architectures (see
Modulithic architectures)
monitoring and security, 565
monolithic architecture (see
Monolithic architecture)
operational capabilities, 564
organization context, 556
profiles, 532, 533
strangler fig pattern, 561
team coordination, 563
Artificial General
Intelligence (AGI), 572
Artificial intelligence (AI),
1, 20, 569
advantages
automation/efficiency, 572
handling unstructured
data, 573
pattern recognition/insight
generation, 572
personalization, 573
608
recommendation
system, 573
assessTransaction method, 600
autonomous enterprise
systems, 603
categories, 572
definition, 571, 572
deployment architectures, 602
development process, 603
disadvantages
contextual
understanding, 574
data dependency/
quality, 573
ethical considerations, 574
interpretability/
explainability, 574
edge computing, 602
enterprise applications, 603
fraud detection system, 598-601
history, 570, 571
Jakarta EE, 20
large language models, 602
orchestration frameworks, 594
LangChain4j, 594
Spring, 594, 595
revolution, 20
service layer encapsulation
approach, 595
concurrency utilities, 596
integration architecture, 597
lifecycle management, 597
resource management,
595-597
INDEX
standardization, 601
Artificial Super
Intelligence (ASI), 572
ASI, see Artificial Super
Intelligence (ASI)
ASTQB, see American Software
Testing Qualifications
Board (ASTQB)
Aspect-Oriented Programming
(AOP), 48, 151
C
CDI, see Contexts and Dependency
Injection (CDI)
Chain-of-Thought technique, 576
Cloud-native application, 23
APIs development, 34
architectures, 498
application servers, 500
cloud requirements, 500
configuration
management, 501
containerization, 499
distribution, 500
immutable
infrastructure, 499
CNCF definition, 27, 28
containerization, 40-44
containerization efforts, 33
container orchestration
platforms, 28
contribution, 54
core principles, 26
dependency injection
framework, 35
deployment/
operations, 498-527
directions initiative, 53
ecosystem, 49
environments, 26, 44-46
considerations, 45, 46
private/hybrid setups, 45
public cloud providers, 44
frameworks, 46-49
health checks, 442-450
Jakarta Persistence, 36
JSON-B, 34
landscape, 50
capabilities, 50
community contributions, 52
developer experience, 51
edge computing, 51
GraalVM, 52
stability, 52
standards, 51
technologies, 50
lightweight framework, 33
MicroProfile config, 35
microservices, 37-40
microservices development, 32
modular architecture, 32
objectives, 24
REST/JAX-RS, 34
twelve-factor app, 29-32
Cloud Native Computing
Foundation (CNCF),
27, 28, 415
609
INDEX
CNCF, see Cloud Native Computing
Foundation (CNCF)
Configuration management
alternatives/qualifier
features, 336
cloud-native applications,
336, 337
deployment patterns, 506-508
environment entries, 335, 336
external resources, 334
fault tolerance system, 382-384
MicroProfile
automatic conversion, 342
config source/priority,
338, 339
conversion, 342-346
custom conversion, 343-345
custom source
implementation, 340-342
priority setting, 345, 346
sources/ordinals, 339
specification, 337
type conversion, 342
overview, 333
resource injection, 334
values
bean, 347, 348
ConfigValue metadata, 352
direct injection, 348
getOptionalValue
method, 347
getValue method, 347
optional injection, 349
provider injection, 350-352
610
retrieval method, 346
supplier injection, 351, 352
web.xml file, 335
Containerization
applications, 42, 43
challenges/considerations, 44
containers, 40
Dockerfile, 41, 42
handling, 43
logging solutions, 44
Open Container
Initiative (OCI), 41
Contexts and Dependency
Injection (CDI), 4, 32, 35, 77
architectural improvements/
features, 94
bean-discovery-mode
activation process, 98
annotations, 98
attribute, 97
none, 98
beans/contextual instances
attributes, 105
components, 104
contextual instances, 109
dependency declaration, 105
label/qualifier, 107
managed bean, 104
methods, 106
name, 108
resolution, 107
types, 106, 107
WalletService, 104
beans.xml config file, 97
INDEX
cloud-native applications, 449
container
components, 99
dependency resolution, 102
error message, 101
instance management, 101
responsibilities, 99
scenarios, 102
transparent operation, 103
validation, 99-101
decorator
design pattern, 156
differents, 156
SimpleUserService, 157
UserServiceDecorator, 158
UserService interface, 157
enterprise beans, 125, 126
event mechanism
asynchronous, 164-166
components, 160
conditional observation,
175, 176
createUser method, 163
dynamic qualifier
selection, 171
MessageCenter class, 170
MessageOption
parameter, 169
metadata, 174
objects, 160-163
observers, 163, 164
qualifiers, 168-174
sendUserSms, 176
transactional
observers, 167-169
UserResponse, 162
UserServiceDecorator, 161
events, 96
expression language (EL), 94
features, 95
HealthCheck interface, 430-436
injection points
constructor injection,
121-123
field injection point, 121
initializeMeter method, 124
MeteredWalletService, 124
methods, 124
representation, 121
SignupManager class, 123
integration, 96
interceptors, 96
AroundInvoke, 153
bean class, 152-155
binding annotation, 151, 152
components, 151
functionalities, 150
logging, 151
stereotypes, 155, 156
Inversion of Control (IoC),
92-94
lifecycle callbacks, 148
@PostConstruct annotation,
149, 150
@PreDestroy methods, 150
SecurityManager bean, 149
611
INDEX
Contexts and Dependency
Injection (CDI) (cont.)
lifecycle context, 95
loose coupling, 91
metrics/stereotypes, 413, 414
portable extensions, 96
producers
EntityManager, 141
fields, 140-142
fixed producer method, 138
GPT-4 and GPT-3.5
qualifiers, 142
@Inject, 144
interceptors, 145
logger producer method,
140, 141
methods, 136-139
@Observes/@
ObservesAsync
annotations, 144
OpenAiChatModel class,
135, 136
qualifiers, 142-144
validation error, 137
programmatic access, 95
proxying
circular dependencies, 113
class requirements, 114
dependency injection, 112
ecommerce system, 113
final methods, 114
lazy initialization, 113
method visibility, 113
objects, 112
612
requirements, 113
scope independence, 112
userService, 112
qualifiers, 127-135
@Any, 131
custom qualifiers, 128-130
@Default, 131
error message, 128
MessageCenter, 130
MessageOption, 129
@Named, 132-134
RateResource interface, 127
resolution, 95
scopes/contexts
@ApplicationScoped
annotation, 114
built-in scopes, 114
conversation scope, 117-120
dependent-scoped bean, 120
differents, 110
proxying, 111-114
@RequestScoped
annotation, 115
SecurityManager
controller, 110
service()/doFilter()
methods, 115
@SessionScoped
annotation, 116, 117
UserService controller,
110, 115
stereotypes
action, 146, 147
metadata requirements, 146
INDEX
restrictions, 148
WalletService/UserService
beans, 146
testing, 485, 486
D
Data access operations
features, 260
repository interfaces, 261
BasicRepository, 262
built-in repositories, 263, 264
conditional expressions, 264
CrudRepository, 262
querying data, 264-266
types, 261
UserRepository, 261
Data definition language (DDL)
modeling process, 187
Data modeling process
AbstractEntity class, 204
annotations transform, 181
basic/simple types, 197
collection-valued
relationship, 215
lazy fetching, 218
many-to-many
association, 217
maps, 219
one-to-many, 216
simple types, 218, 219
TransactionHistory
entity, 216
column customization, 191-194
embeddables, 206-209
fetching, 198
field/property access, 203
inheritance, 204-207
mapping enums, 198-201
mapping large objects, 196, 197
primary key generation
AUTO, 187
IDENTITY, 191
ID generation, 186-188
SEQUENCE, 191
TABLE generation, 187-190
user entity, 184, 185
wallet entity schema, 186
relationships/associations, 210
simplest unit, 182-184
single-valued relationship
cardinality, 210
many-to-one
relationship, 210-212
one-to-one
association, 213-215
TransactionHistory
entity, 211
temporal mapping, 194-196
transient fields, 202, 203
user schema diagram, 193
DDD, see Domain-Driven
Design (DDD)
DDL, see Data definition
language (DDL)
Deep Java Library (DJL), 579-581
Deep learning, 20, 581
Deeplearning4j (DL4J), 581-583
613
INDEX
Deployment patterns, 501
caching synchronization, 512
cache invalidation
message, 512
distributed solutions, 512
shared backing store, 512
configuration management, 506
ConfigMap, 506, 507
sensitive information, 507
server.xml, 507
high availability
configuration, 513-515
horizontal pod autoscaling, 510
Ingress resource, 504
logging/debugging
development-time, 520
log management, 519
production
environments, 520
remote debugging, 519
structured/generation, 519
maintenance/operations
automated recovery
scripts, 525
backup strategies, 523
data protection, 523
disaster recovery
planning, 524
documentation, 525
health management, 523
recovery time objectives
(RTOs), 524, 525
restore procedures, 524
persistent storage, 508-510
614
readiness/liveness probes,
514, 515
resource, 502, 503
scaling/high
availability, 510-515
service discovery/
networking, 503-505
session management, 510
centralization, 511
replication techniques, 511
session-less
architectures, 511
StatefulSets, 502
strategies, 520
blue-green deployments, 521
canary releases, 522
rolling updates, 521
volume type, 508
DJL, see Deep Java Library (DJL)
DL4J, see Deeplearning4j (DL4J)
Domain-Driven Design (DDD), 555
aggregates function, 61
architectural concepts, 57, 58
architectural decisions, 79-87
bounded contexts, 60
concepts
create, read, update, and
delete (CRUD), 63
entities, 62, 63
events, 68-71
principles/patterns, 70
repositories, 63
services, 64-68
WalletService interface, 64
INDEX
domain events, 61
entities, 60
layers (see Layered architecture)
principles/patterns, 59
repositories, 61
specifications, 58
technical/domain experts, 59
ubiquitous language, 59
value objects, 60
E
Eclipse Foundation Specification
Process (EFSP), 3
EFSP, see Eclipse Foundation
Specification
Process (EFSP)
EJBs, see Enterprise
JavaBeans (EJBs)
Enterprise JavaBeans (EJBs),
125, 126
F
Fault tolerance metrics, 412-414
Fault tolerance system
artificial intelligence, 598-601
asynchronous
class/method level, 380
component, 379
context handling, 381
exception handling, 381
implementation, 381
integration, 380
bulkhead annotation, 376
integration, 378
lifecycle management, 379
semaphore bulkhead
approach, 377
thread pool-style, 378
circuit breaker pattern
configuration options, 374
convertCurrency
method., 373-375
counting rules, 375
integration patterns, 375
normal operation, 372
open state, 372
recovery testing, 373
state management, 376
configuration, 382
dynamic properties, 383
effect, 384
hierarchical approach, 383
patterns, 382
core patterns
bulkhead approaches, 359
categories/solutions,
360, 361
electrical circuit
breakers, 358
fallback, 357
retry annotation, 358
timeouts, 358
distributed systems, 356, 357
fallback annotation, 361
advantages, 363
applyOn parameter, 362
615
INDEX
Fault tolerance system (cont.)
currency conversion service,
361, 362
fallbackConvert
method, 362
implementation, 363-365
jitter/delays, 370
maxDuration parameter, 371
@Retry annotation, 368, 369
rules, 370
scope/application, 371
@Timeout annotation,
365-368
G
GANs, see Generative Adversarial
Networks (GANs)
Generative Adversarial
Networks (GANs), 575
Generative Pre-trained
Transformer (GPT), 20
GPT, see Generative Pre-trained
Transformer (GPT)
H
HATEOS, see Hypermedia as
the Engine of Application
State (HATEOS)
Health checks
API structure, 428-430
HealthCheck interface, 429
HealthCheckResponse, 430
616
procedures, 429
statuses, 429
asynchronous, 451
CDI qualifiers
components, 430
JSON representation, 432
liveness, 433, 434
readiness, 431, 432
startup, 434-436
cloud environments, 428
cloud-native
applications, 442-450
CDI scope, 449
diagnostic information, 446
error handling, 447, 448
idempotent, 446
intervals/thresholds,
448, 449
monitoring, 449
quick execution, 443, 444
resource
consumption, 444-446
separate concerns, 442
side effects, 446
combination/
implementation, 436-438
dependency chain
validation, 450
Kubernetes, 452-455
overview, 427
producer methods, 438-442
progressive detail levels, 452
reporting system, 452
self-healing mechanisms, 451
INDEX
startup verification, 450
system resources, 451
HTTP, see Hypertext transfer
protocol (HTTP)
Hypermedia as the Engine of
Application State
(HATEOS), 278
Hypertext transfer protocol (HTTP)
@BeanParam/@QueryParam
annotation, 300-302
class-level annotations, 289
CreateUserRequest, 294
DefaultValue
annotation, 302-307
@DELETE method, 309
GET request, 297-299
message body reader, 289-291
message body writer,
291, 292
@PathParam annotation, 299
paths/methods, 282
POST requests, 288, 289, 295
@PUT method, 307-309
resource methods, 287
response data, 297
response object, 310-312
SearchResult class, 303
user implementation, 304
UserResponse class, 296
UserSearchRequest class,
300, 301
validation
specification, 293-297
I
IAM, see Identity and access
management (IAM)
Identity and access management
(IAM), 458, 464
Integration testing, 481
Inversion of Control (IoC), 18
container, 93
factory floor, 94
traditional programming, 92, 93
IoC, see Inversion of Control (IoC)
J
Jakarta EE, see Jakarta Enterprise
Edition (Jakarta EE)
Jakarta EE Specification
Process (JESP), 3, 6
Jakarta Enterprise Edition
(Jakarta EE)
AI (see Artificial
intelligence (AI))
AI/LLMs, 20
AI revolution, 20
architectural patterns (see
Architectural patterns)
CDI (see Contexts and
Dependency
Injection (CDI))
cloud-native application, 23
code-first approach, 19
configuration (see Configuration
management)
617
INDEX
Jakarta Enterprise
Edition (Jakarta EE) (cont.)
containerization, 40-44
core profile, 12, 13
DDD (see Domain-Driven
Design (DDD))
development/flexibility, 19
evolution, 25-27
features, 7-9
history, 4-6, 18
integration, 20
JPA (see Jakarta Persistence
API (JPA))
key features, 23
MicroProfile (see MicroProfile
project)
microservices, 37-40
objectives, 2
platform, 10
potential intersection, 20, 21
profiles, 9
resources, 19
REST (see Representational
State Transfer (REST))
specifications, 2, 3
Spring Framework, 17, 18
stages, 6
standardization/stability, 19
testing, 484-495
vendor lock-in, 19
web application, 10-12
Jakarta Persistence
API (JPA), 36, 535
broad categories, 179
618
data access operations, 260-266
definition, 180
Jakarta Data, 259, 260
JPQL (see Jakarta Persistence
Query Language (JPQL))
modeling (see Data modeling
process)
NoSQL (see Non-relational
(NoSQL) databases)
portability considerations, 267
querying data, 182
relational database
management
systems, 180
repository concepts, 259
runtime, 181
technologies, 269-271
template pattern, 260
Jakarta Persistence Query
Language (JPQL), 234
aggregate function, 240
BaseRepository’s
implementation, 235
from clause, 238, 239
criteria API, 243-247
dynamic queries, 240
execution, 240
find method, 235
named query, 241
passing parameters, 242
select clause, 237
setParameter method, 243
structure, 236
where clause, 239
INDEX
Jakarta RESTful Web
Services (JAX-RS), 37
Jakarta Server Faces (JSF), 535
Java Community
Process (JCP), 3, 13
Java 2 Platform Enterprise
Edition (J2EE), 2, 24
Java Naming and Directory
Interface (JNDI), 334
Java platform
AI/ML frameworks, 578-601
JavaScript Object Notation (JSON)
binding, 34
MediaType.APPLICATION_
JSON, 287
GROUPING, 254
Java Specification
Requests (JSRs), 3
Java Virtual Machine (JVM),
390, 579
JCP, see Java Community
Process (JCP)
J2EE, see Java 2 Enterprise
Edition (J2EE)
JESP, see Jakarta EE Specification
Process (JESP)
JNDI, see Java Naming and
Directory Interface (JNDI)
JPA, see Jakarta Persistence
API (JPA)
JSON Web Token (JWT), 458, 511
claim values, 475
configuration, 471-473
JsonWebToken interface,
472-474
objectives, 463
raw types, 475
requirements, 463
SecurityContext interface, 476
security process, 464
authentication, 464, 465
authorization, 469
Keycloak, 464, 465
propagation, 470
public key, 465-469
validation error
handling, 469
token-based security, 458-463
WalletResource, 471
WalletService, 473
JSRs, see Java Specification
Requests (JSRs)
JVM, see Java Virtual
Machine (JVM)
JWTs, see JSON Web Tokens (JWTs)
K
Key performance
indicators (KPIs), 516
KPIs, see Key performance
indicators (KPIs)
Kubernetes integration, 452
configuration strategies, 453
deployment strategies, 455
failures trigger action, 454
619
INDEX
Kubernetes integration (cont.)
monitoring/
troubleshooting, 455
probe mapping, 453
resource consideration, 454
startup optimization, 454
zero-downtime
deployments, 454
L
Large language models (LLMs), 20,
591, 602
Layered architecture
advantages, 73
application/service
layer, 77, 78
domain layer, 78
domain/persistence
layers, 72
maintenance/update
processes, 73
modification/replacement, 74
persistence layer, 78
presentation layer, 75-77
responsibilities/concerns, 72
reusability, 74
separation concerns, 73
technologies/adaptation, 74
testing, 74
visual representation, 72
LLMs, see Large language
models (LLMs)
620
M
Machine learning (ML), 20
AI (see Artificial
intelligence (AI))
architectural framework, 577
Deep Java Library (DJL),
579-581
definition, 575
domain-specific models, 577
foundation, 576
generative models, 575
models function, 575
neural networks, 581-583
predictive models, 575
reinforcement learning, 578
supervised learning, 577
thinking models, 576
unsupervised learning, 578
Mean Time To
Resolution (MTTR), 388
Metrics
annotation, 392
CDI stereotypes, 413, 414
ConcurrentGauge, 395-397
convertCurrency method, 399
@Counted, 393
@Gauge metric, 397, 398
injection, 405
histogram, 405-407
manual
instantiation, 408-410
metadata, 409-411
INDEX
metered annotation, 398-400
monitoring applications,
516, 517
parameters, 392, 393
@SimplyTimed
annotation, 400-402
specifications, 411-413
@Timed metric, 402-404
MicroProfile project
benefits, 17
config specification,
337-346
failure (see Fault
tolerance system)
health check, 427
Java enterprise ecosystems, 14
JWT (see JSON Web
Token (JWT))
key specifications, 15-17
relationship, 14
REST client, 317-322
telemetry metrics, 390-414
Microservices
architecture, 40
challenges/solution, 39
features, 37
implementation, 38, 39
inter-service
communication, 39
key principles, 37
Microservices architectures
advantages
focused codebase, 552
scale independent, 552
team autonomy, 552
technologies, 552
boundaries, 549
characteristics, 548
components, 548
disadvantages
data management, 553
distributed systems, 552
independent services, 552
infrastructure, 553
independent deployment, 548
requirements, 549-551
REST specification, 549
scenarios/features, 553-556
services, 549
structure/characteristics, 542
Modulithic architecture
advantages
adoption, 545
balanced complexity, 544
deployment coupling, 545
evolutionary
deployment, 544
focused codebase, 552
individual modules, 544
module boundaries, 545
reusability, 544
scalability, 545
scale independent, 552
share resources, 545
simplifying operation, 544
team autonomy, 552
technologies, 552
testability, 544
621
INDEX
Modulithic architecture (cont.)
approaches, 515-518
event-based
communication, 543
interface boundaries, 543
metrics collection, 516
application, 516
distributed tracing, 518
runtime, 517
migration, 559
module organization, 543
pointers, 546-548
resource management, 543
simplicity/efficiency, 541
observability (see Observability)
prometheus, 390
telemetry specification, 390
Monolithic architecture
advantages, 536
data management, 537
development process, 536
performance, 537
testing and debugging, 537
codebase complexity, 538
deployment constraints, 538
migration, 559
operational resources, 541
rapid development process, 540
requirements, 540
scaling limitations, 539
small-medium application, 540
structure/characteristics
components/
functionalities, 536
622
data sources, 535
functional components, 534
service layer, 535
web layer, 534
technologies, 539
traditional approach, 534
MTTR, see Mean Time To
Resolution (MTTR)
N
Natural language
processing (NLP), 587
CoreNLP, 587-589
LangChain4j, 591-594
OpenNLP, 589-591
TextAnalysisService class, 588
N-dimensional arrays (ND4J), 583
ND4J, see N-dimensional
arrays (ND4J)
Network File System (NFS), 508
Neural networks
deep learning, 581
Deeplearning4j (DL4J), 581-583
Deep Netts, 584
drools serves, 586, 587
expert systems, 584
ND4J features, 584
OptaPlanner, 584
NFS, see Network File System (NFS)
NLP, see Natural language
processing (NLP)
Non-relational (NoSQL)
databases, 260
INDEX
annotations
@Column, 253
@Convert, 254, 255
@Embeddable, 253, 254
@Entity, 252
@Id, 252
data access code, 255
CRUD operations, 256
database types, 258
navigation, 258, 259
template pattern, 256-258
entity classes
annotations, 252
persistent fields, 250
types, 250
user entity mapping, 251, 252
goals, 248
integration, 266
primary categories, 248-250
relational paradigm, 247
NoSQL databases, see Non­
relational (NoSQL)
databases
O
Object-relational mapping
(ORM), 535
Observability
deep dive telemetry, 418-425
fundamental pillars, 389
MicroProfile specification, 417
monitoring (see Monitoring
applications)
traditional monitoring, 388
Object-relational
mapping (ORM), 248
OCI, see Open Container
Initiative (OCI)
Open Container Initiative (OCI), 41
OpenTelemetry (OTel), 44
OpenTelemetry metrics, 387
ORM, see Object-relational
mapping (ORM)
OTel, see OpenTelemetry (OTel)
P, Q
PCA, see Principal component
analysis (PCA)
PDBs, see Pod disruption
budget (PDBs)
Persistence
comparison matrix, 267-269
context, 221
data source, 220
entities, 220
BaseRepository, 224-226
callback methods, 231, 232
cascade operations, 230, 231
computeAge method, 232
entity listeners, 232-234
EntityManager, 223
merge method, 229, 230
PostLoad callback, 231
transaction rollback,
226-229
UserCredentials entity, 228
623
INDEX
Persistence (cont.)
UserRepository, 225
UserService, 226
validation constraints, 228
EntityManager, 222
implementation, 182
jwallet application, 220
transactional boundaries, 222
unit, 220, 221
Persistence options, 179
Persistent Volume Claims (PVCs),
508, 509
Persistent volumes (PVs), 508, 509
Plain old Java objects (POJOs), 17
Pod disruption budget (PDBs),
513, 514
POJOs, see Plain old Java
objects (POJOs)
Principal component
analysis (PCA), 578
PVCs, see Persistent Volume
Claims (PVCs)
PVs, see Persistent volumes (PVs)
R
RAG, see Retrieval-augmented
generation (RAG)
Recovery time
objectives (RTOs), 525
Reinforcement learning, 578
Representational State
Transfer (REST), 75, 275
architectural principles, 277
624
cacheability, 277
HATEOS, 278
resource-based
design, 277
statelessness, 277
CDI qualifiers, 127
client resources
GET request, 317
path method, 316
POST/GET requests, 315
post method, 317
WebTarget, 314, 315
design principles, 283
evolution
content negotiation, 282
response encapsulation, 281
versioning, 280
exception mapping
implementation, 312
toResponse method, 313
HTTP handling/data
transformation, 276
MicroProfile client
ApiLayerConvert
Request, 321
ApiLayerConvert
Response, 321
authentication, 319
GET methods, 318
RateService method,
319, 320
return data, 322
specification, 317
modeling services, 276
INDEX
OpenAPI specification, 322-329
resource naming patterns, 278
anti-patterns, 279
collections, 278
deep nesting, 280
implementation details, 279
inconsistencies, 280
query parameters/
metadata, 279
URL paths, 279
verb-based actions, 280
resource organization
getClasses method, 284-286
hierarchical
organization, 283
HTTP method, 287-312
root/base path, 284
UserResource class, 286, 287
versioning strategies, 286
user resource, 282, 283
web browsers/mobile
apps, 275
REST, see Representational
State Transfer (REST)
RESTful Web Services
(JAX-RS), 34, 75
RTOs, see Recovery time
objectives (RTOs)
Retrieval-augmented
generation (RAG), 592
S
Security, 458
sendMessage method, 132
Service provider
interface (SPI), 96
SPI, see Service provider
interface (SPI)
Supervised learning, 577
T
TCK, see Test Compatibility
Kit (TCK)
Telemetry metrics
data collection, 415
deep dive
agent-based
instrumentation, 422
automatic instruments, 419
batch span processor
(bsp), 424
configuration
options, 423-425
export configuration, 424
manual instrumentation,
419-422
OpenTelemetry, 418
RateService, 421
resource attributes, 423
setup/configuration, 418, 419
distributed tracing, 414
metrics (see Metrics)
MicroProfile specification, 416
integration, 416
scope/target audience, 417
standards-based
approach, 416
625
INDEX
Telemetry metrics (cont.)
OpenTelemetry, 415
unified standard, 415
vendor-neutral
approach, 416
specification, 390
structure, 390
application, 391
base metrics, 390
data format, 391
registry, 391
vendor, 391
Test Compatibility Kit (TCK), 6
Testing (TestContainers)
absence of errors, 484
cluster, 483
context-dependent activity, 484
defects, 483
definition, 480
enterprise applications, 483
frontend automated testing, 482
functional test, 481
integration, 481
integration tests, 479
Jakarta EE, 484-495
components, 485, 486
createWallet, 492
DockerCompose
Container, 491
end-to-end test, 493
integration testing, 490-495
JUnit, 486
Mockito, 486-490
unit testing, 485, 486
626
WalletServiceTest, 488
performance test, 481
pesticide principle, 484
principles, 482
smoke test, 482
time/money, 483
unit test, 480
Token-based authentication
claims/body, 459
header, 459
signature, 460-463
Twelve-Factor App
admin/management tasks, 31
codebases/dependencies, 29
concurrency, 30
configuration, 29
Dev/Prod Parity, 30
factors, 29
logging framework, 31, 32
methodology, 29
port binding, 30
stateless processes, 30
treat backing services, 30
U
Unit testing, 480
Unsupervised learning, 578
V, W, X, Y, Z
VAEs, see Variational
Autoencoders (VAEs)
Variational Autoencoders
(VAEs), 575
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )