SlideShare une entreprise Scribd logo
1  sur  61
Télécharger pour lire hors ligne
INTRODUCTION TO CONTEXTS AND 
DEPENDENCY INJECTION (CDI) 
@antoine_sd
ANTOINE SABOT-DURAND 
• Senior Software Engineer @Red Hat 
• Java & OSS : 
• CDI co-spec lead 
• CDI community development 
• Tech Lead on Agorava 
• @antoine_sd
WHAT IS CDI ? 
• Java EE dependency injection standard 
• Strong typed and type safe 
• Context management 
• Observer pattern included (Event bus) 
• Highly extensible
Previously on CDI
A BIT OF HISTORY 
CDI 1.0 (Java EE 6) 
CDI 1.1 (Java EE 7) 
CDI 1.2 (1.1 MR) 
CDI 2.0 Starts 
Dec 2009 June 2013 Apr 2014 Sep 2014 
CDI 2.0 released 
Q1 2016
IMPLEMENTATIONS 
JBoss Weld (Reference Implementation) Apache Open WebBeans
CDI ACTIVATION 
• In CDI 1.0, you must add a beans.xml file to your archive 
• Since CDI 1.1, it’s activated by default: 
• All classes having a “bean defining annotation” become a bean 
• You can still use beans.xml file to activate CDI explicitly or 
deactivate it
THE CDI BEAN 
• In Java EE 6 and 7 everything is a Managed Bean 
• Managed beans are basic components 
• They are managed by the container 
• They all have a lifecycle 
• They can be intercepted (AOP) 
• They can be injected 
• Accessible from outside CDI code.
BASIC DEPENDENCY INJECTION 
@Inject
THIS IS A BEAN 
public class HelloService { 
public String hello() { 
return "Hello World!"; 
} 
}
DI IN CONSTRUCTOR 
public class MyBean { 
private HelloService service; 
@Inject 
public MyBean(HelloService service) { 
this.service = service; 
} 
}
DI IN SETTER 
public class MyBean { 
private HelloService service; 
@Inject 
public void setService(HelloService service) { 
this.service = service; 
} 
}
DI IN FIELD 
public class MyBean { 
@Inject 
private HelloService service; 
public void displayHello() { 
display(service.hello(); 
} 
}
NO TYPE ERASURE IN CDI 
public class MyBean { 
@Inject Service<User> userService; 
@Inject Service<Staff> staffService; 
}
NO TYPE ERASURE IN CDI 
public class MyBean { 
@Inject Service<User> userService; 
@Inject Service<Staff> staffService; 
} 
This works
USING QUALIFIERS TO DISTINGUISH 
BEANS OF THE SAME TYPE
2 SERVICE IMPLEMENTATIONS… 
public interface HelloService { 
public String hello(); 
} 
public class FrenchHelloService implements HelloService { 
public String hello() { 
return "Bonjour tout le monde!"; 
} 
} 
public class EnglishHelloService implements HelloService { 
public String hello() { 
return "Hello World!"; 
} 
}
…NEED QUALIFIERS… 
@Qualifier 
@Retention(RUNTIME) 
@Target({FIELD, TYPE, METHOD, PARAMETER}) 
public @interface French {} 
@Qualifier 
@Retention(RUNTIME) 
@Target({FIELD, TYPE, METHOD, PARAMETER}) 
public @interface English {}
…TO BE DISTINGUISHED. 
@French 
public class FrenchHelloService implements HelloService { 
public String hello() { 
return "Bonjour tout le monde!"; 
} 
} 
@English 
public class EnglishHelloService implements HelloService { 
public String hello() { 
return "Hello World!"; 
} 
}
QUALIFIED INJECTION POINTS 
public class MyBean { 
@Inject @French HelloService service; 
public void displayHello() { 
display( service.hello(); 
} 
} 
public class MyBean { 
@Inject @English HelloService service; 
public void displayHello() { 
display( service.hello(); 
} 
}
QUALIFIERS CAN HAVE MEMBERS 
@Qualifier 
@Retention(RUNTIME) 
@Target({FIELD, TYPE, METHOD, PARAMETER}) 
public @interface Language { 
Languages value(); 
@Nonbinding String description() default ""; 
public enum Languages { 
FRENCH, ENGLISH 
} 
}
QUALIFIERS WITH MEMBERS 1/2 
@Language(FRENCH) 
public class FrenchHelloService implements HelloService { 
public String hello() { 
return "Bonjour tout le monde!"; 
} 
} 
@Language(ENGLISH) 
public class EnglishHelloService implements HelloService { 
public String hello() { 
return "Hello World!"; 
} 
}
QUALIFIERS WITH MEMBERS 2/2 
public class MyBean { 
@Inject @Language(ENGLISH) HelloService service; 
public void displayHello() { 
display( service.hello(); 
} 
} 
public class MyBean { 
@Inject @Language(FRENCH) HelloService service; 
public void displayHello() { 
display( service.hello(); 
} 
}
MULTIPLE QUALIFIERS 
public class MyBean { 
@Inject @French 
HelloService service; 
} 
@French @Console @Secured 
public class FrenchHelloService implements HelloService { 
}
MULTIPLE QUALIFIERS 
public class MyBean { 
@Inject @French @Console 
HelloService service; 
} 
@French @Console @Secured 
public class FrenchHelloService implements HelloService { 
}
MULTIPLE QUALIFIERS 
public class MyBean { 
@Inject @French @Console @Secured 
HelloService service; 
} 
@French @Console @Secured 
public class FrenchHelloService implements HelloService { 
}
MULTIPLE QUALIFIERS 
public class MyBean { 
@Inject @French @Console @Secured 
HelloService service; 
} 
@French @Secured 
public class FrenchHelloService implements HelloService { 
}
MULTIPLE QUALIFIERS 
public class MyBean { 
@Inject @French @Console @Secured 
HelloService service; 
} 
@French @Secured 
public class FrenchHelloService implements HelloService { 
}
RESERVED QUALIFIERS 
@Default 
@Any 
@Named
PROGRAMMATIC LOOKUP
SOMETIMES CALLED “LAZY INJECTION” 
public class MyBean { 
@Inject Instance<HelloService> service; 
public void displayHello() { 
display( service.get().hello() ); 
} 
}
CHECK BEAN EXISTENCE AT RUNTIME 
public class MyBean { 
@Inject Instance<HelloService> service; 
public void displayHello() { 
if (!service.isUnsatisfied()) { 
display( service.get().hello() ); 
} 
} 
}
INSTANCE<T> IS ITERABLE 
public interface Instance<T> extends Iterable<T>, Provider<T> { 
public Instance<T> select(Annotation... qualifiers); 
public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers); 
public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers); 
public boolean isUnsatisfied(); 
public boolean isAmbiguous(); 
public void destroy(T instance); 
}
LOOP ON ALL BEANS OF A GIVEN TYPE 
public class MyBean { 
@Inject @Any Instance<HelloService> services; 
public void displayHello() { 
for (HelloService service : services) { 
display( service.hello() ); 
} 
} 
}
SELECT A QUALIFIER AT RUNTIME 
public class MyBean { 
@Inject @Any Instance<HelloService> services; 
public void displayHello() { 
display( 
service.select( 
new AnnotationLiteral()<French> {}) 
.get() ); 
} 
}
CONTEXTS
CONTEXTS MANAGE BEANS LIFECYCLE 
• They helps container to choose when a bean should be instantiated and destroyed 
• They enforce the fact that a given bean is a singleton for a given context 
• Built-in CDI contexts : 
• @Dependent (default) 
• @ApplicationScoped, @SessionScoped, @RequestScoped 
• @ConversationScoped 
• @Singleton 
• You can create your own scope
CHOOSING THE RIGHT CONTEXT 
@SessionScoped 
public class CartBean { 
public void addItem(Item item) { 
... 
} 
}
CHOOSING THE RIGHT CONTEXT 
@ApplicationScoped 
public class CartBean { 
public void addItem(Item item) { 
... 
} 
}
CHOOSING THE RIGHT CONTEXT 
@ApplicationScoped 
public class CartBean { 
public void addItem(Item item) { 
... 
} 
} 
FAIL !!!
CONVERSATION IS MANAGE BY DEV 
@ConversationScoped 
public class CartBean { 
public void addItem(Item item) { 
... 
} 
}
NEW CONTEXTS CAN BE CREATED 
@ThreadScoped 
public class CartBean { 
public void addItem(Item item) { 
... 
} 
}
PRODUCERS
CREATING BEAN FROM ANY CLASS 
@Produces 
public MyNonCDIClass myProducer() { 
return new MyNonCdiClass(); 
} 
... 
@Inject 
MyNonCDIClass bean;
PRODUCERS MAY HAVE A SCOPE 
@Produces 
@RequestScoped 
public FacesContext produceFacesContext() { 
return FacesContext.getCurrentInstance(); 
}
GETTING INFO FROM INJECTION POINT 
@Produces 
public Logger produceLog(InjectionPoint injectionPoint) { 
return Logger.getLogger(injectionPoint.getMember() 
.getDeclaringClass().getName()); 
}
EVENTS
A NICE WAY TO ADD DECOUPLING 
public class FirstBean { 
@Inject Event<Post> postEvent; 
public void saveNewPost(Post myPost) { 
postEvent.fire(myPost); 
} 
} 
public class SecondBean { 
public void listenPost(@Observes Post post) { 
System.out.println("Received : " + evt.message()); 
} 
}
EVENTS CAN BE QUALIFIED 
public class FirstBean { 
@Inject Event<Post> postEvent; 
public void saveNewPost(Post myPost) { 
postEvent.select( 
new AnnotationLiteral()<French> {}).fire(myPost); 
} 
} 
public class SecondBean { 
// these 3 observers will be called 
public void listenFrPost(@Observes @French Post post) {} 
public void listenPost(@Observes Post post) {} 
public void listenObject(@Observes Object obj) {} 
// This one won’t be called 
public void listenEnPost(@Observes @English Post post) {} 
}
AS ALWAYS “NO TYPE ERASURE” 
public class SecondBean { 
// these observers will be resolved depending 
// on parameter in event payload type 
public void listenStrPost(@Observes Post<String> post) {} 
public void listenNumPost(@Observes Post<Number> post) {} 
}
SOME BUILT-IN EVENTS 
public class SecondBean { 
public void beginRequest(@Observes @Initialized(RequestScoped.class) 
ServletRequest req) {} 
public void endRequest(@Observes @Destroyed(RequestScoped.class) 
ServletRequest req) {} 
public void beginSession(@Observes @Initialized(SessionScoped.class) 
HttpSession session) {} 
public void endSession(@Observes @Destroyed(SessionScoped.class) 
HttpSession session) {} 
}
STEREOTYPES TO AVOID ANNOTATIONS 
HELL
BUILT-IN STEREOTYPE 
@Named 
@RequestScoped 
@Documented 
@Stereotype 
@Target({ TYPE, METHOD, FIELD }) 
@Retention(RUNTIME) 
public @interface Model { 
}
MY STEREOTYPE 
@Named 
@SessionScoped 
@MyQualifier 
@MyOtherQualifier 
@Documented 
@Stereotype 
@Target({ TYPE, METHOD, FIELD }) 
@Retention(RUNTIME) 
public @interface MyModel { 
}
USAGE 
@MyModel 
public class CircularBean { 
}
DECORATORS & INTERCEPTORS
A DECORATOR 
@Decorator 
@Priority(Interceptor.Priority.APPLICATION) 
public abstract class HelloDecorator implements HelloService { 
// The decorated service may be restricted with qualifiers 
@Inject @Delegate HelloService service; 
public String hello() { 
return service.hello() + "-decorated"; 
} 
}
INTERCEPTOR BINDING… 
@InterceptorBinding 
@Target({METHOD, TYPE}) 
@Retention(RUNTIME) 
public @interface Loggable {}
…IS USED TO BIND AN INTERCEPTOR 
@Interceptor @Loggable 
@Priority(Interceptor.Priority.APPLICATION) 
public class LogInterceptor { 
@AroundInvoke 
public Object log(InvocationContext ic) throws Exception { 
System.out.println("Entering " + ic.getMethod().getName()); 
try { 
return ic.proceed(); 
} finally { 
System.out.println("Exiting " + ic.getMethod().getName()); 
} 
} 
}
IT CAN BE PUT ON CLASS OR METHOD 
@Loggable 
public class MyBean { 
@Inject HelloService service; 
public void displayHello() { 
display( service.hello(); 
} 
}
THAT’S ALL FOR BASIC CDI 
• If you want to learn advanced stuff come to check my over talk : CDI 
advanced. 
• follow @cdispec and @antoine_sd on twitter 
• Questions ?

Contenu connexe

Tendances

Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
🎤 Hanno Embregts 🎸
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Zend Studio Tips and Tricks
Zend Studio Tips and TricksZend Studio Tips and Tricks
Zend Studio Tips and Tricks
Roy Ganor
 

Tendances (20)

Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Angular Best Practices - Perfomatix
Angular Best Practices - PerfomatixAngular Best Practices - Perfomatix
Angular Best Practices - Perfomatix
 
JUnit 5 — New Opportunities for Testing on the JVM
JUnit 5 — New Opportunities for Testing on the JVMJUnit 5 — New Opportunities for Testing on the JVM
JUnit 5 — New Opportunities for Testing on the JVM
 
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
 
Introduction to Continuous Integration
Introduction to Continuous IntegrationIntroduction to Continuous Integration
Introduction to Continuous Integration
 
FAST for SharePoint Deep Dive
FAST for SharePoint Deep DiveFAST for SharePoint Deep Dive
FAST for SharePoint Deep Dive
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Connecting Connect with Spring Boot
Connecting Connect with Spring BootConnecting Connect with Spring Boot
Connecting Connect with Spring Boot
 
SpringBoot
SpringBootSpringBoot
SpringBoot
 
Spring Test Framework
Spring Test FrameworkSpring Test Framework
Spring Test Framework
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!
 
Testing with Spring 4.x
Testing with Spring 4.xTesting with Spring 4.x
Testing with Spring 4.x
 
Eclipse IDE, 2019.09, Java Development
Eclipse IDE, 2019.09, Java Development Eclipse IDE, 2019.09, Java Development
Eclipse IDE, 2019.09, Java Development
 
Bulletproof Microservices with Spring and Kubernetes
Bulletproof Microservices with Spring and KubernetesBulletproof Microservices with Spring and Kubernetes
Bulletproof Microservices with Spring and Kubernetes
 
Zend Studio Tips and Tricks
Zend Studio Tips and TricksZend Studio Tips and Tricks
Zend Studio Tips and Tricks
 
Replicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containersReplicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containers
 
Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 

En vedette

Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
Antoine Sabot-Durand
 
Play Framework
Play FrameworkPlay Framework
Play Framework
Armaklan
 

En vedette (20)

Java EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's QuarrelJava EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's Quarrel
 
Devoxx Java Social and Agorava
Devoxx Java Social and AgoravaDevoxx Java Social and Agorava
Devoxx Java Social and Agorava
 
Advanced CDI in live coding
Advanced CDI in live codingAdvanced CDI in live coding
Advanced CDI in live coding
 
Play! Framework at GenevaJUG by Guillaume Bort
Play! Framework at GenevaJUG by Guillaume BortPlay! Framework at GenevaJUG by Guillaume Bort
Play! Framework at GenevaJUG by Guillaume Bort
 
Apache Camel
Apache CamelApache Camel
Apache Camel
 
CDI 2.0 is coming
CDI 2.0 is comingCDI 2.0 is coming
CDI 2.0 is coming
 
Mute Java EE DNA with CDI
Mute Java EE DNA with CDI Mute Java EE DNA with CDI
Mute Java EE DNA with CDI
 
CDI 1.1 university
CDI 1.1 universityCDI 1.1 university
CDI 1.1 university
 
Adopt a JSR: CDI 2.0 at Devoxx UK
Adopt a JSR: CDI 2.0 at Devoxx UKAdopt a JSR: CDI 2.0 at Devoxx UK
Adopt a JSR: CDI 2.0 at Devoxx UK
 
CDI 2.0 is upon us Devoxx
CDI 2.0 is upon us DevoxxCDI 2.0 is upon us Devoxx
CDI 2.0 is upon us Devoxx
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Why Play Framework is fast
Why Play Framework is fastWhy Play Framework is fast
Why Play Framework is fast
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
CDI par la pratique
CDI par la pratiqueCDI par la pratique
CDI par la pratique
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
CDI mis en pratique avec Seam Social et Weld OSGI
CDI mis en pratique avec Seam Social et Weld OSGICDI mis en pratique avec Seam Social et Weld OSGI
CDI mis en pratique avec Seam Social et Weld OSGI
 
Java EE, un ami qui vous veut du bien
Java EE, un ami qui vous veut du bienJava EE, un ami qui vous veut du bien
Java EE, un ami qui vous veut du bien
 

Similaire à 1/3 : introduction to CDI - Antoine Sabot-Durand

Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
Ray Ploski
 

Similaire à 1/3 : introduction to CDI - Antoine Sabot-Durand (20)

Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
VRaptor 4 - JavaOne
VRaptor 4 - JavaOneVRaptor 4 - JavaOne
VRaptor 4 - JavaOne
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
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
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
CDI in JEE6
CDI in JEE6CDI in JEE6
CDI in JEE6
 
Solid principles
Solid principlesSolid principles
Solid principles
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 Platform
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
 

Plus de SOAT

20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat
SOAT
 
Soirée 3T Soat - Asp.net MVC
Soirée 3T Soat - Asp.net MVCSoirée 3T Soat - Asp.net MVC
Soirée 3T Soat - Asp.net MVC
SOAT
 
Présentation spring data Matthieu Briend
Présentation spring data  Matthieu BriendPrésentation spring data  Matthieu Briend
Présentation spring data Matthieu Briend
SOAT
 

Plus de SOAT (20)

Back from Microsoft //Build 2018
Back from Microsoft //Build 2018Back from Microsoft //Build 2018
Back from Microsoft //Build 2018
 
L'entreprise libérée
L'entreprise libéréeL'entreprise libérée
L'entreprise libérée
 
Amélioration continue, c'est l'affaire de tous !
Amélioration continue, c'est l'affaire de tous !Amélioration continue, c'est l'affaire de tous !
Amélioration continue, c'est l'affaire de tous !
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entreprise
 
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUESARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
 
Angular JS - Paterne Gaye-Guingnido
Angular JS - Paterne Gaye-Guingnido Angular JS - Paterne Gaye-Guingnido
Angular JS - Paterne Gaye-Guingnido
 
Dans l'enfer du Web Mobile - un retour d'expérience - Mathieu Parisot
Dans l'enfer du Web Mobile - un retour d'expérience - Mathieu ParisotDans l'enfer du Web Mobile - un retour d'expérience - Mathieu Parisot
Dans l'enfer du Web Mobile - un retour d'expérience - Mathieu Parisot
 
RxJava, Getting Started - David Wursteisen - 16 Octobre 2014
RxJava, Getting Started - David Wursteisen - 16 Octobre 2014RxJava, Getting Started - David Wursteisen - 16 Octobre 2014
RxJava, Getting Started - David Wursteisen - 16 Octobre 2014
 
L'impact du Responsive Web Design sur vos équipes projet - Mathieu Parisot - ...
L'impact du Responsive Web Design sur vos équipes projet - Mathieu Parisot - ...L'impact du Responsive Web Design sur vos équipes projet - Mathieu Parisot - ...
L'impact du Responsive Web Design sur vos équipes projet - Mathieu Parisot - ...
 
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
 
20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat
 
Développer des applications iOS et Android avec c# grâce à Xamarin par Cyril ...
Développer des applications iOS et Android avec c# grâce à Xamarin par Cyril ...Développer des applications iOS et Android avec c# grâce à Xamarin par Cyril ...
Développer des applications iOS et Android avec c# grâce à Xamarin par Cyril ...
 
Amazon Web Service par Bertrand Lehurt - 11 mars 2014
Amazon Web Service par Bertrand Lehurt - 11 mars 2014Amazon Web Service par Bertrand Lehurt - 11 mars 2014
Amazon Web Service par Bertrand Lehurt - 11 mars 2014
 
ASP.Net Web API - Léonard Labat (18 février 2014)
ASP.Net Web API - Léonard Labat (18 février 2014)ASP.Net Web API - Léonard Labat (18 février 2014)
ASP.Net Web API - Léonard Labat (18 février 2014)
 
Xamarin et le développement natif d’applications Android, iOS et Windows en C#
 Xamarin et le développement natif d’applications Android, iOS et Windows en C# Xamarin et le développement natif d’applications Android, iOS et Windows en C#
Xamarin et le développement natif d’applications Android, iOS et Windows en C#
 
A la découverte du Responsive Web Design par Mathieu Parisot - Soat
A la découverte du Responsive Web Design par Mathieu Parisot - SoatA la découverte du Responsive Web Design par Mathieu Parisot - Soat
A la découverte du Responsive Web Design par Mathieu Parisot - Soat
 
MongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesMongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de données
 
Soirée 3T Soat - Asp.net MVC
Soirée 3T Soat - Asp.net MVCSoirée 3T Soat - Asp.net MVC
Soirée 3T Soat - Asp.net MVC
 
Présentation spring data Matthieu Briend
Présentation spring data  Matthieu BriendPrésentation spring data  Matthieu Briend
Présentation spring data Matthieu Briend
 
Je suis agile tout seul - Ricardo Minhoto
Je suis agile tout seul - Ricardo MinhotoJe suis agile tout seul - Ricardo Minhoto
Je suis agile tout seul - Ricardo Minhoto
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
 

Dernier (20)

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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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...
 
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?
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
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
 
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...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

1/3 : introduction to CDI - Antoine Sabot-Durand

