SlideShare a Scribd company logo
1 of 55
Download to read offline
@antoine_sd @cdispec#CDI2
CDI II is coming
Antoine Sabot-Durand
Red Hat
CDI spec lead
MicroProfile 1.0 Released!
Microservice Collaboration and Innovation in the Java Community
microprofilelunch.com, Thursday 11:30am - 2:00pm
Learn more at microprofile.io
MicroProfile BOF, Tuesday 10:30 - 11:30, Hilton Lombard Room

(3rd tower, 6th floor)
@antoine_sd @cdispec#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#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#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#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#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#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#CDI2
CDI 2.0 status
JSR 365 started in September 2014
EDR1 released in 2015
EDR2 released in august.
Weld 3 Aplha 17 is the RI for EDR2
Release expected in January 2017
@antoine_sd @cdispec#CDI2
cdi-spec.org
@antoine_sd @cdispec#CDI2
CDI 2.0 new features
@antoine_sd @cdispec#CDI2
Java SE support
using CDI outside Java EE
@antoine_sd @cdispec#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#CDI2
What did we do?
CDI Specification
CDI Core CDI for Java EECDI for Java SE
@antoine_sd @cdispec#CDI2
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();

}
Java SE bootstrap API
@antoine_sd @cdispec#CDI2
Enhancing events
Making popular feature even more popular
@antoine_sd @cdispec#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#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#CDI2
public void observer1(@Observes @Priority(1) Payload p) {
}
public void observer2(@Observes @Priority(2) Payload p) {
}
Events ordering
@antoine_sd @cdispec#CDI2
public class MyExtension implements Extension {



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

}

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

}



}
Events ordering in extensions
@antoine_sd @cdispec#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#CDI2
@Inject

Event<Payload> event;

public void someBSCriticalBusinessMethod() {

event.fire(new Payload());

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

// Do something with the event
}
Synchronous events - observing pattern
@antoine_sd @cdispec#CDI2
Events are sync in CDI 1
Right now:
All the observers are called in the firing thread
In no particular order (at least not specified)
The payload may be mutated
@antoine_sd @cdispec#CDI2
Events and contexts
Contexts:
Two contexts are critical: transactions and HTTP requests / sessions
Events are aware of those contexts
In an all-sync world, everything is fine
But in an async world, we will be in trouble
@antoine_sd @cdispec#CDI2
Asynchronous Events
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#CDI2
@Inject

Event<Payload> event;

public void someEvenMoreCriticalBusinessMethod() {


event.fireAsync(new Payload());

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

// I am called in another thread
}
Async events - observing pattern
@antoine_sd @cdispec#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#CDI2
@Inject

Event<PanelUpdater> event;

public void someOtherCriticalBusinessMethod() {


event.fireAsync(new PanelUpdater(green), 

executor);
}
Adding an Executor to fireAsync
@antoine_sd @cdispec#CDI2
@Inject

Event<PanelUpdater> event;

public void someOtherCriticalBusinessMethod() {


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

}
Async event in the GUI thread
@antoine_sd @cdispec#CDI2
@Inject

Event<PanelUpdater> event;

public void someOtherCriticalBusinessMethod() {


CompletionStage<PanelUpdater> stage = 

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

}
Handling exceptions
@antoine_sd @cdispec#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#CDI2
Handling exceptions
The Exception in fireAsync returned CompletionStage is
CompletionException
It holds all the exceptions in the suppressed exception set
@antoine_sd @cdispec#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#CDI2
SPI enhancement
New configurators for meta data
@antoine_sd @cdispec#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#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#CDI2
Example 1/7
First we need to implement an AnnotatedType to decorate the original one
and modify AnnotatedField set
@antoine_sd @cdispec#CDI2
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);

}

}

…
Example 2/7
@antoine_sd @cdispec#CDI2
…

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

return fields;

}

public Class<X> getJavaClass() {

return delegate.getJavaClass();

}

// 7 more similar methods


}

