SlideShare a Scribd company logo
1 of 59
Download to read offline
@antoine_sd @cdispec#Devoxx #CDI2
CDI 2.0 is upon us
Antoine Sabot-Durand
Red Hat
CDI spec lead
@antoine_sd @cdispec#Devoxx #CDI2
Me, Myself and I
Antoine Sabot-Durand
Software Engineer at Red Hat
CDI spec lead
CDI evangelist
Follow me: @antoine_sd
Follow CDI: @cdispec
@antoine_sd @cdispec#Devoxx #CDI2
Agenda
Flashback on CDI & CDI 2.0 status
CDI 2.0 new features
Java SE support
Enhancing events
Metadata configurators
Interceptor and Decorators on Produced / custom beans (coming)
Questions and Feedback
Previously on CDI
@antoine_sd @cdispec#Devoxx #CDI2
CDI Timeline
Dec 2009 June 2013 Apr 2014 Sep 2014
CDI1.0
(Java
EE
6)
CDI1.1
(Java
EE
7)
CDI1.2
(1.1
MR)
CDI2.0
Starts
jan 2017
CDI2.0
released
@antoine_sd @cdispec#Devoxx #CDI2
CDI 1.0 - December 2009
A well-defined lifecycle for stateful objects bound to lifecycle contexts
Where the set of contexts is extensible
A type-safe dependency injection mechanism without verbose configuration
Dependencies can be selected at development or deployment time
Type-safe decorators and interceptors
An event notification model
An SPI allowing portable extensions to integrate cleanly with the container
@antoine_sd @cdispec#Devoxx #CDI2
CDI 1.1 / 1.2 – June 2013 / April 2014
Add automatic enablement of CDI in Java EE
Add introspection with event, bean, decorator and interceptor meta data
Ease access to bean manager from outside CDI with CDI class
Add global enablement of interceptors using the @Priority annotation
Add Unmanaged allowing easy access to non-contexutal instances
Spec clarification
@antoine_sd @cdispec#Devoxx #CDI2
CDI 1.2 - April 2014
Clarification in the spec regarding:
CDI Lifecycle
Events
Reworking Bean defining annotation to avoid conflict with other JSR 330
frameworks
Clarification on conversation resolution
OSGi official support in the API
@antoine_sd @cdispec#Devoxx #CDI2
CDI 2.0 status
JSR 365 started in September 2014
EDR1 released in 2015
EDR2 released in august.
Weld 3 Alpha 17 is the RI for EDR2
Release expected in January 2017
@antoine_sd @cdispec#Devoxx #CDI2
cdi-spec.org
@antoine_sd @cdispec#Devoxx #CDI2
CDI 2.0 new features
@antoine_sd @cdispec#Devoxx #CDI2
Java SE support
using CDI outside Java EE
@antoine_sd @cdispec#Devoxx #CDI2
Java SE support - Why?
To align on many other Java EE spec which support Java SE bootstrapping
To boost CDI adoption for Spec and Frameworks
To provide a mean of building new stacks out of Java EE
@antoine_sd @cdispec#Devoxx #CDI2
What did we do?
CDI Specification
CDI Core CDI for Java EECDI for Java SE
@antoine_sd @cdispec#Devoxx #CDI2
Java SE bootstrap API
public static void main(String[] args) {



SeContainer container = SeContainerInitializer.newInstance()

.disableDiscovery()

.addBeanClasses(MyService.class)

.initialize();



MyService service = container.select(MyService.class).get();



service.sayHello();



container.close();

}
@antoine_sd @cdispec#Devoxx #CDI2
Controlling the Request Context
In Java SE, most of our built-in contexts are unavailable:
Request context
Session context
Conversation context
That’s why we added tools to activate Request context programmatically
This feature is also available for Java EE
@antoine_sd @cdispec#Devoxx #CDI2
Controlling the Request Context
@ApplicationScoped

public class MyBean {



@Inject

private RequestContextController requestContextController;



public void doRequest(String body) {

// activate request context

requestContextController.activate();



// do work in a request context.



// deactivate the request context

requestContextController.deactivate();

}



}
@antoine_sd @cdispec#Devoxx #CDI2
In interceptor mode
@ApplicationScoped