  • 1. INTRODUCTION TO CONTEXTS AND DEPENDENCY INJECTION (CDI) @antoine_sd
  • 2. ANTOINE SABOT-DURAND • Senior Software Engineer @Red Hat • Java & OSS : • CDI co-spec lead • CDI community development • Tech Lead on Agorava • @antoine_sd
  • 3. WHAT IS CDI ? • Java EE dependency injection standard • Strong typed and type safe • Context management • Observer pattern included (Event bus) • Highly extensible
  • 5. A BIT OF HISTORY CDI 1.0 (Java EE 6) CDI 1.1 (Java EE 7) CDI 1.2 (1.1 MR) CDI 2.0 Starts Dec 2009 June 2013 Apr 2014 Sep 2014 CDI 2.0 released Q1 2016
  • 6. IMPLEMENTATIONS JBoss Weld (Reference Implementation) Apache Open WebBeans
  • 7. CDI ACTIVATION • In CDI 1.0, you must add a beans.xml file to your archive • Since CDI 1.1, it’s activated by default: • All classes having a “bean defining annotation” become a bean • You can still use beans.xml file to activate CDI explicitly or deactivate it
  • 8. THE CDI BEAN • In Java EE 6 and 7 everything is a Managed Bean • Managed beans are basic components • They are managed by the container • They all have a lifecycle • They can be intercepted (AOP) • They can be injected • Accessible from outside CDI code.
  • 10. THIS IS A BEAN public class HelloService { public String hello() { return "Hello World!"; } }
  • 11. DI IN CONSTRUCTOR public class MyBean { private HelloService service; @Inject public MyBean(HelloService service) { this.service = service; } }
  • 12. DI IN SETTER public class MyBean { private HelloService service; @Inject public void setService(HelloService service) { this.service = service; } }
  • 13. DI IN FIELD public class MyBean { @Inject private HelloService service; public void displayHello() { display(service.hello(); } }
  • 14. NO TYPE ERASURE IN CDI public class MyBean { @Inject Service<User> userService; @Inject Service<Staff> staffService; }
  • 15. NO TYPE ERASURE IN CDI public class MyBean { @Inject Service<User> userService; @Inject Service<Staff> staffService; } This works
  • 16. USING QUALIFIERS TO DISTINGUISH BEANS OF THE SAME TYPE
  • 17. 2 SERVICE IMPLEMENTATIONS… public interface HelloService { public String hello(); } public class FrenchHelloService implements HelloService { public String hello() { return "Bonjour tout le monde!"; } } public class EnglishHelloService implements HelloService { public String hello() { return "Hello World!"; } }
  • 18. …NEED QUALIFIERS… @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface French {} @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface English {}
  • 19. …TO BE DISTINGUISHED. @French public class FrenchHelloService implements HelloService { public String hello() { return "Bonjour tout le monde!"; } } @English public class EnglishHelloService implements HelloService { public String hello() { return "Hello World!"; } }
  • 20. QUALIFIED INJECTION POINTS public class MyBean { @Inject @French HelloService service; public void displayHello() { display( service.hello(); } } public class MyBean { @Inject @English HelloService service; public void displayHello() { display( service.hello(); } }
  • 21. QUALIFIERS CAN HAVE MEMBERS @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface Language { Languages value(); @Nonbinding String description() default ""; public enum Languages { FRENCH, ENGLISH } }
  • 22. QUALIFIERS WITH MEMBERS 1/2 @Language(FRENCH) public class FrenchHelloService implements HelloService { public String hello() { return "Bonjour tout le monde!"; } } @Language(ENGLISH) public class EnglishHelloService implements HelloService { public String hello() { return "Hello World!"; } }
  • 23. QUALIFIERS WITH MEMBERS 2/2 public class MyBean { @Inject @Language(ENGLISH) HelloService service; public void displayHello() { display( service.hello(); } } public class MyBean { @Inject @Language(FRENCH) HelloService service; public void displayHello() { display( service.hello(); } }
  • 24. MULTIPLE QUALIFIERS public class MyBean { @Inject @French HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 25. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 26. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 27. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  • 28. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  • 31. SOMETIMES CALLED “LAZY INJECTION” public class MyBean { @Inject Instance<HelloService> service; public void displayHello() { display( service.get().hello() ); } }
  • 32. CHECK BEAN EXISTENCE AT RUNTIME public class MyBean { @Inject Instance<HelloService> service; public void displayHello() { if (!service.isUnsatisfied()) { display( service.get().hello() ); } } }
  • 33. INSTANCE<T> IS ITERABLE public interface Instance<T> extends Iterable<T>, Provider<T> { public Instance<T> select(Annotation... qualifiers); public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers); public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers); public boolean isUnsatisfied(); public boolean isAmbiguous(); public void destroy(T instance); }
  • 34. LOOP ON ALL BEANS OF A GIVEN TYPE public class MyBean { @Inject @Any Instance<HelloService> services; public void displayHello() { for (HelloService service : services) { display( service.hello() ); } } }
  • 35. SELECT A QUALIFIER AT RUNTIME public class MyBean { @Inject @Any Instance<HelloService> services; public void displayHello() { display( service.select( new AnnotationLiteral()<French> {}) .get() ); } }
  • 37. CONTEXTS MANAGE BEANS LIFECYCLE • They helps container to choose when a bean should be instantiated and destroyed • They enforce the fact that a given bean is a singleton for a given context • Built-in CDI contexts : • @Dependent (default) • @ApplicationScoped, @SessionScoped, @RequestScoped • @ConversationScoped • @Singleton • You can create your own scope
  • 38. CHOOSING THE RIGHT CONTEXT @SessionScoped public class CartBean { public void addItem(Item item) { ... } }
  • 39. CHOOSING THE RIGHT CONTEXT @ApplicationScoped public class CartBean { public void addItem(Item item) { ... } }
  • 40. CHOOSING THE RIGHT CONTEXT @ApplicationScoped public class CartBean { public void addItem(Item item) { ... } } FAIL !!!
  • 41. CONVERSATION IS MANAGE BY DEV @ConversationScoped public class CartBean { public void addItem(Item item) { ... } }
  • 42. NEW CONTEXTS CAN BE CREATED @ThreadScoped public class CartBean { public void addItem(Item item) { ... } }
  • 44. CREATING BEAN FROM ANY CLASS @Produces public MyNonCDIClass myProducer() { return new MyNonCdiClass(); } ... @Inject MyNonCDIClass bean;
  • 45. PRODUCERS MAY HAVE A SCOPE @Produces @RequestScoped public FacesContext produceFacesContext() { return FacesContext.getCurrentInstance(); }
  • 46. GETTING INFO FROM INJECTION POINT @Produces public Logger produceLog(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember() .getDeclaringClass().getName()); }
  • 48. A NICE WAY TO ADD DECOUPLING public class FirstBean { @Inject Event<Post> postEvent; public void saveNewPost(Post myPost) { postEvent.fire(myPost); } } public class SecondBean { public void listenPost(@Observes Post post) { System.out.println("Received : " + evt.message()); } }
  • 49. EVENTS CAN BE QUALIFIED public class FirstBean { @Inject Event<Post> postEvent; public void saveNewPost(Post myPost) { postEvent.select( new AnnotationLiteral()<French> {}).fire(myPost); } } public class SecondBean { // these 3 observers will be called public void listenFrPost(@Observes @French Post post) {} public void listenPost(@Observes Post post) {} public void listenObject(@Observes Object obj) {} // This one won’t be called public void listenEnPost(@Observes @English Post post) {} }
  • 50. AS ALWAYS “NO TYPE ERASURE” public class SecondBean { // these observers will be resolved depending // on parameter in event payload type public void listenStrPost(@Observes Post<String> post) {} public void listenNumPost(@Observes Post<Number> post) {} }
  • 51. SOME BUILT-IN EVENTS public class SecondBean { public void beginRequest(@Observes @Initialized(RequestScoped.class) ServletRequest req) {} public void endRequest(@Observes @Destroyed(RequestScoped.class) ServletRequest req) {} public void beginSession(@Observes @Initialized(SessionScoped.class) HttpSession session) {} public void endSession(@Observes @Destroyed(SessionScoped.class) HttpSession session) {} }
  • 52. STEREOTYPES TO AVOID ANNOTATIONS HELL
  • 53. BUILT-IN STEREOTYPE @Named @RequestScoped @Documented @Stereotype @Target({ TYPE, METHOD, FIELD }) @Retention(RUNTIME) public @interface Model { }
  • 54. MY STEREOTYPE @Named @SessionScoped @MyQualifier @MyOtherQualifier @Documented @Stereotype @Target({ TYPE, METHOD, FIELD }) @Retention(RUNTIME) public @interface MyModel { }
  • 55. USAGE @MyModel public class CircularBean { }
  • 57. A DECORATOR @Decorator @Priority(Interceptor.Priority.APPLICATION) public abstract class HelloDecorator implements HelloService { // The decorated service may be restricted with qualifiers @Inject @Delegate HelloService service; public String hello() { return service.hello() + "-decorated"; } }
  • 58. INTERCEPTOR BINDING… @InterceptorBinding @Target({METHOD, TYPE}) @Retention(RUNTIME) public @interface Loggable {}
  • 59. …IS USED TO BIND AN INTERCEPTOR @Interceptor @Loggable @Priority(Interceptor.Priority.APPLICATION) public class LogInterceptor { @AroundInvoke public Object log(InvocationContext ic) throws Exception { System.out.println("Entering " + ic.getMethod().getName()); try { return ic.proceed(); } finally { System.out.println("Exiting " + ic.getMethod().getName()); } } }
  • 60. IT CAN BE PUT ON CLASS OR METHOD @Loggable public class MyBean { @Inject HelloService service; public void displayHello() { display( service.hello(); } }
  • 61. THAT’S ALL FOR BASIC CDI • If you want to learn advanced stuff come to check my over talk : CDI advanced. • follow @cdispec and @antoine_sd on twitter • Questions ?