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-forkjoin
knight1128
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
knight1128
 
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
Jiayun Zhou
 

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

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 

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

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

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.