SlideShare a Scribd company logo
1 of 23
Context and Dependency Injection 2.0
Brian S Paskin, Senior Application Architect, R&D Services, IBM Cloud Innovations Lab
Updated 17 January 2019
WebSphere Liberty Lunch and Learn
What is Context and Dependency Injection?
2
 Context and Dependency Injection (CDI) is part of the Java Enterprise Edition (JEE)
specification (JSR-299 and JSR-330)
– Context: Manage the lifecycle of stateful components using domain specific lifecycle
contexts (Application, Request, Session, et cetera)
– Dependency Injection: Injection of loosely coupled components into client Objects
 CDI provides
– Type safety by injecting objects using a String name and is resolved by using Java types
 Qualifiers can further distinguish Objects
– Nearly all Objects can be injected (POJOs, EJBs, PersistenceUnit, et cetera)
– Allows for extending the of JEE platform without changing core behavior using the
Service Provider Interface (SPI) that is vendor independent
– Using Interceptors to inject code without having to changing the original code, but cannot
do business logic
– Using Decorators to inject code without having to change the original code, and can do
business logic
– Multiple Events can be triggered synchronously or asynchronous that are loosely coupled
– Integrated support for Expression Language (EL)
Configuration file
3
 CDI does require a configuration file called beans.xml under certain circumstances
– Belongs under the WEB-INF directory for web applications
– Belongs under META-INF directory for jar or EJB applications
– Needed for Interceptors, Decorators and Alternatives
– Needed for changing default discovery mode, which is annotated.
 Bean discover modes
– None – CDI is disabled
– Annotated (default) – only class level annotations are processed
– All – All components are processed
Configuration file
4
<beans bean-discovery-mode="all"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd">
<interceptors>
<class>com.ibm.example.cdi.interceptor.LoggingInterceptor</class>
</interceptors>
<decorators>
<class>com.ibm.example.cdi.decorator.LoggingDecorator</class>
</decorators>
<alternatives>
<class>com.ibm.example.cdi.alternative.FavoriteDoctorAlternative</class>
</alternatives>
</beans>
Simple Injection
5
 @Inject is used to specify that an Object is to be injected into the current client Object
 An Object that implements an Interface can be injected
– An interface can be injected in cases where there is only one Object implementing it
@Inject private City city;
Retrieving Beans By Name
6
 When more than one Object implements an Interface @Named should be used
