SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Downloaden Sie, um offline zu lesen
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
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; 
} 
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 { 
}
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) { 
... 
} 
} 
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()); 
}
REMEMBER : “NO TYPE ERASURE” 
@Produces 
public <K, V> Map<K, V> produceMap(InjectionPoint ip) { 
if (valueIsNumber(ip.getType())) { 
return new TreeMap<K, V>(); 
} 
return new HashMap<K, V>(); 
}
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) {} 
}
DECORATORS & INTERCEPTORS
A DECORATOR 
@Decorator 
@Priority(Interceptor.Priority.APPLICATION) 
public 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 : 
Going Farther with CDI 1.2 [CON5585] Monday 5:30pm 
• visit : http://cdi-spec.org 
• follow @cdispec and @antoine_sd on twitter 
• Questions ?

Weitere ähnliche Inhalte

Was ist angesagt?

Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
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 6Ray Ploski
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesAntonio Goncalves
 
When Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets AngularWhen Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets AngularAntonio Goncalves
 
Zend Studio Tips and Tricks
Zend Studio Tips and TricksZend Studio Tips and Tricks
Zend Studio Tips and TricksRoy Ganor
 
Invoke dynamite in Java EE with invoke dynamic
Invoke dynamite in Java EE with invoke dynamicInvoke dynamite in Java EE with invoke dynamic
Invoke dynamite in Java EE with invoke dynamicAntoine Sabot-Durand
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDiego Lewin
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QAFest
 
Dependency Injections in Kotlin
Dependency Injections in KotlinDependency Injections in Kotlin
Dependency Injections in KotlinEatDog
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
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 PotencierHimel Nag Rana
 
Refactoring a go project
Refactoring a go projectRefactoring a go project
Refactoring a go projectDan Tran
 
Manage software dependencies with ioc and aop
Manage software dependencies with ioc and aopManage software dependencies with ioc and aop
Manage software dependencies with ioc and aopStefano Leli
 
vJUG - The JavaFX Ecosystem
vJUG - The JavaFX EcosystemvJUG - The JavaFX Ecosystem
vJUG - The JavaFX EcosystemAndres Almiray
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code lessAnton Novikau
 
Test code that will not slow you down
Test code that will not slow you downTest code that will not slow you down
Test code that will not slow you downKostadin Golev
 
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
 

Was ist angesagt? (20)

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
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
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
 
The path to cdi 2.0
The path to cdi 2.0The path to cdi 2.0
The path to cdi 2.0
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutes
 
When Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets AngularWhen Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets Angular
 
Zend Studio Tips and Tricks
Zend Studio Tips and TricksZend Studio Tips and Tricks
Zend Studio Tips and Tricks
 
Invoke dynamite in Java EE with invoke dynamic
Invoke dynamite in Java EE with invoke dynamicInvoke dynamite in Java EE with invoke dynamic
Invoke dynamite in Java EE with invoke dynamic
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
 
Dependency Injections in Kotlin
Dependency Injections in KotlinDependency Injections in Kotlin
Dependency Injections in Kotlin
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
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
 
Refactoring a go project
Refactoring a go projectRefactoring a go project
Refactoring a go project
 
Manage software dependencies with ioc and aop
Manage software dependencies with ioc and aopManage software dependencies with ioc and aop
Manage software dependencies with ioc and aop
 
vJUG - The JavaFX Ecosystem
vJUG - The JavaFX EcosystemvJUG - The JavaFX Ecosystem
vJUG - The JavaFX Ecosystem
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Test code that will not slow you down
Test code that will not slow you downTest code that will not slow you down
Test code that will not slow you down
 
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
 

Andere mochten auch

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 bienAntoine Sabot-Durand
 
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
 
Moving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutterMoving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutterDan Allen
 
CDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE DevelopmentCDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE DevelopmentSaltmarch Media
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIMichel Graciano
 
What we can expect from Java 9 by Ivan Krylov
What we can expect from Java 9 by Ivan KrylovWhat we can expect from Java 9 by Ivan Krylov
What we can expect from Java 9 by Ivan KrylovJ On The Beach
 
CDI, Weld and the future of Seam
CDI, Weld and the future of SeamCDI, Weld and the future of Seam
CDI, Weld and the future of SeamDan Allen
 
