SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Injection in CDI
in 15 minutes
by antonio goncalves
@agoncal
Antonio Goncalves

antonio goncalves

2
History of CDI
antonio goncalves

4
History of CDI

antonio goncalves

5
@Inject
Dependency Injection

antonio goncalves

7
Attributes
@Path("/items")
public class ItemRestService {
@Inject
private IsbnGenerator numberGenerator;
@Inject
private ItemEJB itemEJB;

// ...
}
antonio goncalves

8
Constructor
@Path("/items")
public class ItemRestService {
private IsbnGenerator numberGenerator;
private ItemEJB itemEJB;
@Inject
public ItemRestService(IsbnGenerator numberGenerator,
ItemEJB itemEJB) {
this.numberGenerator = numberGenerator;
this.itemEJB = itemEJB;
}

// ...
}
antonio goncalves

9
Setter
@Path("/items")
public class ItemRestService {
private IsbnGenerator numberGenerator;
private ItemEJB itemEJB;
@Inject
public void setNumberGenerator(IsbnGenerator gen) {
this.numberGenerator = gen;
}
@Inject
public void setItemEJB(ItemEJB itemEJB) {
this.itemEJB = itemEJB;
}
// ...
}
antonio goncalves

10
Ambiguous Dependency Injection

antonio goncalves

11
Ambiguous Dependency Injection

antonio goncalves

12
Qualifiers
Type Safe Dependency Injection

antonio goncalves

14
Qualifier
@Path("/items")
public class ItemRestService {
@Inject @ThirteenDigits
private NumberGenerator numberGenerator;
@Inject
private ItemEJB itemEJB;

// ...
}
antonio goncalves

15
Qualifier and Bean
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD, PARAMETER})
public @interface ThirteenDigits { }

@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {
@Override
public String generateNumber() {
return "13-" + Math.abs(new Random().nextInt());
}
}

antonio goncalves

16
Qualifier with Attributes
@Path("/items")
public class ItemRestService {
@Inject @NumberDigits(Digits.Thirteen, true)
private NumberGenerator numberGenerator;
@Inject
private ItemEJB itemEJB;

// ...
}
antonio goncalves

17
Multiple Qualifiers
@Path("/items")
public class ItemRestService {
@Inject @ThirteenDigits @Odd
private NumberGenerator numberGenerator;
@Inject
private ItemEJB itemEJB;

// ...
}
antonio goncalves

18
Qualifier and Bean
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD, PARAMETER})
public @interface Odd { }

@ThirteenDigits @Odd
public class IsbnGenerator implements NumberGenerator {
@Override
public String generateNumber() {
return "13-" + Math.abs(new Random().nextInt());
}
}

antonio goncalves

19
@Default
@Any
@Named
Programmatic Lookup
@Path("/items")
public class ItemRestService {
@Inject @ThirteenDigits
private Instance<NumberGenerator> numberGenerator;
@Inject
private ItemEJB itemEJB;
public String getISBN() {
return numberGenerator.get().generateNumber();
}

// ...
}
antonio goncalves

21
Programmatic Lookup
@Path("/items")
public class ItemRestService {
@Inject @Any
private Instance<NumberGenerator> numberGenerators;
@Inject
private ItemEJB itemEJB;
public void generateNumbers() {
for(NumberGenerator generator: numberGenerators) {
display(generator.generateNumber());
}
}
// ...
}
antonio goncalves

22
Producers
Injectable ?
@Path("/items")
public class ItemRestService {
@PersistenceContext(unitName = "myPU")
private EntityManager em;
// ...
}

antonio goncalves

24
Injectable ?
@Path("/items")
public class ItemRestService {
@Inject(unitName = "myPU")
private EntityManager em;
// ...
}

antonio goncalves

25
Injectable ?
@Path("/items")
public class ItemRestService {
@Inject(unitName = "myPU")
private EntityManager em;
// ...
}

antonio goncalves

26
Inject with Qualifier
@Path("/items")
public class ItemRestService {
@Inject @Item
private EntityManager em;
// ...
}

antonio goncalves

27
Produce it
@Path("/items")
public class ItemRestService {
@Inject @Item
private EntityManager em;
// ...
}
public class DatabaseProducer {
@Produces
@PersistenceContext(unitName = "myPU")
@Item
private EntityManager em;
}
antonio goncalves

28
Strong Typing
Loose coupling
</>
CDI is Much More !

antonio goncalves

31
Thanks
www.antoniogoncalves.org
antonio.goncalves@gmail.com
@agoncal
@devoxxfr
@lescastcodeurs
Q&A
Creative Commons
●

●

●