public class MyBean {



@ActivateRequestContext

public void doRequest(String body) {

// Request Context will be activated during this invocation

}

}
@antoine_sd @cdispec#Devoxx #CDI2
Enhancing events
Making popular feature even more popular
@antoine_sd @cdispec#Devoxx #CDI2
Enhancing events
CDI events are a very loved feature
We took a very long time to see how to enhance them
In CDI 2.0 we are introducing
Event ordering
Asynchronous events
@antoine_sd @cdispec#Devoxx #CDI2
Events ordering
By adding a @Priority (from commons annotations) on an observer.
The lowest value is first
Observers with no explicit priority have a middle range priority
Allowing observer to be called last
Observer with the same priority are called in an undefined order
No priority on async events
@antoine_sd @cdispec#Devoxx #CDI2
Events ordering
public void observer1(@Observes @Priority(1) Payload p) {
}
public void observer2(@Observes @Priority(2) Payload p) {
}
@antoine_sd @cdispec#Devoxx #CDI2
Events ordering in extensions
public class MyExtension implements Extension {



public void firstPat(@Observes @Priority(1) ProcessAnnotatedType<?> pat) {
…

}

public void secondPat(@Observes @Priority(2) ProcessAnnotatedType<?> pat) {
…

}



}
@antoine_sd @cdispec#Devoxx #CDI2
CDI 1.x: Sync / Async
Sync / Async is not specified
The immutable status of the payload is not specified
Implementations use a Sync model
The payload is mutated in some implementations / framework
Going async “blindly” might raise problems…
@antoine_sd @cdispec#Devoxx #CDI2
Synchronous events - firing pattern
@Inject

Event<Payload> event;

public void someBSCriticalBusinessMethod() {

event.fire(new Payload());

}
@antoine_sd @cdispec#Devoxx #CDI2
Synchronous events - observing pattern
public void callMe(@Observes Payload payload) {

// Do something with the event
}
@antoine_sd @cdispec#Devoxx #CDI2
Events are sync in CDI 1
All the observers are called in the firing thread
In no particular order (at least not specified)
The payload may be mutated
Observers may inject beans
Observers are aware of Transactional and security contexts
@antoine_sd @cdispec#Devoxx #CDI2
Asynchronous Events
Async events can’t:
Mute Payload
Access CDI contexts states at the firing point
Be transactional
So designing backward compatible async events is more tricky than it looks:
A currently sync event should remain sync
Going sync / async should be a decision taken from the firing side
Being sync should be possible from the observing side
@antoine_sd @cdispec#Devoxx #CDI2
Async events - firing pattern
@Inject

Event<Payload> event;

public void someEvenMoreCriticalBusinessMethod() {


event.fireAsync(new Payload());

}
@antoine_sd @cdispec#Devoxx #CDI2
Async events - observing pattern
public void callMe(@ObservesAsync Payload payload) {

// I am called in another thread
}
@antoine_sd @cdispec#Devoxx #CDI2
Sync vs Async Events in a nutshell
callMe(@Observes payload) callMe(@ObservesAsync payload)
event.fire(payload) Sync call Not notified
event.fireAsync(payload) Not notified Async call
@antoine_sd @cdispec#Devoxx #CDI2
Adding an Executor to fireAsync
@Inject

Event<PanelUpdater> event;

public void someOtherCriticalBusinessMethod() {


event.fireAsync(new PanelUpdater(green), 

executor);
}
@antoine_sd @cdispec#Devoxx #CDI2
Async event in the GUI thread
@Inject

Event<PanelUpdater> event;

public void someOtherCriticalBusinessMethod() {


event.fireAsync(new PanelUpdater(green),
SwingUtilities::invokeLater);

}
@antoine_sd @cdispec#Devoxx #CDI2
Handling exceptions
@Inject

Event<PanelUpdater> event;

public void someOtherCriticalBusinessMethod() {


CompletionStage<PanelUpdater> stage = 

event.fireAsync(new PanelUpdater(green),
SwingUtilities::invokeLater);

}
@antoine_sd @cdispec#Devoxx #CDI2
Handling exceptions
Exception in one async observer doesn’t stop execution as in sync observer
One of the reasons why firing async event doesn’t trigger sync observers
Event.fireAsync returns a CompletionStage
Allowing integration of async events in standard Java 8 async pipeline
@antoine_sd @cdispec#Devoxx #CDI2
Handling exceptions
The Exception in fireAsync returned CompletionStage is
CompletionException
It holds all the exceptions in the suppressed exception set
@antoine_sd @cdispec#Devoxx #CDI2
Handling exceptions
Exception handling is done with the Standard Java 8 async api, with:
stage.whenComplete() to deal with result or exception
stage.handle() same as above but allows transformation of stage
stage.exceptionally() to only treat exception case
@antoine_sd @cdispec#Devoxx #CDI2
SPI enhancement
New configurators for meta data
@antoine_sd @cdispec#Devoxx #CDI2
Standard annotations instances
CDI makes an heavy use of Annotations
Java doesn’t provide easy way to create an annotation instance
We provided AnnotationLiteral, to help users create their instances
Annotation instance = new AnnotationLiteral<ApplicationScoped>(){};
@antoine_sd @cdispec#Devoxx #CDI2
When members are here a class has to be created
public class NamedLiteral extends AnnotationLiteral<Named> implements Named{



private String value;



public NamedLiteral(String value) {

this.value = value;

}



@Override

public String value() {

return null;

}

}
@antoine_sd @cdispec#Devoxx #CDI2
CDI 2.0 provides helpers out of the box
ApplicationScoped literal = ApplicationScoped.Literal.INSTANCE;


