SlideShare a Scribd company logo
1 of 81
To inject or not to inject : CDI is the question by  a ntonio  g oncalves
Welcome to a type-safe injection journey
Antonio Goncalves ,[object Object]
Author (Java EE 5 and Java EE 6)
JCP expert member (Java EE 6, Java EE 7)
Co-leader of the Paris JUG
Les Cast Codeurs podcast
Java Champion
[object Object],[object Object]
Dependency Injection
@Inject & CDI
And that's it
Inversion of control ,[object Object]
The control of : ,[object Object]
lifecycle
configuration ,[object Object]
...not the component itself
It brings loose coupling
Own deps Own config Own lifecycle Dependencies injected Config injected Lifecycle Managed from outside
Own deps Own config Own lifecycle Dependencies injected Config injected Lifecycle Managed from outside
Own deps Own config Own lifecycle Dependencies injected Config injected Lifecycle Managed from outside
Example of dependency
The good old  new public class ItemService { private IsbnGenerator  isbnGenerator ; public ItemService() { this. isbnGenerator  =  new IsbnGenerator() ; } public Book createBook(Book book) { ... book.setIsbn( isbnGenerator .generateNumber()); } }
What's wrong with that ? ,[object Object]
Impossible to MOCK if needed ,[object Object],[object Object]
Creating an instance, opening, closing
[object Object],[object Object]
Decouples dependent components ,[object Object],[object Object],[object Object]
How to choose implementation?
Constructor (or setter) injection public class ItemService { private NumberGenerator  numberGenerator ; public ItemService(NumberGenerator  numberGenerator ) { this.numberGenerator = numberGenerator ; } public Book createBook(Book book) { ... book.setIsbn( numberGenerator .generateNumber()); } }
With the good old  new  again // With constructor injection ItemService itemService = new ItemService( new IsbnGenerator() ); ItemService itemService = new ItemService( new IssnGenerator() ); // With setter injection ItemService itemService = new ItemService(); itemService.setNumberGenerator( new IsbnGenerator() ); itemService.setNumberGenerator( new IssnGenerator() );
Using factories ,[object Object]
Factory design pattern (GoF)
Everywhere in Java ,[object Object]
java.util.Arrays#asList()
java.sql.DriverManager#getConnection()
java.lang.Class#newInstance()
java.lang.Integer#valueOf()
With a Factory public class ItemServiceFactory { public ItemService  newIsbnGenerator()  { return new ItemService( new IsbnGenerator() ); } public ItemService  newIssnGenerator()  { return new ItemService( new IssnGenerator() ); } } // Client ItemService itemService =  new ItemServiceFactory(). newIsbnGenerator ();
Another pattern: Service Locator ,[object Object]
Used to find services
May reside in the same application, machine or network
JNDI is a perfect service locator ItemService itemService =  new  ServiceLocator() .get(ā€ IsbnGeneratorService ā€);
All that is constructing by hand // new() public ItemService() { this. isbnGenerator  =  new IsbnGenerator() ; } // Factory ItemService itemService =  new ItemServiceFactory(). newIsbnGenerator (); // Service locator ItemService itemService =  new  ServiceLocator() .get(ā€ IsbnGeneratorService ā€);
Give control to an injector ,[object Object]
Creating, assembling and wiring done by an external framework with Provides
Dependency injector ,[object Object]
Spring framework
Pico container
Nano container
Apache Hivemind
Seam
Google Guice
Contexts and Dependency Injection (CDI)
A bit of history May 1998 Project JPE Dec 1999 J2EE 1.2 Servlet/JSP EJB JMS RMI/IIOP Sept 2001 J2EE 1.3 CMP JCA Nov 2003 J2EE 1.4 WS Management Deployment May 2006 Java EE 5 Annotations EJB 3 JPA 1.0 WS-* JSF Q4 2009 Java EE 6 EJB 3.1 JPA 2.0 Servlet 3.0 JSF 2.0 JAX-RS 1.1 CDI 1.0 @Inject Bean ValidatĀ° Web Profile Managed Bean Resource  injection Dependency  injection
Resource injection in EE 5 ,[object Object]
Dependency injection in EE 6 ,[object Object]
DI (aka @Inject) JSR 330 ,[object Object]
ā€¦ and even outside Java EE
EE 5 resource injection @EJB @EJB @EJB @Resource @PersistenceContext
EE 6 dependency injection @Inject @Inject @Inject @Inject @Inject @Inject @Inject @Resource @PersistenceContext @Inject
2 specs to archieve it ,[object Object]
JSR 330
javax.inject
@Inject
@Named
@Singleton
@Qualifier
@Scope ,[object Object]
JSR 299
javax.enterprise.context
Alternatives
Producers
Scopes & context
Stereotypes
Decorators, Events
Extensions
Injection with @Inject
@Inject @WebServlet(urlPatterns = "/itemServlet") public class ItemServlet extends HttpServlet { @Inject private  IsbnGenerator  numberGenerator; ... book.setIsbn( isbnGenerator.generateNumber() ); } public class  IsbnGenerator  { public String generateNumber () { return "13-84356-" + nextNumber()); } } Injection point POJO Servlet
What's needed to make it work ? ,[object Object]
CDI