Example 3/7
@antoine_sd @cdispec#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#CDI2
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;

}

...
Example 5/7
@antoine_sd @cdispec#CDI2
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


}
Example 6/7
@antoine_sd @cdispec#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#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#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#CDI2
AOP enhancement
Support AOP on custom or produced bean
@antoine_sd @cdispec#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#CDI2
Support AOP on producer
Answer is probably the new InterceptionProxyFactory
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 InterceptionProxyFactory<T> {



InterceptionProxyFactory<T> ignoreFinalMethods();



AnnotatedTypeConfigurator<T> configure();



<T> T createInterceptionProxy(T InstanceToWrap);



}
@antoine_sd @cdispec#CDI2
@Produces

@RequestScoped

public MyClass createJpaEmAssumed(InterceptionProxyFactory<MyClass> ipf) {

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



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

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



return ipf.createInterceptionProxy(new MyClass());



}
Add @transaction on one produced bean method
@antoine_sd @cdispec#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#CDI2
Which JSR you’ll use 365 days a year?
…
JSR 365

More Related Content

What's hot

What's hot (20)

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
 
Binary Authorization in Kubernetes
Binary Authorization in KubernetesBinary Authorization in Kubernetes
Binary Authorization in Kubernetes
 
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
 
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
 
OpenDDR and Jakarta MVC - JavaLand 2021
OpenDDR and Jakarta MVC - JavaLand 2021OpenDDR and Jakarta MVC - JavaLand 2021
OpenDDR and Jakarta MVC - JavaLand 2021
 
Hands on React Native: From Zero to Hero
Hands on React  Native:  From Zero to HeroHands on React  Native:  From Zero to Hero
Hands on React Native: From Zero to Hero
 
Trying to build an Open Source browser in 2020
Trying to build an Open Source browser in 2020Trying to build an Open Source browser in 2020
Trying to build an Open Source browser in 2020
 
DevNexus 2019: MicroProfile and Jakarta EE - What's Next?
DevNexus 2019:  MicroProfile and Jakarta EE - What's Next?DevNexus 2019:  MicroProfile and Jakarta EE - What's Next?
DevNexus 2019: MicroProfile and Jakarta EE - What's Next?
 
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
 
Peering Inside the Black Box: A Case for Observability
Peering Inside the Black Box: A Case for ObservabilityPeering Inside the Black Box: A Case for Observability
Peering Inside the Black Box: A Case for Observability
 
Implementing Microservices with Jakarta EE and MicroProfile
Implementing Microservices with Jakarta EE and MicroProfileImplementing Microservices with Jakarta EE and MicroProfile
Implementing Microservices with Jakarta EE and MicroProfile
 
DevSecCon SG 2018 Fabian Presentation Slides
DevSecCon SG 2018 Fabian Presentation SlidesDevSecCon SG 2018 Fabian Presentation Slides
DevSecCon SG 2018 Fabian Presentation Slides
 
You Want to Kubernetes? You MUST Know Containers!
You Want to Kubernetes? You MUST Know Containers!You Want to Kubernetes? You MUST Know Containers!
You Want to Kubernetes? You MUST Know Containers!
 
WSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
WSO2Con EU 2015: Keynote - The Containerization of the Developer WorkspaceWSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
WSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
 
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
 
The DevSecOps Builder’s Guide to the CI/CD Pipeline
The DevSecOps Builder’s Guide to the CI/CD PipelineThe DevSecOps Builder’s Guide to the CI/CD Pipeline
The DevSecOps Builder’s Guide to the CI/CD Pipeline
 
Android's security architecture
Android's security architectureAndroid's security architecture
Android's security architecture
 
Declarative Import with Magento 2 Import Framework (M2IF)
Declarative Import with Magento 2 Import Framework (M2IF)Declarative Import with Magento 2 Import Framework (M2IF)
Declarative Import with Magento 2 Import Framework (M2IF)
 