Named literal2 = NamedLiteral.of("myName");

@antoine_sd @cdispec#Devoxx #CDI2
Configurators for meta-data
Some meta-data are very verbose to create
AnnotatedType
Bean
InjectionPoint
ObserverMethod
If you only need to add info to an existing meta-data, it’s very boring
@antoine_sd @cdispec#Devoxx #CDI2
Example with CDI 1.2
I have a legacy framework
I want to adapt it for CDI
I need to detect all @CacheContext annotations on fields…
...And transform them in injection point
I’ll use an extension to replace @CacheContext annotation by @Inject in
AnnotatedTypes
@antoine_sd @cdispec#Devoxx #CDI2
Example 1/7
First we need to implement an AnnotatedType to decorate the original one
and modify AnnotatedField set
@antoine_sd @cdispec#Devoxx #CDI2
Example 2/7
public class AutoInjectingAnnotatedType<X> implements AnnotatedType<X> {



private final AnnotatedType<X> delegate;

private final Set<AnnotatedField<? super X>> fields;



public AutoInjectingAnnotatedType(AnnotatedType<X> delegate) {

this.delegate = delegate;

fields = new HashSet<>();

for (AnnotatedField<? super X> field : delegate.getFields()) {

if (field.isAnnotationPresent(CacheContext.class))

fields.add(new AutoInjectingAnnotatedField(field));

else

fields.add(field);

}

}

…
@antoine_sd @cdispec#Devoxx #CDI2
Example 3/7
…

public Set<AnnotatedField<? super X>> getFields() {

return fields;

}

public Class<X> getJavaClass() {

return delegate.getJavaClass();

}

// 7 more similar methods


}

@antoine_sd @cdispec#Devoxx #CDI2
Example 4/7
Then we need to do the same for AnnotatedField to add @Inject to the
field annotations set
public class AutoInjectingAnnotatedField<X> implements AnnotatedField<X> {



private final Set<Annotation> annotations;

private final AnnotatedField<X> delegate;



public AutoInjectingAnnotatedField(AnnotatedField<X> delegate) {

this.delegate = delegate;

annotations = new HashSet<>(delegate.getAnnotations());

annotations.add(new InjectLiteral());

}

…
@antoine_sd @cdispec#Devoxx #CDI2
Example 5/7
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {

if (annotationType.equals(Inject.class))

return (T) new InjectLiteral();

return delegate.getAnnotation(annotationType);

}



public Set<Annotation> getAnnotations() {

return annotations;

}

...
@antoine_sd @cdispec#Devoxx #CDI2
Example 6/7
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {

if (annotationType.equals(Inject.class))

return true;

return delegate.isAnnotationPresent(annotationType);

}
public Set<Type> getTypeClosure() {

return delegate.getTypeClosure();

}

// 4 similar methods


}
@antoine_sd @cdispec#Devoxx #CDI2
Example 7/7
Finaly we need to write the extension to use our custom AnnotatedType
and AnnotatedField
public class AutoInjectExtension implements Extension {



public <T> void CreateIP(
@Observes @WithAnnotations(CacheContext.class)
ProcessAnnotatedType<T> pat) {

pat.setAnnotatedType(
new AutoInjectingAnnotatedType<T>(pat.getAnnotatedType()));

}

}
@antoine_sd @cdispec#Devoxx #CDI2
In CDI 2.0
We introduced configurators, helping creation of these metadata
This configurators are accessible thru container lifecycle events
They are automatically built by the container at the end of
observer invocation
@antoine_sd @cdispec#Devoxx #CDI2
In CDI 2.0
All the previous code fits in this extension
public class AutoInjectExtension implements Extension {



public <T> void CreateIP(
@Observes @WithAnnotations(CacheContext.class) ProcessAnnotatedType<T> pat)
{

pat.configureAnnotatedType().filterFields(
f -> f.isAnnotationPresent(CacheContext.class)
)

.forEach(f -> f.add(InjectLiteral.INSTANCE));
}

}
@antoine_sd @cdispec#Devoxx #CDI2
AOP enhancement
Support AOP on custom or produced bean
@antoine_sd @cdispec#Devoxx #CDI2
Support AOP on producer
In CDI 1.x you cannot bind an interceptor to a produced bean
When you write:
@Transactional is applied to producer method
@Produces