The Magnificent java EE 7 in Wildfly-O-Rama
The Magnificent java EE 7 in Wildfly-O-RamaThe Magnificent java EE 7 in Wildfly-O-Rama
The Magnificent java EE 7 in Wildfly-O-RamaAntoine Sabot-Durand
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-DurandSOAT
 
Fais ce que tu veux avec Java EE - Devoxx France 2014
Fais ce que tu veux avec Java EE - Devoxx France 2014Fais ce que tu veux avec Java EE - Devoxx France 2014
Fais ce que tu veux avec Java EE - Devoxx France 2014Antoine Sabot-Durand
 
Java one 2015 [con3339]
Java one 2015 [con3339]Java one 2015 [con3339]
Java one 2015 [con3339]Arshal Ameen
 
Architecting Large Enterprise Projects @DevConf.CZ
Architecting Large Enterprise Projects @DevConf.CZArchitecting Large Enterprise Projects @DevConf.CZ
Architecting Large Enterprise Projects @DevConf.CZMarkus Eisele
 

Andere mochten auch (20)

Advanced CDI in live coding
Advanced CDI in live codingAdvanced CDI in live coding
Advanced CDI in live coding
 
CDI 2.0 is coming
CDI 2.0 is comingCDI 2.0 is coming
CDI 2.0 is coming
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
Going further with CDI 1.2
Going further with CDI 1.2Going further with CDI 1.2
Going further with CDI 1.2
 
Mute Java EE DNA with CDI
Mute Java EE DNA with CDI Mute Java EE DNA with CDI
Mute Java EE DNA with CDI
 
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
 
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
 
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
 
Moving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutterMoving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutter
 
Java EE 6
Java EE 6Java EE 6
Java EE 6
 
CDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE DevelopmentCDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE Development
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDI
 
What we can expect from Java 9 by Ivan Krylov
What we can expect from Java 9 by Ivan KrylovWhat we can expect from Java 9 by Ivan Krylov
What we can expect from Java 9 by Ivan Krylov
 
CDI, Weld and the future of Seam
CDI, Weld and the future of SeamCDI, Weld and the future of Seam
CDI, Weld and the future of Seam
 
The Magnificent java EE 7 in Wildfly-O-Rama
The Magnificent java EE 7 in Wildfly-O-RamaThe Magnificent java EE 7 in Wildfly-O-Rama
The Magnificent java EE 7 in Wildfly-O-Rama
 
Devoxx Java Social and Agorava
Devoxx Java Social and AgoravaDevoxx Java Social and Agorava
Devoxx Java Social and Agorava
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
 
Fais ce que tu veux avec Java EE - Devoxx France 2014
Fais ce que tu veux avec Java EE - Devoxx France 2014Fais ce que tu veux avec Java EE - Devoxx France 2014
Fais ce que tu veux avec Java EE - Devoxx France 2014
 
Java one 2015 [con3339]
Java one 2015 [con3339]Java one 2015 [con3339]
Java one 2015 [con3339]
 
Architecting Large Enterprise Projects @DevConf.CZ
Architecting Large Enterprise Projects @DevConf.CZArchitecting Large Enterprise Projects @DevConf.CZ
Architecting Large Enterprise Projects @DevConf.CZ
 

Ähnlich wie Introduction to cdi given at java one 2014

softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
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 VRaptorCaelum
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzgKristijan Jurković
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Constanța Developers
 
How to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyHow to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyIordanis (Jordan) Giannakakis
 
Infinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using KotlinInfinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using KotlinInfinum
 

Ähnlich wie Introduction to cdi given at java one 2014 (20)

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
 
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
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
 
Popup view on Mortar
Popup view on MortarPopup view on Mortar
Popup view on Mortar
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
How to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happyHow to build rock solid apps & keep 100m+ users happy
How to build rock solid apps & keep 100m+ users happy
 
CDI in JEE6
CDI in JEE6CDI in JEE6
CDI in JEE6
 
Infinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using KotlinInfinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using Kotlin
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Test Engine
Test EngineTest Engine
Test Engine
 

Kürzlich hochgeladen

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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 textsMaria Levchenko
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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 SolutionsEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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 interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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...apidays
 