MySQL Software Repositories
MySQL Software RepositoriesMySQL Software Repositories
MySQL Software Repositories
 

Viewers also liked

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
 

Viewers also liked (17)

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
 
Devoxx Java Social and Agorava
Devoxx Java Social and AgoravaDevoxx Java Social and Agorava
Devoxx Java Social and Agorava
 
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
 
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
 
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
 
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 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
 
Nashorn in the future (Japanese)
Nashorn in the future (Japanese)Nashorn in the future (Japanese)
Nashorn in the future (Japanese)
 
CDI In Real Life
CDI In Real LifeCDI In Real Life
CDI In Real Life
 
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
 
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
 
Architecting Large Enterprise Projects @DevConf.CZ
Architecting Large Enterprise Projects @DevConf.CZArchitecting Large Enterprise Projects @DevConf.CZ
Architecting Large Enterprise Projects @DevConf.CZ
 
Kids computer-programming
Kids computer-programmingKids computer-programming
Kids computer-programming
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 

Similar to CDI 2.0 is coming

Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...
JAXLondon2014
 

Similar to CDI 2.0 is coming (20)

Cdi from monolith to module
Cdi from monolith to moduleCdi from monolith to module
Cdi from monolith to module
 
How it's made - MyGet (CloudBurst)
How it's made - MyGet (CloudBurst)How it's made - MyGet (CloudBurst)
How it's made - MyGet (CloudBurst)
 
Prepare to defend thyself with Blue/Green
Prepare to defend thyself with Blue/GreenPrepare to defend thyself with Blue/Green
Prepare to defend thyself with Blue/Green
 
All Day DevOps 2016 Fabian - Defending Thyself with Blue Green
All Day DevOps 2016 Fabian - Defending Thyself with Blue GreenAll Day DevOps 2016 Fabian - Defending Thyself with Blue Green
All Day DevOps 2016 Fabian - Defending Thyself with Blue Green
 
DDD in Pixel Federation volume 2
DDD in Pixel Federation volume 2DDD in Pixel Federation volume 2
DDD in Pixel Federation volume 2
 
Liferay Italy Symposium 2015 Liferay Mobile SDK and Liferay Screens
Liferay Italy Symposium 2015 Liferay Mobile SDK and Liferay ScreensLiferay Italy Symposium 2015 Liferay Mobile SDK and Liferay Screens
Liferay Italy Symposium 2015 Liferay Mobile SDK and Liferay Screens
 
20131028 BTUG.be - BizTalk Deployment
20131028 BTUG.be - BizTalk Deployment20131028 BTUG.be - BizTalk Deployment
20131028 BTUG.be - BizTalk Deployment
 
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
 
Industrial IoT bootcamp
Industrial IoT bootcampIndustrial IoT bootcamp
Industrial IoT bootcamp
 
Building android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Cl...
Building  android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Cl...Building  android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Cl...
Building android apps with MVP, Dagger, Retrofit, Gson, JSON, Kotlin Data Cl...
 
Yann Albou & Sébastien Féré - GitOps as a way to manage enterprise K8s and vi...
Yann Albou & Sébastien Féré - GitOps as a way to manage enterprise K8s and vi...Yann Albou & Sébastien Féré - GitOps as a way to manage enterprise K8s and vi...
Yann Albou & Sébastien Féré - GitOps as a way to manage enterprise K8s and vi...
 
Continuous Delivery and Automated Operations on k8s with keptn
Continuous Delivery and Automated Operations on k8s with keptnContinuous Delivery and Automated Operations on k8s with keptn
Continuous Delivery and Automated Operations on k8s with keptn
 
Test-Driven Development in React with Cypress
Test-Driven Development in React with CypressTest-Driven Development in React with Cypress
Test-Driven Development in React with Cypress
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prod
 
Building and Deploying Microservices with Event Sourcing, CQRS and Docker
Building and Deploying Microservices with Event Sourcing, CQRS and DockerBuilding and Deploying Microservices with Event Sourcing, CQRS and Docker
Building and Deploying Microservices with Event Sourcing, CQRS and Docker
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?
 
Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...
 