@Transactional
public MyService produceService() {
...
}
@antoine_sd @cdispec#Devoxx #CDI2
Support Interceptor on producer
Answer is probably the new InterceptionFactory
This factory uses an AnnotatedType to know where adding interceptor bindings in
the class
Could also be used in Custom Bean create method
public interface InterceptionFactory<T> {



InterceptionProxyFactory<T> ignoreFinalMethods();



AnnotatedTypeConfigurator<T> configure();



<T> T createInterceptedInstance(T InstanceToWrap);



}
@antoine_sd @cdispec#Devoxx #CDI2
Add @transaction on one produced bean method
@Produces

@RequestScoped

public MyClass createJpaEmAssumed(InterceptionFactory<MyClass> ify) {

AnnotatedTypeConfigurator<MyClass> atc = ify.configure();



atc.filterMethods(m -> m.getJavaMember().getName().equals("doSomething"))

.findFirst()
.ifPresent(m -> m.add(new AnnotationLiteral<Transactional>() { }));



return ify.createInterceptedInstance(new MyClass());



}
@antoine_sd @cdispec#Devoxx #CDI2
CDI 2.0 needs you
CDI 2.0 specification is open to everyone
Come on join us on the mailing list and IRC channel
All infos on http://cdi-spec.org or by following to @cdispec on
twitter
The more we are the more we’ll deliver
@antoine_sd @cdispec#Devoxx #CDI2
Which JSR you’ll use 365 days a year?
…
JSR 365

More Related Content

What's hot

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
 

What's hot (20)

CDI In Real Life
CDI In Real LifeCDI In Real Life
CDI In Real Life
 
New York Kubernetes: CI/CD Patterns for Kubernetes
New York Kubernetes: CI/CD Patterns for KubernetesNew York Kubernetes: CI/CD Patterns for Kubernetes
New York Kubernetes: CI/CD Patterns for Kubernetes
 
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
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
 
基於 Flow & Path 的 MVP 架構
基於 Flow & Path 的 MVP 架構基於 Flow & Path 的 MVP 架構
基於 Flow & Path 的 MVP 架構
 
OpenDDR and Jakarta MVC - JavaLand 2021
OpenDDR and Jakarta MVC - JavaLand 2021OpenDDR and Jakarta MVC - JavaLand 2021
OpenDDR and Jakarta MVC - JavaLand 2021
 
Binary Authorization in Kubernetes
Binary Authorization in KubernetesBinary Authorization in Kubernetes
Binary Authorization in Kubernetes
 
Android NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo NativoAndroid NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo Nativo
 
Software Supply Chain Management with Grafeas and Kritis
Software Supply Chain Management with Grafeas and KritisSoftware Supply Chain Management with Grafeas and Kritis
Software Supply Chain Management with Grafeas and Kritis
 
Scala on androids
Scala on androidsScala on androids
Scala on androids
 
Common primitives in Docker environments
Common primitives in Docker environmentsCommon primitives in Docker environments
Common primitives in Docker environments
 
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plansOpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
OpenDaylight Developers Experience 1.5: Eclipse Setup, HOT reload, future plans
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
 
MicroProfile for MicroServices
MicroProfile for MicroServicesMicroProfile for MicroServices
MicroProfile for MicroServices
 
Steelcon 2015 Reverse-Engineering Obfuscated Android Applications
Steelcon 2015 Reverse-Engineering Obfuscated Android ApplicationsSteelcon 2015 Reverse-Engineering Obfuscated Android Applications
Steelcon 2015 Reverse-Engineering Obfuscated Android Applications
 
Spring Up Your Graph
Spring Up Your GraphSpring Up Your Graph
Spring Up Your Graph
 
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
 
BMO - Intelligent Projects with Maven
BMO - Intelligent Projects with MavenBMO - Intelligent Projects with Maven
BMO - Intelligent Projects with Maven
 
AOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformAOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java Platform
 
OSGi, Eclipse and API Tooling
OSGi, Eclipse and API ToolingOSGi, Eclipse and API Tooling
OSGi, Eclipse and API Tooling
 

Similar to CDI 2.0 is upon us Devoxx

CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
telestax
 

Similar to CDI 2.0 is upon us Devoxx (20)

3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
 
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
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Angular%201%20to%20angular%202
Angular%201%20to%20angular%202Angular%201%20to%20angular%202
Angular%201%20to%20angular%202
 