Attribution — You must attribute the work in
the manner specified by the author or licensor
(but not in any way that suggests that they
endorse you or your use of the work).
Noncommercial — You may not use this work for
commercial purposes.
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.
antonio goncalves

34

Weitere ähnliche Inhalte

Was ist angesagt?

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
CDI do básico ao avançado
CDI do básico ao avançadoCDI do básico ao avançado
CDI do básico ao avançado
Alberto Souza
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
lcbj
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
Stephan Hochdörfer
 

Was ist angesagt? (20)

Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 
Unit Testing in Kotlin
Unit Testing in KotlinUnit Testing in Kotlin
Unit Testing in Kotlin
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書く
 
Maze
MazeMaze
Maze
 
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
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017
 
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
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 
CDI do básico ao avançado
CDI do básico ao avançadoCDI do básico ao avançado
CDI do básico ao avançado
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
 
Qe Reference
Qe ReferenceQe Reference
Qe Reference
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
 

Andere mochten auch

Lightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPALightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPA
mh0708
 
Seven Points for Applying Java EE 7
Seven Points for Applying Java EE 7Seven Points for Applying Java EE 7
Seven Points for Applying Java EE 7
Hirofumi Iwasaki
 

Andere mochten auch (17)

Future of Java EE with SE 8 (revised)
Future of Java EE with SE 8 (revised)Future of Java EE with SE 8 (revised)
Future of Java EE with SE 8 (revised)
 
Java EE 6 Adoption in One of the World's Largest Online Financial Systems (fo...
Java EE 6 Adoption in One of the World's Largest Online Financial Systems (fo...Java EE 6 Adoption in One of the World's Largest Online Financial Systems (fo...
Java EE 6 Adoption in One of the World's Largest Online Financial Systems (fo...
 
Whats New In Java Ee 6
Whats New In Java Ee 6Whats New In Java Ee 6
Whats New In Java Ee 6
 
Are app servers still fascinating
Are app servers still fascinatingAre app servers still fascinating
Are app servers still fascinating
 
Lightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPALightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPA
 
Come and Play! with Java EE 7
Come and Play! with Java EE 7Come and Play! with Java EE 7
Come and Play! with Java EE 7
 
Case Study of Financial Web System Development and Operations with Oracle Web...
Case Study of Financial Web System Development and Operations with Oracle Web...Case Study of Financial Web System Development and Operations with Oracle Web...
Case Study of Financial Web System Development and Operations with Oracle Web...
 
Move from J2EE to Java EE
Move from J2EE to Java EEMove from J2EE to Java EE
Move from J2EE to Java EE
 
Java EE 7 for Real Enterprise Systems
Java EE 7 for Real Enterprise SystemsJava EE 7 for Real Enterprise Systems
Java EE 7 for Real Enterprise Systems
 
Java one 2015 [con3339]
Java one 2015 [con3339]Java one 2015 [con3339]
Java one 2015 [con3339]
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
 
Seven Points for Applying Java EE 7
Seven Points for Applying Java EE 7Seven Points for Applying Java EE 7
Seven Points for Applying Java EE 7
 
Just enough app server
Just enough app serverJust enough app server
Just enough app server
 
Java EE 7 - Overview and Status
Java EE 7  - Overview and StatusJava EE 7  - Overview and Status
Java EE 7 - Overview and Status
 
IBM WebSphere Application Server (Clustering) Concept
IBM WebSphere Application Server (Clustering) ConceptIBM WebSphere Application Server (Clustering) Concept
IBM WebSphere Application Server (Clustering) Concept
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
 

Ähnlich wie Dependency Injection with CDI in 15 minutes

Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
Martijn Dashorst
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Christian Schneider
 

Ähnlich wie Dependency Injection with CDI in 15 minutes (20)

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
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdf
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testing
 
Android studio plugin 作ってみた 〜 create intent method generator 〜
Android studio plugin 作ってみた 〜 create intent method generator 〜Android studio plugin 作ってみた 〜 create intent method generator 〜
Android studio plugin 作ってみた 〜 create intent method generator 〜
 
create-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdfcreate-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdf
 
Android testing
Android testingAndroid testing
Android testing
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
An intro to cqrs
An intro to cqrsAn intro to cqrs
An intro to cqrs
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
droidparts
droidpartsdroidparts
droidparts
 
Introduction toandroid
Introduction toandroidIntroduction toandroid
Introduction toandroid
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
Cambio de bases
Cambio de basesCambio de bases
Cambio de bases
 
Software engineering ⊇ Software testing
Software engineering ⊇ Software testingSoftware engineering ⊇ Software testing
Software engineering ⊇ Software testing
 

Kürzlich hochgeladen

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
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 

Dependency Injection with CDI in 15 minutes