#JaxLondon: Building microservices with Scala, functional domain models and S...
#JaxLondon: Building microservices with Scala, functional domain models and S...#JaxLondon: Building microservices with Scala, functional domain models and S...
#JaxLondon: Building microservices with Scala, functional domain models and S...
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
Angular 2 : learn TypeScript already with Angular 1
Angular 2 : learn TypeScript already with Angular 1Angular 2 : learn TypeScript already with Angular 1
Angular 2 : learn TypeScript already with Angular 1
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Recently uploaded (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
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
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
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
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
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
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

CDI 2.0 is coming

  • 1. @antoine_sd @cdispec#CDI2 CDI II is coming Antoine Sabot-Durand Red Hat CDI spec lead
  • 2. MicroProfile 1.0 Released! Microservice Collaboration and Innovation in the Java Community microprofilelunch.com, Thursday 11:30am - 2:00pm Learn more at microprofile.io MicroProfile BOF, Tuesday 10:30 - 11:30, Hilton Lombard Room
 (3rd tower, 6th floor)
  • 3. @antoine_sd @cdispec#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
  • 4. @antoine_sd @cdispec#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
  • 6. @antoine_sd @cdispec#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
  • 7. @antoine_sd @cdispec#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
  • 8. @antoine_sd @cdispec#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
  • 9. @antoine_sd @cdispec#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
  • 10. @antoine_sd @cdispec#CDI2 CDI 2.0 status JSR 365 started in September 2014 EDR1 released in 2015 EDR2 released in august. Weld 3 Aplha 17 is the RI for EDR2 Release expected in January 2017
  • 13. @antoine_sd @cdispec#CDI2 Java SE support using CDI outside Java EE
  • 14. @antoine_sd @cdispec#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
  • 15. @antoine_sd @cdispec#CDI2 What did we do? CDI Specification CDI Core CDI for Java EECDI for Java SE
  • 16. @antoine_sd @cdispec#CDI2 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();
 } Java SE bootstrap API
  • 17. @antoine_sd @cdispec#CDI2 Enhancing events Making popular feature even more popular
  • 18. @antoine_sd @cdispec#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
  • 19. @antoine_sd @cdispec#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
  • 20. @antoine_sd @cdispec#CDI2 public void observer1(@Observes @Priority(1) Payload p) { } public void observer2(@Observes @Priority(2) Payload p) { } Events ordering
  • 21. @antoine_sd @cdispec#CDI2 public class MyExtension implements Extension {
 
 public void firstPat(@Observes @Priority(1) ProcessAnnotatedType<?> pat) { …
 }
 public void secondPat(@Observes @Priority(2) ProcessAnnotatedType<?> pat) { …
 }
 
 } Events ordering in extensions
  • 22. @antoine_sd @cdispec#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…
  • 23. @antoine_sd @cdispec#CDI2 @Inject
 Event<Payload> event;
 public void someBSCriticalBusinessMethod() {
 event.fire(new Payload());
 } Synchronous events - firing pattern
  • 24. @antoine_sd @cdispec#CDI2 public void callMe(@Observes Payload payload) {
 // Do something with the event } Synchronous events - observing pattern
  • 25. @antoine_sd @cdispec#CDI2 Events are sync in CDI 1 Right now: All the observers are called in the firing thread In no particular order (at least not specified) The payload may be mutated
  • 26. @antoine_sd @cdispec#CDI2 Events and contexts Contexts: Two contexts are critical: transactions and HTTP requests / sessions Events are aware of those contexts In an all-sync world, everything is fine But in an async world, we will be in trouble
  • 27. @antoine_sd @cdispec#CDI2 Asynchronous Events 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
  • 28. @antoine_sd @cdispec#CDI2 @Inject
 Event<Payload> event;
 public void someEvenMoreCriticalBusinessMethod() { 
 event.fireAsync(new Payload());
 } Async events - firing pattern
  • 29. @antoine_sd @cdispec#CDI2 public void callMe(@ObservesAsync Payload payload) {
 // I am called in another thread } Async events - observing pattern
  • 30. @antoine_sd @cdispec#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
  • 31. @antoine_sd @cdispec#CDI2 @Inject
 Event<PanelUpdater> event;
 public void someOtherCriticalBusinessMethod() { 
 event.fireAsync(new PanelUpdater(green), 
 executor); } Adding an Executor to fireAsync
  • 32. @antoine_sd @cdispec#CDI2 @Inject
 Event<PanelUpdater> event;
 public void someOtherCriticalBusinessMethod() { 
 event.fireAsync(new PanelUpdater(green), SwingUtilities::invokeLater);
 } Async event in the GUI thread
  • 33. @antoine_sd @cdispec#CDI2 @Inject
 Event<PanelUpdater> event;
 public void someOtherCriticalBusinessMethod() { 
 CompletionStage<PanelUpdater> stage = 
 event.fireAsync(new PanelUpdater(green), SwingUtilities::invokeLater);
 } Handling exceptions
  • 34. @antoine_sd @cdispec#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
  • 35. @antoine_sd @cdispec#CDI2 Handling exceptions The Exception in fireAsync returned CompletionStage is CompletionException It holds all the exceptions in the suppressed exception set
  • 36. @antoine_sd @cdispec#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
  • 37. @antoine_sd @cdispec#CDI2 SPI enhancement New configurators for meta data
  • 38. @antoine_sd @cdispec#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
  • 39. @antoine_sd @cdispec#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
  • 40. @antoine_sd @cdispec#CDI2 Example 1/7 First we need to implement an AnnotatedType to decorate the original one and modify AnnotatedField set
  • 41. @antoine_sd @cdispec#CDI2 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);
 }
 }
 … Example 2/7
  • 42. @antoine_sd @cdispec#CDI2 …
 public Set<AnnotatedField<? super X>> getFields() {
 return fields;
 }
 public Class<X> getJavaClass() {
 return delegate.getJavaClass();
 }
 // 7 more similar methods 
 }
 Example 3/7
  • 43. @antoine_sd @cdispec#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());
 }
 …
  • 44. @antoine_sd @cdispec#CDI2 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;
 }
 ... Example 5/7
  • 45. @antoine_sd @cdispec#CDI2 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 
 } Example 6/7
  • 46. @antoine_sd @cdispec#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()));
 }
 }
  • 47. @antoine_sd @cdispec#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
  • 48. @antoine_sd @cdispec#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)); }
 }
  • 49. @antoine_sd @cdispec#CDI2 AOP enhancement Support AOP on custom or produced bean
  • 50.
  • 51. @antoine_sd @cdispec#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() { ... }
  • 52. @antoine_sd @cdispec#CDI2 Support AOP on producer Answer is probably the new InterceptionProxyFactory 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 InterceptionProxyFactory<T> {
 
 InterceptionProxyFactory<T> ignoreFinalMethods();
 
 AnnotatedTypeConfigurator<T> configure();
 
 <T> T createInterceptionProxy(T InstanceToWrap);
 
 }
  • 53. @antoine_sd @cdispec#CDI2 @Produces
 @RequestScoped
 public MyClass createJpaEmAssumed(InterceptionProxyFactory<MyClass> ipf) {
 AnnotatedTypeConfigurator<MyClass> atc = ipf.configure();
 
 atc.filterMethods(m -> m.getJavaMember().getName().equals("doSomething"))
 .findFirst() .ifPresent(m -> m.add(new AnnotationLiteral<Transactional>() { }));
 
 return ipf.createInterceptionProxy(new MyClass());
 
 } Add @transaction on one produced bean method
  • 54. @antoine_sd @cdispec#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
  • 55. @antoine_sd @cdispec#CDI2 Which JSR you’ll use 365 days a year? … JSR 365