Deep Dive OpenShitt on Azure & .NET Core on OpenShift
Deep Dive OpenShitt on Azure & .NET Core on OpenShiftDeep Dive OpenShitt on Azure & .NET Core on OpenShift
Deep Dive OpenShitt on Azure & .NET Core on OpenShift
 
Sapphire Gimlets
Sapphire GimletsSapphire Gimlets
Sapphire Gimlets
 
Cleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsCleaning your architecture with android architecture components
Cleaning your architecture with android architecture components
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
 
Guice gin
Guice ginGuice gin
Guice gin
 
Intro to Eclipse Che, by Tyler Jewell
Intro to Eclipse Che, by Tyler JewellIntro to Eclipse Che, by Tyler Jewell
Intro to Eclipse Che, by Tyler Jewell
 
Java EE Connector Architecture 1.6 (JSR 322) Technology
Java EE Connector Architecture 1.6 (JSR 322) TechnologyJava EE Connector Architecture 1.6 (JSR 322) Technology
Java EE Connector Architecture 1.6 (JSR 322) Technology
 
How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
.net Framework
.net Framework.net Framework
.net Framework
 
Don't Deploy Into the Dark: DORA Metrics for your K8s GitOps Deployments
Don't Deploy Into the Dark: DORA Metrics for your K8s GitOps DeploymentsDon't Deploy Into the Dark: DORA Metrics for your K8s GitOps Deployments
Don't Deploy Into the Dark: DORA Metrics for your K8s GitOps Deployments
 
apidays Australia 2022 - Spinning Your Drones with Cadence Workflows and Apac...
apidays Australia 2022 - Spinning Your Drones with Cadence Workflows and Apac...apidays Australia 2022 - Spinning Your Drones with Cadence Workflows and Apac...
apidays Australia 2022 - Spinning Your Drones with Cadence Workflows and Apac...
 
Cdi from monolith to module
Cdi from monolith to moduleCdi from monolith to module
Cdi from monolith to module
 

More from Antoine Sabot-Durand

More from Antoine Sabot-Durand (9)

What's new in CDI 2.0
What's new in CDI 2.0What's new in CDI 2.0
What's new in CDI 2.0
 
Mute Java EE DNA with CDI
Mute Java EE DNA with CDI Mute Java EE DNA with CDI
Mute Java EE DNA with CDI
 
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
 
Going further with CDI 1.2
Going further with CDI 1.2Going further with CDI 1.2
Going further with CDI 1.2
 
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
 
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
 
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
 
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
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