More Related Content

What's hot

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
Ā 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMashleypuls
Ā 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modulesRafael Winterhalter
Ā 
Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„
Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„
Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„knight1128
Ā 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to missAndres Almiray
Ā 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
Ā 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise EditionFrancesco Nolano
Ā 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac pluginOleksandr Radchykov
Ā 
Spring & Hibernate
Spring & HibernateSpring & Hibernate
Spring & HibernateJiayun Zhou
Ā 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
Ā 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
Ā 
Spring Boot
Spring BootSpring Boot
Spring BootJiayun Zhou
Ā 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
Ā 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
Ā 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma Christopher Bartling
Ā 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with SwiftRay Deck
Ā 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
Ā 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
Ā 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
Ā 

What's hot (20)

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
Ā 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
Ā 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
Ā 
Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„
Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„
Jdk(java) 7 - 6 źø°ķƒ€źø°ėŠ„
Ā 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
Ā 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Ā 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
Ā 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
Ā 
Spring & Hibernate
Spring & HibernateSpring & Hibernate
Spring & Hibernate
Ā 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
Ā 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
Ā 
Spring Boot
Spring BootSpring Boot
Spring Boot
Ā 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Ā 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
Ā 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Ā 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with Swift
Ā 
Angular testing
Angular testingAngular testing
Angular testing
Ā 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
Ā 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
Ā 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
Ā 

Similar to To inject or not to inject: CDI is the question

ęƔXMLę›“å„½ē”Øēš„Java Annotation
ęƔXMLę›“å„½ē”Øēš„Java AnnotationęƔXMLę›“å„½ē”Øēš„Java Annotation
ęƔXMLę›“å„½ē”Øēš„Java Annotationjavatwo2011
Ā 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 referenceGiacomo Veneri
Ā 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan HinojosaDan Hinojosa
Ā 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
Ā 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughMahfuz Islam Bhuiyan
Ā 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0Matt Raible
Ā 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
Ā 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
Ā 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
Ā 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
Ā 
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...GreeceJS
Ā 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
Ā 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
Ā 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
Ā 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
Ā 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
Ā 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
Ā 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
Ā 

Similar to To inject or not to inject: CDI is the question (20)

ęƔXMLę›“å„½ē”Øēš„Java Annotation
ęƔXMLę›“å„½ē”Øēš„Java AnnotationęƔXMLę›“å„½ē”Øēš„Java Annotation
ęƔXMLę›“å„½ē”Øēš„Java Annotation
Ā 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 reference
Ā 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
Ā 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Ā 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
Ā 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
Ā 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
Ā 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Ā 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Ā 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Ā 
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
Ā 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journey
Ā 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
Ā 
Bean Intro
Bean IntroBean Intro
Bean Intro
Ā 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
Ā 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Ā 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Ā 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
Ā 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
Ā 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
Ā 

Recently uploaded

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
Ā 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
Ā 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
Ā 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
Ā 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
Ā 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
Ā 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
Ā 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
Ā 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
Ā 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
Ā 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
Ā 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
Ā 

