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
 
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
 
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
 
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
 
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 journeyThiago “Fred” Porciúncula
 
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

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

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.