– Class should be annotated with @Named
– If no @Named is found, then the class name is used by default
– @Inject must include @Named
@Named("Rome")
public class Rome implements City {
@Named("Cologne")
public class Cologne implements City {
@Inject @Named("Rome") private City city;
Lazy Injection
7
 When the Interface is known, but not Objects that implement the interface are not known
– Dynamically obtain instances of Beans using Instance<T>
– Each instance can be acted upon
@Inject private Instance<City> instance;
Context Scopes
8
 Tells the container when a Bean is created and destroyed
 Objects are annotated with a context scope
– Objects not annotated are given the default annotation @Dependent
 @Dependent – serves exactly one client Bean and has the same lifecycle of the client Bean
 @RequestScoped – lasts through a single HTTP request
 @SessionScoped – lasts through multiple HTTP requests
 @ApplicationScoped – lasts through the entire life of the application for all users
 @ConversationScope – exists in developer controlled boundaries across multiple
requests and long running conversations.
– Session boundaries cannot be crossed
 Developers can create their own scopes @RequestScoped
public class ScopeBean1 {
@ApplicationScoped
public class ScopeBean2 {
Qualifiers
9
 Provides various implementations of a particular type of bean
– Uses @Qualifer with the @Retention policy and @Target elements
 @Retention is how long annotations with the annotated type are to be retained
– Usually Runtime, the default, since CDI works with injection at runtime
 @Target specifies the program elements that the Qualifier can apply
 The name of the Qualifier is the annotation that is applied to a bean
@Qualifier
@Target({ TYPE, FIELD, METHOD, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Favorite {
@Favorite
public class NewFavoriteDoctor extends FavoriteDoctor {
@Inject @Favorite private FavoriteDoctor doctor2;
Producers
10
 Provides a way to inject Objects that are not Beans
 Executes the @Produces annotated method when the Object is injected
– Can include a scope
 Requires a Qualifier to specify that the injection will run the annotated method on the Bean
 Disposers are optional and are called at end of life and take the parameter of the Object that
is produced and is annotated with @Disposes
@Retention(RUNTIME)
@Target({ TYPE, FIELD, METHOD, PARAMETER })
public @interface Favorite {
public @Produces @Favorite String getDoctor() {
@Inject @Favorite String name;
public void regenerate(@Disposes String instance) {
Events
11
 CDI Events are based on the Observer/Observable pattern
– Does not require compile time dependencies
– Events can be synchronous or asynchronous
– Can trigger multiple events with priority
 A Qualifier is required
 An Object is created that represents the Event type
– The methods would define if the events are intercepted synchronously or asynchronously
and their priority
 The Event<T> is injected with the Qualifier in an Object that needs to fire events
 There are built in events
– beginRequest, endRequest, beginSession, endSession
Events
12
@Qualifier
@Retention(RUNTIME)
@Target({ TYPE, FIELD, METHOD, PARAMETER })
public @interface Doctor {
public void firstObserver(@Observes
@Priority(Interceptor.Priority.APPLICATION) @Doctor Regenerate doctor)
public void secondObserver(@Observes
@Priority(Interceptor.Priority.APPLICATION+1) @Doctor Regenerate doctor)
@Inject @Doctor private Event<Regenerate> doctor;
doctor.fire(new Regenerate());
Interceptors and Decorators
13
 Both are part of aspect oriented mechanism
 Interceptors are technically oriented and used mainly for transactions, security, and logging
– Can be bound to any bean or bean method
 Decorators are business oriented and are used to chain the behavior of a bean
– Bound to a bean class
 Both require entries in the beans.xml to active or @Priority to specify globally
<interceptors>
<class>com.ibm.example.cdi.interceptor.LoggingInterceptor</class>
</interceptors>
<decorators>
<class>com.ibm.example.cdi.decorator.LoggingDecorator</class>
</decorators>
Interceptors
14
 Interceptors usually contain the annotation @AroundInvoke which specifies the method to
be run when the interceptor is invoked
 The methods @PostConstruct, @PreDestroy, @PrePassivate, and @PostActivate
to specify lifecycle callback interceptors
 The method @AroundTimeout can be used to specify an EJB timeout interceptor
 Interceptor classes can contain more than one Interceptor methods but only one of each type
 One or more Interceptor Binding Types must be defined
– Associate annotation with target bean or method
– Similar to Qualifiers but annotated with @InterceptorBinding
– Can include the annotation @Inherited to specify it can be inherited by the superclass
– May declare other Interceptor Bindings
 Interceptor classes are annotated with @Interceptor and the Interceptor Binding
 @AroundInvoke takes an InovationContext parameter and can throw an Exception
Interceptors
15
@InterceptorBinding
@Inherited
@Target({TYPE, METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logging {
@Interceptor
@Logging
public class LoggingInterceptor {
@AroundInvoke
public Object doLog (InvocationContext ctx)
throws Exception {
@RequestScoped
public class InterceptorBean {
@Logging
public String doHello() {
@Inject InterceptorBean bean;
Interceptors
16
@RequestScoped
public class DoctorWho {
@PostConstruct
private void setDoctor() {
@PreDestroy
private void regenerate() {
@Inject private DoctorWho doctor;
doctor.getDoctor();
Decorators
17
 Decorators implement an interface and are annotated with the annotation @Decorator
 More than Decorator can be called with the annotation @Priority and providing the order
 A Delegate injection entry point is required using @Delegate
– Can be field, constructor parameter, or initializer method
– Allows to get handle of called Object
– Only one Delegate is allowed per Decorator
 The code in Decorator overrides the code in the actual class using the Delegate
Decorators
18
public interface Logging {
public class LoggingEntry implements Logging {
@Decorator
public class LoggingDecorator implements Logging {
@Inject @Delegate @Any
private Logging logging;
@Inject private LoggingEntry entry;
Alternatives
19
 Used when there is more than one version of a Bean and is determined at deployment time
 The class that is a different version is annotated with @Alternative
 The Alternative class must be placed in the beans.xml to activate
 Multiple Alternative classes can be invoked using @Priority and providing the order
Alternatives
20
public interface Doctor {
public class FavoriteDoctor implements Doctor {
@Alternative
public class FavoriteDoctorAlternative implements Doctor {
@Inject private Doctor doctor;
<alternatives>
<class>com.ibm.example.cdi.alternative.FavoriteDoctorAlternative</class>
</alternatives>
Utilizing the BeanManager
21
 The BeanManager allows for extensions to interact with the container
 Any Bean can injected the BeanManager
 An instance of the BeanManager can be obtained using JNDI looking up
java:comp/BeanManager
 Once obtained can use introspection on Beans or change certain behaviors of CDI
@Inject private BeanManager bm;
More information
22
 Context and Dependency Injection for Java EE (JEE 8)
 Examples used for this presentations from GitHub
 Learning CDI
Context and Dependency Injection 2.0

More Related Content

What's hot

JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...Jorge Hidalgo
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Raffi Khatchadourian
 
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) TechnologySivakumar Thyagarajan
 
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiJDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiPROIDEA
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for ProductivityDavid Noble
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
[Blackhat2015] FileCry attack against Java
[Blackhat2015] FileCry attack against Java[Blackhat2015] FileCry attack against Java
[Blackhat2015] FileCry attack against JavaMoabi.com
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-examdmz networks
 
ICPC 2012 - Mining Source Code Descriptions
ICPC 2012 - Mining Source Code DescriptionsICPC 2012 - Mining Source Code Descriptions
ICPC 2012 - Mining Source Code DescriptionsSebastiano Panichella
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification QuestionsSpringMockExams
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practiceGuo Albert
 
Enterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin BlockEnterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin Blockmcgurk
 
Enterprise Library 3.0 Overview
Enterprise Library 3.0 OverviewEnterprise Library 3.0 Overview
Enterprise Library 3.0 Overviewmcgurk
 
LDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionLDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionChema Alonso
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxRohit Radhakrishnan
 

What's hot (20)

JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
Java annotations
Java annotationsJava annotations
Java annotations
 
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
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiJDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
[Blackhat2015] FileCry attack against Java
[Blackhat2015] FileCry attack against Java[Blackhat2015] FileCry attack against Java
[Blackhat2015] FileCry attack against Java
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-exam
 
ICPC 2012 - Mining Source Code Descriptions
ICPC 2012 - Mining Source Code DescriptionsICPC 2012 - Mining Source Code Descriptions
ICPC 2012 - Mining Source Code Descriptions
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practice
 
Enterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin BlockEnterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin Block
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Enterprise Library 3.0 Overview
Enterprise Library 3.0 OverviewEnterprise Library 3.0 Overview
Enterprise Library 3.0 Overview
 
Struts2
Struts2Struts2
Struts2
 
LDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionLDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP Injection
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 

Similar to Context and Dependency Injection 2.0

OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Androidemanuelez
 
Context and Dependency Injection
Context and Dependency InjectionContext and Dependency Injection
Context and Dependency InjectionWerner Keil
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataWaheed Nazir
 
2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-DurandSOAT
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)Peter Antman
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIos890
 
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...Sigma Software
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
FileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docxFileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docxssuser454af01
 
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6Saltmarch Media
 
Summer industrial trainingnew
Summer industrial trainingnewSummer industrial trainingnew
Summer industrial trainingnewVignesh Ramesh
 
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemSpark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemArun Gupta
 

Similar to Context and Dependency Injection 2.0 (20)

OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Java EE 6
Java EE 6Java EE 6
Java EE 6
 
Context and Dependency Injection
Context and Dependency InjectionContext and Dependency Injection
Context and Dependency Injection
 
Spring boot
Spring bootSpring boot
Spring boot
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
 
2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
Struts
StrutsStruts
Struts
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODI
 
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
 
Spring training
Spring trainingSpring training
Spring training
 
FileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docxFileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docx
 
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
 
Summer industrial trainingnew
Summer industrial trainingnewSummer industrial trainingnew
Summer industrial trainingnew
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemSpark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
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.comFatema Valibhai
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
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 ApplicationsAlberto González Trastoy
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
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 Modelsaagamshah0812
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Recently uploaded (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
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
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
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
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

Context and Dependency Injection 2.0

  • 1. Context and Dependency Injection 2.0 Brian S Paskin, Senior Application Architect, R&D Services, IBM Cloud Innovations Lab Updated 17 January 2019 WebSphere Liberty Lunch and Learn
  • 2. What is Context and Dependency Injection? 2  Context and Dependency Injection (CDI) is part of the Java Enterprise Edition (JEE) specification (JSR-299 and JSR-330) – Context: Manage the lifecycle of stateful components using domain specific lifecycle contexts (Application, Request, Session, et cetera) – Dependency Injection: Injection of loosely coupled components into client Objects  CDI provides – Type safety by injecting objects using a String name and is resolved by using Java types  Qualifiers can further distinguish Objects – Nearly all Objects can be injected (POJOs, EJBs, PersistenceUnit, et cetera) – Allows for extending the of JEE platform without changing core behavior using the Service Provider Interface (SPI) that is vendor independent – Using Interceptors to inject code without having to changing the original code, but cannot do business logic – Using Decorators to inject code without having to change the original code, and can do business logic – Multiple Events can be triggered synchronously or asynchronous that are loosely coupled – Integrated support for Expression Language (EL)
  • 3. Configuration file 3  CDI does require a configuration file called beans.xml under certain circumstances – Belongs under the WEB-INF directory for web applications – Belongs under META-INF directory for jar or EJB applications – Needed for Interceptors, Decorators and Alternatives – Needed for changing default discovery mode, which is annotated.  Bean discover modes – None – CDI is disabled – Annotated (default) – only class level annotations are processed – All – All components are processed
  • 5. Simple Injection 5  @Inject is used to specify that an Object is to be injected into the current client Object  An Object that implements an Interface can be injected – An interface can be injected in cases where there is only one Object implementing it @Inject private City city;
  • 6. Retrieving Beans By Name 6  When more than one Object implements an Interface @Named should be used – Class should be annotated with @Named – If no @Named is found, then the class name is used by default – @Inject must include @Named @Named("Rome") public class Rome implements City { @Named("Cologne") public class Cologne implements City { @Inject @Named("Rome") private City city;
  • 7. Lazy Injection 7  When the Interface is known, but not Objects that implement the interface are not known – Dynamically obtain instances of Beans using Instance<T> – Each instance can be acted upon @Inject private Instance<City> instance;
  • 8. Context Scopes 8  Tells the container when a Bean is created and destroyed  Objects are annotated with a context scope – Objects not annotated are given the default annotation @Dependent  @Dependent – serves exactly one client Bean and has the same lifecycle of the client Bean  @RequestScoped – lasts through a single HTTP request  @SessionScoped – lasts through multiple HTTP requests  @ApplicationScoped – lasts through the entire life of the application for all users  @ConversationScope – exists in developer controlled boundaries across multiple requests and long running conversations. – Session boundaries cannot be crossed  Developers can create their own scopes @RequestScoped public class ScopeBean1 { @ApplicationScoped public class ScopeBean2 {
  • 9. Qualifiers 9  Provides various implementations of a particular type of bean – Uses @Qualifer with the @Retention policy and @Target elements  @Retention is how long annotations with the annotated type are to be retained – Usually Runtime, the default, since CDI works with injection at runtime  @Target specifies the program elements that the Qualifier can apply  The name of the Qualifier is the annotation that is applied to a bean @Qualifier @Target({ TYPE, FIELD, METHOD, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface Favorite { @Favorite public class NewFavoriteDoctor extends FavoriteDoctor { @Inject @Favorite private FavoriteDoctor doctor2;
  • 10. Producers 10  Provides a way to inject Objects that are not Beans  Executes the @Produces annotated method when the Object is injected – Can include a scope  Requires a Qualifier to specify that the injection will run the annotated method on the Bean  Disposers are optional and are called at end of life and take the parameter of the Object that is produced and is annotated with @Disposes @Retention(RUNTIME) @Target({ TYPE, FIELD, METHOD, PARAMETER }) public @interface Favorite { public @Produces @Favorite String getDoctor() { @Inject @Favorite String name; public void regenerate(@Disposes String instance) {
  • 11. Events 11  CDI Events are based on the Observer/Observable pattern – Does not require compile time dependencies – Events can be synchronous or asynchronous – Can trigger multiple events with priority  A Qualifier is required  An Object is created that represents the Event type – The methods would define if the events are intercepted synchronously or asynchronously and their priority  The Event<T> is injected with the Qualifier in an Object that needs to fire events  There are built in events – beginRequest, endRequest, beginSession, endSession
  • 12. Events 12 @Qualifier @Retention(RUNTIME) @Target({ TYPE, FIELD, METHOD, PARAMETER }) public @interface Doctor { public void firstObserver(@Observes @Priority(Interceptor.Priority.APPLICATION) @Doctor Regenerate doctor) public void secondObserver(@Observes @Priority(Interceptor.Priority.APPLICATION+1) @Doctor Regenerate doctor) @Inject @Doctor private Event<Regenerate> doctor; doctor.fire(new Regenerate());
  • 13. Interceptors and Decorators 13  Both are part of aspect oriented mechanism  Interceptors are technically oriented and used mainly for transactions, security, and logging – Can be bound to any bean or bean method  Decorators are business oriented and are used to chain the behavior of a bean – Bound to a bean class  Both require entries in the beans.xml to active or @Priority to specify globally <interceptors> <class>com.ibm.example.cdi.interceptor.LoggingInterceptor</class> </interceptors> <decorators> <class>com.ibm.example.cdi.decorator.LoggingDecorator</class> </decorators>
  • 14. Interceptors 14  Interceptors usually contain the annotation @AroundInvoke which specifies the method to be run when the interceptor is invoked  The methods @PostConstruct, @PreDestroy, @PrePassivate, and @PostActivate to specify lifecycle callback interceptors  The method @AroundTimeout can be used to specify an EJB timeout interceptor  Interceptor classes can contain more than one Interceptor methods but only one of each type  One or more Interceptor Binding Types must be defined – Associate annotation with target bean or method – Similar to Qualifiers but annotated with @InterceptorBinding – Can include the annotation @Inherited to specify it can be inherited by the superclass – May declare other Interceptor Bindings  Interceptor classes are annotated with @Interceptor and the Interceptor Binding  @AroundInvoke takes an InovationContext parameter and can throw an Exception
  • 15. Interceptors 15 @InterceptorBinding @Inherited @Target({TYPE, METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Logging { @Interceptor @Logging public class LoggingInterceptor { @AroundInvoke public Object doLog (InvocationContext ctx) throws Exception { @RequestScoped public class InterceptorBean { @Logging public String doHello() { @Inject InterceptorBean bean;
  • 16. Interceptors 16 @RequestScoped public class DoctorWho { @PostConstruct private void setDoctor() { @PreDestroy private void regenerate() { @Inject private DoctorWho doctor; doctor.getDoctor();
  • 17. Decorators 17  Decorators implement an interface and are annotated with the annotation @Decorator  More than Decorator can be called with the annotation @Priority and providing the order  A Delegate injection entry point is required using @Delegate – Can be field, constructor parameter, or initializer method – Allows to get handle of called Object – Only one Delegate is allowed per Decorator  The code in Decorator overrides the code in the actual class using the Delegate
  • 18. Decorators 18 public interface Logging { public class LoggingEntry implements Logging { @Decorator public class LoggingDecorator implements Logging { @Inject @Delegate @Any private Logging logging; @Inject private LoggingEntry entry;
  • 19. Alternatives 19  Used when there is more than one version of a Bean and is determined at deployment time  The class that is a different version is annotated with @Alternative  The Alternative class must be placed in the beans.xml to activate  Multiple Alternative classes can be invoked using @Priority and providing the order
  • 20. Alternatives 20 public interface Doctor { public class FavoriteDoctor implements Doctor { @Alternative public class FavoriteDoctorAlternative implements Doctor { @Inject private Doctor doctor; <alternatives> <class>com.ibm.example.cdi.alternative.FavoriteDoctorAlternative</class> </alternatives>
  • 21. Utilizing the BeanManager 21  The BeanManager allows for extensions to interact with the container  Any Bean can injected the BeanManager  An instance of the BeanManager can be obtained using JNDI looking up java:comp/BeanManager  Once obtained can use introspection on Beans or change certain behaviors of CDI @Inject private BeanManager bm;
  • 22. More information 22  Context and Dependency Injection for Java EE (JEE 8)  Examples used for this presentations from GitHub  Learning CDI