[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.pdfhans926745
 
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 MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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 organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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...
 
[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
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Introduction to cdi given at java one 2014

  • 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
  • 4. 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
  • 5. IMPLEMENTATIONS JBoss Weld (Reference Implementation) Apache Open WebBeans
  • 6. 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
  • 7. 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.
  • 9. THIS IS A BEAN public class HelloService { public String hello() { return "Hello World!"; } }
  • 10. DI IN CONSTRUCTOR public class MyBean { private HelloService service; @Inject public MyBean(HelloService service) { this.service = service; } }
  • 11. DI IN SETTER public class MyBean { private HelloService service; @Inject public void setService(HelloService service) { this.service = service; } }
  • 12. DI IN FIELD public class MyBean { @Inject private HelloService service; public void displayHello() { display(service.hello(); } }
  • 13. NO TYPE ERASURE IN CDI public class MyBean { @Inject Service<User> userService; @Inject Service<Staff> staffService; } This works
  • 14. USING QUALIFIERS TO DISTINGUISH BEANS OF THE SAME TYPE
  • 15. 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!"; } }
  • 16. …NEED QUALIFIERS… @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface French {} @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface English {}
  • 17. …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!"; } }
  • 18. 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(); } }
  • 19. 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 } }
  • 20. 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!"; } }
  • 21. 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(); } }
  • 22. MULTIPLE QUALIFIERS public class MyBean { @Inject @French HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 23. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 24. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 25. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  • 28. SOMETIMES CALLED “LAZY INJECTION” public class MyBean { @Inject Instance<HelloService> service; public void displayHello() { display( service.get().hello() ); } }
  • 29. CHECK BEAN EXISTENCE AT RUNTIME public class MyBean { @Inject Instance<HelloService> service; public void displayHello() { if (!service.isUnsatisfied()) { display( service.get().hello() ); } } }
  • 30. 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); }
  • 31. 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() ); } } }
  • 32. SELECT A QUALIFIER AT RUNTIME public class MyBean { @Inject @Any Instance<HelloService> services; public void displayHello() { display( service.select( new AnnotationLiteral()<French> {}) .get() ); } }
  • 34. 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
  • 35. CHOOSING THE RIGHT CONTEXT @SessionScoped public class CartBean { public void addItem(Item item) { ... } }
  • 36. CHOOSING THE RIGHT CONTEXT @ApplicationScoped public class CartBean { public void addItem(Item item) { ... } } FAIL !!!
  • 37. CONVERSATION IS MANAGE BY DEV @ConversationScoped public class CartBean { public void addItem(Item item) { ... } }
  • 38. NEW CONTEXTS CAN BE CREATED @ThreadScoped public class CartBean { public void addItem(Item item) { ... } }
  • 40. CREATING BEAN FROM ANY CLASS @Produces public MyNonCDIClass myProducer() { return new MyNonCdiClass(); } ... @Inject MyNonCDIClass bean;
  • 41. PRODUCERS MAY HAVE A SCOPE @Produces @RequestScoped public FacesContext produceFacesContext() { return FacesContext.getCurrentInstance(); }
  • 42. GETTING INFO FROM INJECTION POINT @Produces public Logger produceLog(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember() .getDeclaringClass().getName()); }
  • 43. REMEMBER : “NO TYPE ERASURE” @Produces public <K, V> Map<K, V> produceMap(InjectionPoint ip) { if (valueIsNumber(ip.getType())) { return new TreeMap<K, V>(); } return new HashMap<K, V>(); }
  • 45. 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()); } }
  • 46. 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) {} }
  • 47. 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) {} }
  • 48. 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) {} }
  • 50. A DECORATOR @Decorator @Priority(Interceptor.Priority.APPLICATION) public class HelloDecorator implements HelloService { // The decorated service may be restricted with qualifiers @Inject @Delegate HelloService service; public String hello() { return service.hello() + "-decorated"; } }
  • 51. INTERCEPTOR BINDING… @InterceptorBinding @Target({METHOD, TYPE}) @Retention(RUNTIME) public @interface Loggable {}
  • 52. …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()); } } }
  • 53. IT CAN BE PUT ON CLASS OR METHOD @Loggable public class MyBean { @Inject HelloService service; public void displayHello() { display( service.hello(); } }
  • 54. THAT’S ALL FOR BASIC CDI • If you want to learn advanced stuff come to : Going Farther with CDI 1.2 [CON5585] Monday 5:30pm • visit : http://cdi-spec.org • follow @cdispec and @antoine_sd on twitter • Questions ?