CDI 2.0 is upon us Devoxx

  • 1. @antoine_sd @cdispec#Devoxx #CDI2 CDI 2.0 is upon us Antoine Sabot-Durand Red Hat CDI spec lead
  • 2. @antoine_sd @cdispec#Devoxx #CDI2 Me, Myself and I Antoine Sabot-Durand Software Engineer at Red Hat CDI spec lead CDI evangelist Follow me: @antoine_sd Follow CDI: @cdispec
  • 3. @antoine_sd @cdispec#Devoxx #CDI2 Agenda Flashback on CDI & CDI 2.0 status CDI 2.0 new features Java SE support Enhancing events Metadata configurators Interceptor and Decorators on Produced / custom beans (coming) Questions and Feedback
  • 5. @antoine_sd @cdispec#Devoxx #CDI2 CDI Timeline Dec 2009 June 2013 Apr 2014 Sep 2014 CDI1.0 (Java EE 6) CDI1.1 (Java EE 7) CDI1.2 (1.1 MR) CDI2.0 Starts jan 2017 CDI2.0 released
  • 6. @antoine_sd @cdispec#Devoxx #CDI2 CDI 1.0 - December 2009 A well-defined lifecycle for stateful objects bound to lifecycle contexts Where the set of contexts is extensible A type-safe dependency injection mechanism without verbose configuration Dependencies can be selected at development or deployment time Type-safe decorators and interceptors An event notification model An SPI allowing portable extensions to integrate cleanly with the container
  • 7. @antoine_sd @cdispec#Devoxx #CDI2 CDI 1.1 / 1.2 – June 2013 / April 2014 Add automatic enablement of CDI in Java EE Add introspection with event, bean, decorator and interceptor meta data Ease access to bean manager from outside CDI with CDI class Add global enablement of interceptors using the @Priority annotation Add Unmanaged allowing easy access to non-contexutal instances Spec clarification
  • 8. @antoine_sd @cdispec#Devoxx #CDI2 CDI 1.2 - April 2014 Clarification in the spec regarding: CDI Lifecycle Events Reworking Bean defining annotation to avoid conflict with other JSR 330 frameworks Clarification on conversation resolution OSGi official support in the API
  • 9. @antoine_sd @cdispec#Devoxx #CDI2 CDI 2.0 status JSR 365 started in September 2014 EDR1 released in 2015 EDR2 released in august. Weld 3 Alpha 17 is the RI for EDR2 Release expected in January 2017
  • 12. @antoine_sd @cdispec#Devoxx #CDI2 Java SE support using CDI outside Java EE
  • 13. @antoine_sd @cdispec#Devoxx #CDI2 Java SE support - Why? To align on many other Java EE spec which support Java SE bootstrapping To boost CDI adoption for Spec and Frameworks To provide a mean of building new stacks out of Java EE
  • 14. @antoine_sd @cdispec#Devoxx #CDI2 What did we do? CDI Specification CDI Core CDI for Java EECDI for Java SE
  • 15. @antoine_sd @cdispec#Devoxx #CDI2 Java SE bootstrap API public static void main(String[] args) {
 
 SeContainer container = SeContainerInitializer.newInstance()
 .disableDiscovery()
 .addBeanClasses(MyService.class)
 .initialize();
 
 MyService service = container.select(MyService.class).get();
 
 service.sayHello();
 
 container.close();
 }
  • 16. @antoine_sd @cdispec#Devoxx #CDI2 Controlling the Request Context In Java SE, most of our built-in contexts are unavailable: Request context Session context Conversation context That’s why we added tools to activate Request context programmatically This feature is also available for Java EE
  • 17. @antoine_sd @cdispec#Devoxx #CDI2 Controlling the Request Context @ApplicationScoped
 public class MyBean {
 
 @Inject
 private RequestContextController requestContextController;
 
 public void doRequest(String body) {
 // activate request context
 requestContextController.activate();
 
 // do work in a request context.
 
 // deactivate the request context
 requestContextController.deactivate();
 }
 
 }
  • 18. @antoine_sd @cdispec#Devoxx #CDI2 In interceptor mode @ApplicationScoped
 public class MyBean {
 
 @ActivateRequestContext
 public void doRequest(String body) {
 // Request Context will be activated during this invocation
 }
 }
  • 19. @antoine_sd @cdispec#Devoxx #CDI2 Enhancing events Making popular feature even more popular
  • 20. @antoine_sd @cdispec#Devoxx #CDI2 Enhancing events CDI events are a very loved feature We took a very long time to see how to enhance them In CDI 2.0 we are introducing Event ordering Asynchronous events
  • 21. @antoine_sd @cdispec#Devoxx #CDI2 Events ordering By adding a @Priority (from commons annotations) on an observer. The lowest value is first Observers with no explicit priority have a middle range priority Allowing observer to be called last Observer with the same priority are called in an undefined order No priority on async events
  • 22. @antoine_sd @cdispec#Devoxx #CDI2 Events ordering public void observer1(@Observes @Priority(1) Payload p) { } public void observer2(@Observes @Priority(2) Payload p) { }
  • 23. @antoine_sd @cdispec#Devoxx #CDI2 Events ordering in extensions public class MyExtension implements Extension {
 
 public void firstPat(@Observes @Priority(1) ProcessAnnotatedType<?> pat) { …
 }
 public void secondPat(@Observes @Priority(2) ProcessAnnotatedType<?> pat) { …
 }
 
 }
  • 24. @antoine_sd @cdispec#Devoxx #CDI2 CDI 1.x: Sync / Async Sync / Async is not specified The immutable status of the payload is not specified Implementations use a Sync model The payload is mutated in some implementations / framework Going async “blindly” might raise problems…
  • 25. @antoine_sd @cdispec#Devoxx #CDI2 Synchronous events - firing pattern @Inject
 Event<Payload> event;
 public void someBSCriticalBusinessMethod() {
 event.fire(new Payload());
 }
  • 26. @antoine_sd @cdispec#Devoxx #CDI2 Synchronous events - observing pattern public void callMe(@Observes Payload payload) {
 // Do something with the event }
  • 27. @antoine_sd @cdispec#Devoxx #CDI2 Events are sync in CDI 1 All the observers are called in the firing thread In no particular order (at least not specified) The payload may be mutated Observers may inject beans Observers are aware of Transactional and security contexts
  • 28. @antoine_sd @cdispec#Devoxx #CDI2 Asynchronous Events Async events can’t: Mute Payload Access CDI contexts states at the firing point Be transactional So designing backward compatible async events is more tricky than it looks: A currently sync event should remain sync Going sync / async should be a decision taken from the firing side Being sync should be possible from the observing side
  • 29. @antoine_sd @cdispec#Devoxx #CDI2 Async events - firing pattern @Inject
 Event<Payload> event;
 public void someEvenMoreCriticalBusinessMethod() { 
 event.fireAsync(new Payload());
 }
  • 30. @antoine_sd @cdispec#Devoxx #CDI2 Async events - observing pattern public void callMe(@ObservesAsync Payload payload) {
 // I am called in another thread }
  • 31. @antoine_sd @cdispec#Devoxx #CDI2 Sync vs Async Events in a nutshell callMe(@Observes payload) callMe(@ObservesAsync payload) event.fire(payload) Sync call Not notified event.fireAsync(payload) Not notified Async call
  • 32. @antoine_sd @cdispec#Devoxx #CDI2 Adding an Executor to fireAsync @Inject
 Event<PanelUpdater> event;
 public void someOtherCriticalBusinessMethod() { 
 event.fireAsync(new PanelUpdater(green), 
 executor); }
  • 33. @antoine_sd @cdispec#Devoxx #CDI2 Async event in the GUI thread @Inject
 Event<PanelUpdater> event;
 public void someOtherCriticalBusinessMethod() { 
 event.fireAsync(new PanelUpdater(green), SwingUtilities::invokeLater);
 }
  • 34. @antoine_sd @cdispec#Devoxx #CDI2 Handling exceptions @Inject
 Event<PanelUpdater> event;
 public void someOtherCriticalBusinessMethod() { 
 CompletionStage<PanelUpdater> stage = 
 event.fireAsync(new PanelUpdater(green), SwingUtilities::invokeLater);
 }
  • 35. @antoine_sd @cdispec#Devoxx #CDI2 Handling exceptions Exception in one async observer doesn’t stop execution as in sync observer One of the reasons why firing async event doesn’t trigger sync observers Event.fireAsync returns a CompletionStage Allowing integration of async events in standard Java 8 async pipeline
  • 36. @antoine_sd @cdispec#Devoxx #CDI2 Handling exceptions The Exception in fireAsync returned CompletionStage is CompletionException It holds all the exceptions in the suppressed exception set
  • 37. @antoine_sd @cdispec#Devoxx #CDI2 Handling exceptions Exception handling is done with the Standard Java 8 async api, with: stage.whenComplete() to deal with result or exception stage.handle() same as above but allows transformation of stage stage.exceptionally() to only treat exception case
  • 38. @antoine_sd @cdispec#Devoxx #CDI2 SPI enhancement New configurators for meta data
  • 39. @antoine_sd @cdispec#Devoxx #CDI2 Standard annotations instances CDI makes an heavy use of Annotations Java doesn’t provide easy way to create an annotation instance We provided AnnotationLiteral, to help users create their instances Annotation instance = new AnnotationLiteral<ApplicationScoped>(){};
  • 40. @antoine_sd @cdispec#Devoxx #CDI2 When members are here a class has to be created public class NamedLiteral extends AnnotationLiteral<Named> implements Named{
 
 private String value;
 
 public NamedLiteral(String value) {
 this.value = value;
 }
 
 @Override
 public String value() {
 return null;
 }
 }
  • 41. @antoine_sd @cdispec#Devoxx #CDI2 CDI 2.0 provides helpers out of the box ApplicationScoped literal = ApplicationScoped.Literal.INSTANCE; 
 Named literal2 = NamedLiteral.of("myName");

  • 42. @antoine_sd @cdispec#Devoxx #CDI2 Configurators for meta-data Some meta-data are very verbose to create AnnotatedType Bean InjectionPoint ObserverMethod If you only need to add info to an existing meta-data, it’s very boring
  • 43. @antoine_sd @cdispec#Devoxx #CDI2 Example with CDI 1.2 I have a legacy framework I want to adapt it for CDI I need to detect all @CacheContext annotations on fields… ...And transform them in injection point I’ll use an extension to replace @CacheContext annotation by @Inject in AnnotatedTypes
  • 44. @antoine_sd @cdispec#Devoxx #CDI2 Example 1/7 First we need to implement an AnnotatedType to decorate the original one and modify AnnotatedField set
  • 45. @antoine_sd @cdispec#Devoxx #CDI2 Example 2/7 public class AutoInjectingAnnotatedType<X> implements AnnotatedType<X> {
 
 private final AnnotatedType<X> delegate;
 private final Set<AnnotatedField<? super X>> fields;
 
 public AutoInjectingAnnotatedType(AnnotatedType<X> delegate) {
 this.delegate = delegate;
 fields = new HashSet<>();
 for (AnnotatedField<? super X> field : delegate.getFields()) {
 if (field.isAnnotationPresent(CacheContext.class))
 fields.add(new AutoInjectingAnnotatedField(field));
 else
 fields.add(field);
 }
 }
 …
  • 46. @antoine_sd @cdispec#Devoxx #CDI2 Example 3/7 …
 public Set<AnnotatedField<? super X>> getFields() {
 return fields;
 }
 public Class<X> getJavaClass() {
 return delegate.getJavaClass();
 }
 // 7 more similar methods 
 }

  • 47. @antoine_sd @cdispec#Devoxx #CDI2 Example 4/7 Then we need to do the same for AnnotatedField to add @Inject to the field annotations set public class AutoInjectingAnnotatedField<X> implements AnnotatedField<X> {
 
 private final Set<Annotation> annotations;
 private final AnnotatedField<X> delegate;
 
 public AutoInjectingAnnotatedField(AnnotatedField<X> delegate) {
 this.delegate = delegate;
 annotations = new HashSet<>(delegate.getAnnotations());
 annotations.add(new InjectLiteral());
 }
 …
  • 48. @antoine_sd @cdispec#Devoxx #CDI2 Example 5/7 public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
 if (annotationType.equals(Inject.class))
 return (T) new InjectLiteral();
 return delegate.getAnnotation(annotationType);
 }
 
 public Set<Annotation> getAnnotations() {
 return annotations;
 }
 ...
  • 49. @antoine_sd @cdispec#Devoxx #CDI2 Example 6/7 public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
 if (annotationType.equals(Inject.class))
 return true;
 return delegate.isAnnotationPresent(annotationType);
 } public Set<Type> getTypeClosure() {
 return delegate.getTypeClosure();
 }
 // 4 similar methods 
 }
  • 50. @antoine_sd @cdispec#Devoxx #CDI2 Example 7/7 Finaly we need to write the extension to use our custom AnnotatedType and AnnotatedField public class AutoInjectExtension implements Extension {
 
 public <T> void CreateIP( @Observes @WithAnnotations(CacheContext.class) ProcessAnnotatedType<T> pat) {
 pat.setAnnotatedType( new AutoInjectingAnnotatedType<T>(pat.getAnnotatedType()));
 }
 }
  • 51. @antoine_sd @cdispec#Devoxx #CDI2 In CDI 2.0 We introduced configurators, helping creation of these metadata This configurators are accessible thru container lifecycle events They are automatically built by the container at the end of observer invocation
  • 52. @antoine_sd @cdispec#Devoxx #CDI2 In CDI 2.0 All the previous code fits in this extension public class AutoInjectExtension implements Extension {
 
 public <T> void CreateIP( @Observes @WithAnnotations(CacheContext.class) ProcessAnnotatedType<T> pat) {
 pat.configureAnnotatedType().filterFields( f -> f.isAnnotationPresent(CacheContext.class) )
 .forEach(f -> f.add(InjectLiteral.INSTANCE)); }
 }
  • 53. @antoine_sd @cdispec#Devoxx #CDI2 AOP enhancement Support AOP on custom or produced bean
  • 54.
  • 55. @antoine_sd @cdispec#Devoxx #CDI2 Support AOP on producer In CDI 1.x you cannot bind an interceptor to a produced bean When you write: @Transactional is applied to producer method @Produces
 @Transactional public MyService produceService() { ... }
  • 56. @antoine_sd @cdispec#Devoxx #CDI2 Support Interceptor on producer Answer is probably the new InterceptionFactory This factory uses an AnnotatedType to know where adding interceptor bindings in the class Could also be used in Custom Bean create method public interface InterceptionFactory<T> {
 
 InterceptionProxyFactory<T> ignoreFinalMethods();
 
 AnnotatedTypeConfigurator<T> configure();
 
 <T> T createInterceptedInstance(T InstanceToWrap);
 
 }
  • 57. @antoine_sd @cdispec#Devoxx #CDI2 Add @transaction on one produced bean method @Produces
 @RequestScoped
 public MyClass createJpaEmAssumed(InterceptionFactory<MyClass> ify) {
 AnnotatedTypeConfigurator<MyClass> atc = ify.configure();
 
 atc.filterMethods(m -> m.getJavaMember().getName().equals("doSomething"))
 .findFirst() .ifPresent(m -> m.add(new AnnotationLiteral<Transactional>() { }));
 
 return ify.createInterceptedInstance(new MyClass());
 
 }
  • 58. @antoine_sd @cdispec#Devoxx #CDI2 CDI 2.0 needs you CDI 2.0 specification is open to everyone Come on join us on the mailing list and IRC channel All infos on http://cdi-spec.org or by following to @cdispec on twitter The more we are the more we’ll deliver
  • 59. @antoine_sd @cdispec#Devoxx #CDI2 Which JSR you’ll use 365 days a year? … JSR 365