Recently uploaded (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Ā 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
Ā 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
Ā 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
Ā 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
Ā 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Ā 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Ā 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
Ā 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
Ā 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Ā 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Ā 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
Ā 

To inject or not to inject: CDI is the question

  • 1. To inject or not to inject : CDI is the question by a ntonio g oncalves
  • 2. Welcome to a type-safe injection journey
  • 3.
  • 4. Author (Java EE 5 and Java EE 6)
  • 5. JCP expert member (Java EE 6, Java EE 7)
  • 6. Co-leader of the Paris JUG
  • 9.
  • 13.
  • 14.
  • 16.
  • 18. It brings loose coupling
  • 19. Own deps Own config Own lifecycle Dependencies injected Config injected Lifecycle Managed from outside
  • 20. Own deps Own config Own lifecycle Dependencies injected Config injected Lifecycle Managed from outside
  • 21. Own deps Own config Own lifecycle Dependencies injected Config injected Lifecycle Managed from outside
  • 23. The good old new public class ItemService { private IsbnGenerator isbnGenerator ; public ItemService() { this. isbnGenerator = new IsbnGenerator() ; } public Book createBook(Book book) { ... book.setIsbn( isbnGenerator .generateNumber()); } }
  • 24.
  • 25.
  • 26. Creating an instance, opening, closing
  • 27.
  • 28.
  • 29. How to choose implementation?
  • 30. Constructor (or setter) injection public class ItemService { private NumberGenerator numberGenerator ; public ItemService(NumberGenerator numberGenerator ) { this.numberGenerator = numberGenerator ; } public Book createBook(Book book) { ... book.setIsbn( numberGenerator .generateNumber()); } }
  • 31. With the good old new again // With constructor injection ItemService itemService = new ItemService( new IsbnGenerator() ); ItemService itemService = new ItemService( new IssnGenerator() ); // With setter injection ItemService itemService = new ItemService(); itemService.setNumberGenerator( new IsbnGenerator() ); itemService.setNumberGenerator( new IssnGenerator() );
  • 32.
  • 34.
  • 39. With a Factory public class ItemServiceFactory { public ItemService newIsbnGenerator() { return new ItemService( new IsbnGenerator() ); } public ItemService newIssnGenerator() { return new ItemService( new IssnGenerator() ); } } // Client ItemService itemService = new ItemServiceFactory(). newIsbnGenerator ();
  • 40.
  • 41. Used to find services
  • 42. May reside in the same application, machine or network
  • 43. JNDI is a perfect service locator ItemService itemService = new ServiceLocator() .get(ā€ IsbnGeneratorService ā€);
  • 44. All that is constructing by hand // new() public ItemService() { this. isbnGenerator = new IsbnGenerator() ; } // Factory ItemService itemService = new ItemServiceFactory(). newIsbnGenerator (); // Service locator ItemService itemService = new ServiceLocator() .get(ā€ IsbnGeneratorService ā€);
  • 45.
  • 46. Creating, assembling and wiring done by an external framework with Provides
  • 47.
  • 52. Seam
  • 54. Contexts and Dependency Injection (CDI)
  • 55. A bit of history May 1998 Project JPE Dec 1999 J2EE 1.2 Servlet/JSP EJB JMS RMI/IIOP Sept 2001 J2EE 1.3 CMP JCA Nov 2003 J2EE 1.4 WS Management Deployment May 2006 Java EE 5 Annotations EJB 3 JPA 1.0 WS-* JSF Q4 2009 Java EE 6 EJB 3.1 JPA 2.0 Servlet 3.0 JSF 2.0 JAX-RS 1.1 CDI 1.0 @Inject Bean ValidatĀ° Web Profile Managed Bean Resource injection Dependency injection
  • 56.
  • 57.
  • 58.
  • 59. ā€¦ and even outside Java EE
  • 60. EE 5 resource injection @EJB @EJB @EJB @Resource @PersistenceContext
  • 61. EE 6 dependency injection @Inject @Inject @Inject @Inject @Inject @Inject @Inject @Resource @PersistenceContext @Inject
  • 62.
  • 69.
  • 79. @Inject @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject private IsbnGenerator numberGenerator; ... book.setIsbn( isbnGenerator.generateNumber() ); } public class IsbnGenerator { public String generateNumber () { return &quot;13-84356-&quot; + nextNumber()); } } Injection point POJO Servlet
  • 80.
  • 81. CDI
  • 82.
  • 84. @Inject @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject private IsbnGenerator numberGenerator; ... book.setIsbn(isbnGenerator.generateNumber()); } public class IsbnGenerator { public String generateNumber () { return &quot;13-84356-&quot; + nextNumber()); } }
  • 85. @Default @Inject @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject @Default private IsbnGenerator numberGenerator; ... book.setIsbn(isbnGenerator.generateNumber()); } @Default public class IsbnGenerator { public String generateNumber () { return &quot;13-84356-&quot; + nextNumber()); } } Every bean has a @Default qualifier Every injection point has a @Default qualifier
  • 86. Use your own qualifier @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject @MyOwnQualifier private IsbnGenerator numberGenerator; ... book.setIsbn(isbnGenerator.generateNumber()); } @MyOwnQualifier public class IsbnGenerator { public String generateNumber () { return &quot;13-84356-&quot; + nextNumber()); } }
  • 87. @MyOwnQualifier @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface MyOwnQualifier { }
  • 90. Defining the qualifiers @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface EightDigits { } @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface ThirteenDigits { }
  • 91. Defining the beans @EightDigits public class IssnGenerator implements NumberGenerator { public String generateNumber() { return &quot;8-&quot; + nextNumber(); } } @ThirteenDigits public class IsbnGenerator implements NumberGenerator { public String generateNumber() { return &quot;13-84356-&quot; + nextNumber(); } }
  • 92. Injection points @Path (&quot;/items&quot;) @ManagedBean public class ItemRestService { @Inject @EightDigits private NumberGenerator numberGenerator; ... } @WebServlet (urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject @ThirteenDigits private NumberGenerator numberGenerator; ... } Strong typing No strings Loose coupling No reference to the implementation
  • 93.
  • 94. 13, 8 digits but also 3, 7, 16, 19, 22, 26...
  • 95. Use qualifiers with enumerations
  • 96. Defining the qualifier & enum @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface NumberOfDigits { Digits value(); } public enum Digits { TWO, EIGHT, TEN, THIRTEEN }
  • 97. Defining the beans @NumberOfDigits(Digits.EIGHT) public class IssnGenerator implements NumberGenerator { public String generateNumber() { return &quot;8-&quot; + nextNumber(); } } @NumberOfDigits(Digits.THIRTEEN) public class IsbnGenerator implements NumberGenerator { public String generateNumber() { return &quot;13-84356-&quot; + nextNumber(); } }
  • 98. Injection points @Path(&quot;/items&quot;) @ManagedBean public class ItemRestService { @Inject @NumberOfDigits(Digits.EIGHT) private NumberGenerator numberGenerator; ... } @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject @NumberOfDigits(Digits.THIRTEEN) private NumberGenerator numberGenerator; ... }
  • 99.
  • 101. Setter
  • 102. Field injection @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { @Inject @ThirteenDigits private NumberGenerator numberGenerator; @Inject private ItemEJB itemEJB; ... }
  • 103. Constructor injection @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { private NumberGenerator numberGenerator; private ItemEJB itemEJB; @Inject public ItemServlet( @ThirteenDigits NumberGenerator numberGenerator, ItemEJB itemEJB) { this.numberGenerator = numberGenerator; this.itemEJB = itemEJB; } ... }
  • 104. Setter injection @WebServlet(urlPatterns = &quot;/itemServlet&quot;) public class ItemServlet extends HttpServlet { private NumberGenerator numberGenerator; private ItemEJB itemEJB; @Inject public void setNumberGenerator( @ThirteenDigits NumberGenerator numberGenerator) { this.numberGenerator = numberGenerator; } @Inject public void setItemEJB(ItemEJB itemEJB) { this.itemEJB = itemEJB; } }
  • 105.
  • 106.
  • 107.
  • 108. Have you seen any XML so far ?
  • 109.
  • 111. By default, alternative beans are disabled
  • 112. Enable them with beans.xml file
  • 113. Alternative to @ThirteenDigits @Alternative @ThirteenDigits public class MockGenerator implements NumberGenerator { public String generateNumber() { return &quot;MOCK-&quot; + nextNumber(); } }
  • 114. Alternative to both @Alternative @ThirteenDigits @EightDigits public class MockGenerator implements NumberGenerator { public String generateNumber() { return &quot;MOCK-&quot; + nextNumber(); } } @Inject @ThirteenDigits private NumberGenerator numberGenerator;
  • 115. beans.xml <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <beans xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot; http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd&quot;> <alternatives> <class>org.agoncal.cdi.MockGenerator</class> </alternatives> </beans>
  • 116. Does this look too verbose ? @Alternative @ThirteenDigits @EightDigits public class MockGenerator implements NumberGenerator { public String generateNumber() { return &quot;MOCK-&quot; + nextNumber(); } }
  • 117. Use stereotypes @MyMock public class MockGenerator implements NumberGenerator { public String generateNumber() { return &quot;MOCK-&quot; + nextNumber(); } } @Stereotype @Retention(RUNTIME) @Target(TYPE) @Alternative @ThirteenDigits @EightDigits public @interface MyMock {}
  • 118.
  • 119.
  • 120.
  • 121. So, we only inject beans ?
  • 122.
  • 123. expose any JDK class as a bean
  • 124. Produce an injectable String public class PrefixGenerator { @Produces @ThirteenDigits public String getIsbnPrefix() { return &quot;13-84356&quot;; } @Produces @EightDigits public String getIssnPrefix() { return &quot;8&quot;; } }
  • 125. Inject the produced String @ThirteenDigits public class IsbnGenerator implements NumberGenerator { @Inject @ThirteenDigits private String prefix ; public String generateNumber() { return prefix + &quot;-&quot; + nextNumber(); } } Bean String
  • 126.
  • 127. a Principal for the current caller identity
  • 128. default Bean Validation ValidationFactory
  • 129.
  • 130. Produce an EntityManager public class DatabaseProducer { @Produces @PersistenceContext(unitName = &quot;cdiPU&quot;) @BookStoreDatabase private EntityManager em; } @Stateless public class ItemEJB { @Inject @BookStoreDatabase private EntityManager em; ... }
  • 131. Produce a FacesContext public class FacesContextProducer { @Produces @RequestScoped FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } }
  • 132. Produce JMS endpoints public class OrderResources { @Resource (name = &quot;jms/ConnectionFactory&quot;) private ConnectionFactory connectionFactory; @Resource (name = &quot;jms/OrderQueue&quot;) private Queue orderQueue; @Produces @OrderConnection public Connection createOrderConnection() { return connectionFactory.createConnection(); } @Produces @OrderSession public Session createOrderSession( @OrderConnection Connection conn){ return conn.createSession(true, Session.AUTO_ACKNOWLEDGE); } ... }
  • 133. Consume JMS endpoints @Inject @OrderSession QueueSession orderSession; public void sendMessage() { MapMessage msg = orderSession .createMapMessage(); msg.setLong(&quot;orderId&quot;, order.getId()); ... producer.send(msg); }
  • 134. Can I use all that from a JSF page ?
  • 135.
  • 136. Gives it a name (a String)
  • 137. Most commonly from a JSF view
  • 138. Non type safe dependency injection
  • 139. Any bean can be named
  • 140. Do we still need JSF managed beans ?
  • 141. Default name @Named public class IsbnGenerator { public String generateNumber() { return &quot;13-84356-&quot; + nextNumber(); } } <h:outputLabel value=&quot; #{isbnGenerator.generateNumber} &quot;/>
  • 142. A different name @Named(&quot; generator &quot;) public class IsbnGenerator { public String generateNumber() { return &quot;13-84356-&quot; + nextNumber(); } } <h:outputLabel value=&quot;#{ generator .generateNumber}&quot;/>
  • 143. Mix a producer and a default name public class IsbnGenerator { @Produces @Named public String generateNumber() { return &quot;13-84356-&quot; + nextNumber(); } } <h:outputLabel value=&quot;#{ generateNumber }&quot;/>
  • 144. Mix a producer and a name public class IsbnGenerator { @Produces @Named(&quot; isbnNumber &quot;) public String generateNumber() { return &quot;13-84356-&quot; + nextNumber(); } } <h:outputLabel value=&quot;#{ isbnNumber }&quot;/>
  • 145. How can I have all these goodies ?
  • 146.
  • 147. Bootstrap CDI in several environments
  • 148.
  • 149. Tomcat 6.x / 7.x
  • 150.
  • 152.
  • 153. Only DI is supported (JSR 330)
  • 154. Not CDI (JSR 299)
  • 155. You can replace @Autowired with @Inject
  • 156.
  • 159.
  • 161. Events
  • 162.
  • 163.
  • 166.
  • 167.
  • 169. Better support for CDI in certain EE components
  • 171. ...
  • 172.
  • 174.
  • 179.
  • 180. Noncommercial ā€” You may not use this work for commercial purposes.
  • 181. Share Alike ā€” If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.