SlideShare a Scribd company logo
1 of 36
CDI – Contexts andCDI – Contexts and
Dependency Injection for theDependency Injection for the
JavaEE platform (JSR299)JavaEE platform (JSR299)
Bozhidar Bozhanov
Bulgarian Association of Software Developers
www.devbg.org
About meAbout me
• Senior Java Developer at Fish4
• 3+ years experience with Spring and
dependency injection
• Implementor of JSR-299 as a university
project
• Committer at Hector (Java Cassandra API)
• http://techblog.bozho.net
Dependency injection?Dependency injection?
• Classes define what are their dependencies,
not how they obtain them
• Object dependencies are set externally
• Unit-test and mocking friendly
• DI frameworks - objects are managed and
have a lifecycle
HistoryHistory
• Theoretical basis - GoF Hollywood principle;
Steffano Mazzocchi
• Spring – 2002/2003, Rod Johnson
• Pico Container - 2003
• Martin Fowler popularized the term - 2004
• JBoss Seam, Google Guice, EJB 3.0
• Contexts and Dependency Injection (JSR-
299, JavaEE 6) - 2006-2009
Current problemsCurrent problems
• Problematic integration between JavaEE
components
• „Crippled“ dependency-injection in EJB
• No standard – only propriatary DI
frameworks (spring, guice, seam)
• Extended reliance on string qualifiers (no
compile-time safety)
JSR-299JSR-299
• What's a JSR?
• CDI Initially named „Web Beans“
• Expert Group formed in June 2006, spec-lead
is Gavin King
• Early draft (2007), Public review (2008), Final
draft (mid-2009), Ralease (Dec 2009)
• Bob Lee (Guice) left the expert group
• IBM voted „No“, Google voted „Yes“,
VMware (SpringSource) and Eclipse didn't
vote.
What is CDIWhat is CDI
• Type-safe DI framework (based on Seam,
Guice and Spring)
• Uses JSR-330 (Dependency Injection for
Java), lead by Rod Johnson (Spring) and Bob
Lee (Guice), which defines only DI
annotations (for JavaSE)
• DI JavaEE-wide – JSF managed beans, EJB,
JavaEE Resources
Implementations; web profileImplementations; web profile
• Three implementations: JBoss Weld, Apache
OpenWebBeans and Resin CanDI
• Only one stable at the moment – Weld, used
in Glassfish v3 and JBoss AS (5.2, 6)
• JavaEE 6 has the so-called „profiles“. CDI is
part of the „Web profile“
• CDI implementations are not limited to
application servers (with the help of
extensions)
Java EE structure with CDIJava EE structure with CDI
Beans and bean archivesBeans and bean archives
• A bean archive has META-INF/beans.xml
• All classes within a bean archive are beans,
and eligible for injection
• All classes in outside bean archives are not
beans
• Beans can have type(s), scope, EL name,
qualifiers, interceptors.
• Beans can be JSF beans, EJBs, JavaEE
resources
• @javax.inject.Inject is used:@javax.inject.Inject is used:
InjectionInjection
publicpublic classclass OrdersBean {OrdersBean {
@Inject@Inject privateprivate OrdersDaoOrdersDao daodao;;
}}
• The „dao“ field is called „injection point“.The „dao“ field is called „injection point“.
Injection point types are:Injection point types are:
• FieldField
• ConstructorConstructor
• SetterSetter
• InitializerInitializer
Injection pointsInjection points
publicpublic classclass OrdersBean {OrdersBean {
@Inject@Inject privateprivate OrdersDaoOrdersDao daodao;;
@Inject@Inject
publicpublic OrdersBean(OrdersDao dao){}OrdersBean(OrdersDao dao){}
@Inject@Inject
publicpublic voidvoid init(OrdersDao dao) {}init(OrdersDao dao) {}
@Inject@Inject
publicpublic voidvoid setOrdersDao(OrdersDao dao){}setOrdersDao(OrdersDao dao){}
}}
• Inject into:Inject into:
– POJOsPOJOs
– EJB Session BeansEJB Session Beans
– ServletsServlets
• Injection candidates:Injection candidates:
– POJOsPOJOs
– EJB Session BeansEJB Session Beans
– JavaEE ResourcesJavaEE Resources
Injection targetsInjection targets
Bean scopesBean scopes
• Built-in scopes (normal vs pseudo):
• @ApplicationScoped – i.e. Singleton
• @RequestScoped – created on http request
• @SessionScoped – within a HttpSession
• @ConversationScoped – between request
and session
• @Dependent (default, pseudo) – the object
lives as long as the object it is injected into
• Custom scopes
• @Named(@Named(""beanNamebeanName"")). Defaults to the. Defaults to the
decapitalized, simple name of the classdecapitalized, simple name of the class
• Used in EL expressions:Used in EL expressions:
Bean nameBean name
<<h:outputTexth:outputText
valuevalue=="#{orderBean.order.price}""#{orderBean.order.price}" />/>
• Used in injections (discouraged)Used in injections (discouraged)
@Inject@Inject @Named@Named(("ordersBean""ordersBean"))
privateprivate OrdersBeanOrdersBean orderBeanorderBean;;
• Qualifiers are annotations (unlike in spring):Qualifiers are annotations (unlike in spring):
QualifiersQualifiers
@Qualifier //retention & target ommitted@Qualifier //retention & target ommitted
publicpublic @interface@interface SynchronousSynchronous {}{}
• Qualifiers are used to differentiate beans with the sameQualifiers are used to differentiate beans with the same
type:type:
@@InjectInject @@SynchronousSynchronous
privateprivate CreditCardProcessor processor;CreditCardProcessor processor;
@@SynchronousSynchronous
publicpublic classclass SynchronousCreditCardProcessorSynchronousCreditCardProcessor
implementsimplements CreditCardProcessor {..}CreditCardProcessor {..}
@@AsynchronousAsynchronous
publicpublic classclass AsyncCreditCardProcessorAsyncCreditCardProcessor
implementsimplements CreditCardPRocessor {..}CreditCardPRocessor {..}
• @Any@Any – all beans have this, unless they have– all beans have this, unless they have @New@New
• @Default, @Named@Default, @Named
• @New@New –– forces the container to return a new beanforces the container to return a new bean
instance each timeinstance each time
Built-in qualifiersBuilt-in qualifiers
@@NewNew publicpublic classclass SomeBean {..}SomeBean {..}
publicpublic classclass AnotherBean {AnotherBean {
@@Inject SomeBean bean1;Inject SomeBean bean1;
@@Inject SomeBean bean2;Inject SomeBean bean2;
@@PostConstructPostConstruct voidvoid init() {init() {
// false// false
System.out.println(bean1 == bean2);System.out.println(bean1 == bean2);
}}
}}
• Stereotypes are used to reduce the amountStereotypes are used to reduce the amount
of boilerplate code:of boilerplate code:
StereotypesStereotypes
@@StereotypeStereotype //denoting a stereotype//denoting a stereotype
@@NamedNamed // built-in qualifier// built-in qualifier
@@RequestScopedRequestScoped // scope// scope
publicpublic @interface@interface
RequestScopedSecureBean {}RequestScopedSecureBean {}
@@RequestScopedNamedRequestScopedNamed BeanBean
publicpublic classclass OrdersBean {..}OrdersBean {..}
DemoDemo
(Beans, Injection, Qualifiers, Stereotypes, EL)
• A way to utilize complex constructionA way to utilize complex construction
• Allow non-beans to be injected (i.e. 3Allow non-beans to be injected (i.e. 3rdrd
partyparty
classes outside a bean-archive)classes outside a bean-archive)
• Handles object disposalHandles object disposal
ProducersProducers
//this class is within a bean archive//this class is within a bean archive
classclass ConnectionProducer {ConnectionProducer {
@Produces@Produces Connection createConnection() {Connection createConnection() {
// create and return jdbc connection// create and return jdbc connection
}}
// when the object gets out of scope// when the object gets out of scope
voidvoid dispose(dispose(@Disposes@Disposes Connection con) {Connection con) {
con.close();con.close();
}}
}}
• Allow injecting JavaEE resources:Allow injecting JavaEE resources:
Producer fieldsProducer fields
@@ProducesProduces @@SomeTopicSomeTopic
@@Resource(name=Resource(name="topics/SomeTopic""topics/SomeTopic"))
privateprivate Topic someTopic;Topic someTopic;
@@ProducesProduces
@@PersistenceContextPersistenceContext
privateprivate EntityManager entityManager;EntityManager entityManager;
@@ProducesProduces // non-JaveEE producer field// non-JaveEE producer field
privateprivate Some3rdPartyBean bean =Some3rdPartyBean bean =
newnew Some3rdPartyBean();Some3rdPartyBean();
• Gives information about the injection pointGives information about the injection point
Injection point metadataInjection point metadata
@@Produces Logger createLogger(InjectionPointProduces Logger createLogger(InjectionPoint
injectionPoint) {injectionPoint) {
returnreturn Logger.getLogger(injectionPointLogger.getLogger(injectionPoint
.getMember().getDeclaringClass());.getMember().getDeclaringClass());
}}
@Produces@Produces @@HttpParam(HttpParam(""""))
String getParamValue(ServletRequest request,String getParamValue(ServletRequest request,
InjectionPoint ip) {InjectionPoint ip) {
returnreturn request.getParameter(iprequest.getParameter(ip
.getAnnotation(HttpParam..getAnnotation(HttpParam.class)class).value());.value());
}}
}}
• Decorators decorate all interfaces theyDecorators decorate all interfaces they
implementimplement
• @Delegate@Delegate is used to inject the originalis used to inject the original
objectobject
• Decorators must be explicitly listed inDecorators must be explicitly listed in
beans.xml, in their respective orderbeans.xml, in their respective order
• Decorators can be abstractDecorators can be abstract
DecoratorsDecorators
@@DecoratorDecorator
publicpublic classclass LogDecoratorLogDecorator implementsimplements Logger {Logger {
@@DelegateDelegate @@AnyAny privateprivate LoggerLogger loggerlogger;;
@Override@Override
publicpublic voidvoid log(String msg) {log(String msg) {
loggerlogger.log(timestamp() +.log(timestamp() + ":"":" + msg);+ msg);
}}
}}
• Interceptor bindings (can be nested or includedInterceptor bindings (can be nested or included
in stereotypes)in stereotypes)
InterceptorsInterceptors
@@InterceptorBindingInterceptorBinding // + retention & target// + retention & target
publicpublic @interface@interface TransactionalTransactional{}{}
@@InterceptorBindings @TransactionalInterceptorBindings @Transactional
publicpublic @interface@interface DataAccessDataAccess {}{}
• Declaring the actual interceptor:Declaring the actual interceptor:
@@TransactionalTransactional @@InterceptorInterceptor
publicpublic classclass TransactionInterceptor {TransactionInterceptor {
@@AroundInvokeAroundInvoke
publicpublic Object manage(InvocationContext ctx)Object manage(InvocationContext ctx)
throwsthrows Exception { .. }Exception { .. }
}}
• Declaring the interceptor on the target beanDeclaring the interceptor on the target bean
Interceptors (2)Interceptors (2)
@@TransactionalTransactional //all methods are transactional//all methods are transactional
public classpublic class OrderService { .. }OrderService { .. }
• Like decorators, must be enabled in beans.xmlLike decorators, must be enabled in beans.xml
• Interceptors-to-intercepted targets: many-to-Interceptors-to-intercepted targets: many-to-
manymany
• Interceptors-to-interceptor bindings: many-to-Interceptors-to-interceptor bindings: many-to-
manymany
• Binding vsBinding vs @NonBinding@NonBinding interceptor attributesinterceptor attributes
DemoDemo
(Producers, Decorators, Interceptors)
Programmatic lookupProgrammatic lookup
@@InjectInject @@AnyAny
privateprivate Instance<CreditCardProcessor> ccProc;Instance<CreditCardProcessor> ccProc;
public voidpublic void processPayment(processPayment(
Payment payment,Payment payment, booleanboolean synchronously) {synchronously) {
Annotation qualifier = synchronouslyAnnotation qualifier = synchronously
?? newnew SynchronousLiteral()SynchronousLiteral()
:: newnew AsynchronousLiteral();AsynchronousLiteral();
CreditCardProcessor actualProcessor =CreditCardProcessor actualProcessor =
ccProc.select(qualifier).get();ccProc.select(qualifier).get();
actualProcessor.process(payment);actualProcessor.process(payment);
}}
classclass SynchronousLiteralSynchronousLiteral extendsextends
AnnotationLiteral<Synchronous> {}AnnotationLiteral<Synchronous> {}
• When qualifiers are to be examined atWhen qualifiers are to be examined at
runtime:runtime:
EventsEvents
@@InjectInject @@EventQualifierEventQualifier
privateprivate Event<SampleEvent> event;Event<SampleEvent> event;
publicpublic voidvoid fireEvent() {fireEvent() {
event.fire(new SimpleEvent());event.fire(new SimpleEvent());
}}
• Event observer (with the appropriate qualifier)Event observer (with the appropriate qualifier)
publicpublic voidvoid observes(observes(
@@ObservesObserves @@EventQualifierEventQualifier
SampleEvent event) { .. }SampleEvent event) { .. }
}}
• Event producer, making use of generics:Event producer, making use of generics:
Events (2)Events (2)
@@InjectInject @@Any Event<LoggedEvent> loggedEvent;Any Event<LoggedEvent> loggedEvent;
publicpublic voidvoid login(user) {login(user) {
LoggedEvent event =LoggedEvent event = newnew LoggedEvent(user);LoggedEvent(user);
ifif (user.isAdmin()) {(user.isAdmin()) {
loggedEvent.select(loggedEvent.select(
newnew AdminLiteral()).fire(event);AdminLiteral()).fire(event);
}} elseelse {{
loggedEvent.fire(event);loggedEvent.fire(event);
}}
}}
• Dynamic choice of qualifiersDynamic choice of qualifiers
• @Observes(notifyObserver=IF_EXISTS)@Observes(notifyObserver=IF_EXISTS)
notifies only if an instance of the declaringnotifies only if an instance of the declaring
beanbean
Circular dependenciesCircular dependencies
@@ApplicationScopedApplicationScoped
publicpublic classclass Bean1 {Bean1 {
@@InjectInject
publicpublic Bean1(Bean2 bean2) {..}Bean1(Bean2 bean2) {..}
}}
@@ApplicationScopedApplicationScoped
publicpublic classclass Bean2 {Bean2 {
@@InjectInject
publicpublic Bean2(Bean1 bean1) {..}Bean2(Bean1 bean1) {..}
}}
• CDI implementations must use proxies for allCDI implementations must use proxies for all
scopes, exceptscopes, except @Dependent@Dependent
DemoDemo
(Programatic lookup, Events, Circular Dependencies)
Portable extensionsPortable extensions
• CDI allows plugable extensions that can
access the context, hook to context events
• Providing its own beans, interceptors and
decorators to the container
• Injecting dependencies into its own objects
using the dependency injection service
• Providing a context implementation for a
custom scope
• Augmenting or overriding the annotation-
based metadata with metadata from some
other source
Portable extensions (2)Portable extensions (2)
• http://seamframework.org/Weld/PortableExte
nsionsPackage
• XML configuration
• Wicket integration
• JavaSE and Servlet container support
ConcernsConcerns
• Lack of standardized XML configuration
• Not many „extras“ available yet
• Annotation mess
• CDI interceptors might not be sufficient,
compared to Spring AOP (AspectJ syntax)
• (un)portable extensions may become exactly
what spring is being critized for – size and
complexity
• Complex
• Being a standard?
• http://seamframework.org/service/File/105766
• http://www.slideshare.net/johaneltes/java-ee6-c
• http://www.slideshare.net/mojavelinux/jsr299-cd
• http://download.oracle.com/javaee/6/tutorial/doc
ResourcesResources
QuestionsQuestions??

More Related Content

What's hot

Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsSyed Shahul
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)Fahad Golra
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in javaAcp Jamod
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEmprovise
 
Java interview questions
Java interview questionsJava interview questions
Java interview questionsSoba Arjun
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3phanleson
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersWhizlabs
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance FeaturesEmprovise
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-finalRohit Kelapure
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questionsRohit Singh
 

What's hot (19)

Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
EJB .
EJB .EJB .
EJB .
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Java EE EJB Applications
Java EE EJB ApplicationsJava EE EJB Applications
Java EE EJB Applications
 
Ecom lec3 16_ej_bs
Ecom lec3 16_ej_bsEcom lec3 16_ej_bs
Ecom lec3 16_ej_bs
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business Logic
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed Answers
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
EJB 3.0 and J2EE
EJB 3.0 and J2EEEJB 3.0 and J2EE
EJB 3.0 and J2EE
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance Features
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
JDT Fundamentals 2010
JDT Fundamentals 2010JDT Fundamentals 2010
JDT Fundamentals 2010
 

Viewers also liked

[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6Jose Naves Moura Neto
 
Cloud ios alternativas
Cloud ios alternativasCloud ios alternativas
Cloud ios alternativascodemotion_es
 
The Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the CloudThe Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the Cloudcodemotion_es
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIMichel Graciano
 
Practical introduction to dependency injection
Practical introduction to dependency injectionPractical introduction to dependency injection
Practical introduction to dependency injectionTamas Rev
 

Viewers also liked (6)

[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6
 
Cloud ios alternativas
Cloud ios alternativasCloud ios alternativas
Cloud ios alternativas
 
The Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the CloudThe Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the Cloud
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDI
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Practical introduction to dependency injection
Practical introduction to dependency injectionPractical introduction to dependency injection
Practical introduction to dependency injection
 

Similar to Contexts and Dependency Injection for the JavaEE platform

CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287Ahmad Gohar
 
Spring framework
Spring frameworkSpring framework
Spring frameworkAjit Koti
 
The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...Paul Bakker
 
Spring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsSpring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsVMware Tanzu
 
Spring introduction
Spring introductionSpring introduction
Spring introductionLê Hảo
 
Spring essentials 2 Spring Series 02)
Spring essentials 2 Spring Series 02)Spring essentials 2 Spring Series 02)
Spring essentials 2 Spring Series 02)Heartin Jacob
 
Spring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreDonald Lika
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologySimon Ritter
 
Java EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseConJava EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseConLudovic Champenois
 
Spring 3 - An Introduction
Spring 3 - An IntroductionSpring 3 - An Introduction
Spring 3 - An IntroductionThorsten Kamann
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
A Notes Developer's Journey into Java
A Notes Developer's Journey into JavaA Notes Developer's Journey into Java
A Notes Developer's Journey into JavaTeamstudio
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSShekhar Gulati
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design PatternsAlex Theedom
 
Apache maven and its impact on java 9 (Java One 2017)
Apache maven and its impact on java 9 (Java One 2017)Apache maven and its impact on java 9 (Java One 2017)
Apache maven and its impact on java 9 (Java One 2017)Robert Scholte
 
XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)Per Henrik Lausten
 

Similar to Contexts and Dependency Injection for the JavaEE platform (20)

CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...
 
Spring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsSpring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden Gems
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring essentials 2 Spring Series 02)
Spring essentials 2 Spring Series 02)Spring essentials 2 Spring Series 02)
Spring essentials 2 Spring Series 02)
 
Spring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-Core
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
 
Java EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseConJava EE 6, Eclipse @ EclipseCon
Java EE 6, Eclipse @ EclipseCon
 
Spring 3 - An Introduction
Spring 3 - An IntroductionSpring 3 - An Introduction
Spring 3 - An Introduction
 
Apache Maven
Apache MavenApache Maven
Apache Maven
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
A Notes Developer's Journey into Java
A Notes Developer's Journey into JavaA Notes Developer's Journey into Java
A Notes Developer's Journey into Java
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011
 
Apache maven and its impact on java 9 (Java One 2017)
Apache maven and its impact on java 9 (Java One 2017)Apache maven and its impact on java 9 (Java One 2017)
Apache maven and its impact on java 9 (Java One 2017)
 
XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)XPages and Java (DanNotes 50th conference, November 2013)
XPages and Java (DanNotes 50th conference, November 2013)
 

More from Bozhidar Bozhanov

Антикорупционен софтуер
Антикорупционен софтуерАнтикорупционен софтуер
Антикорупционен софтуерBozhidar Bozhanov
 
Elasticsearch - Scalability and Multitenancy
Elasticsearch - Scalability and MultitenancyElasticsearch - Scalability and Multitenancy
Elasticsearch - Scalability and MultitenancyBozhidar Bozhanov
 
Encryption in the enterprise
Encryption in the enterpriseEncryption in the enterprise
Encryption in the enterpriseBozhidar Bozhanov
 
Blockchain overview - types, use-cases, security and usabilty
Blockchain overview - types, use-cases, security and usabiltyBlockchain overview - types, use-cases, security and usabilty
Blockchain overview - types, use-cases, security and usabiltyBozhidar Bozhanov
 
Електронна държава
Електронна държаваЕлектронна държава
Електронна държаваBozhidar Bozhanov
 
Blockchain - what is it good for?
Blockchain - what is it good for?Blockchain - what is it good for?
Blockchain - what is it good for?Bozhidar Bozhanov
 
Algorithmic and technological transparency
Algorithmic and technological transparencyAlgorithmic and technological transparency
Algorithmic and technological transparencyBozhidar Bozhanov
 
Alternatives for copyright protection online
Alternatives for copyright protection onlineAlternatives for copyright protection online
Alternatives for copyright protection onlineBozhidar Bozhanov
 
Политики, основани на данни
Политики, основани на данниПолитики, основани на данни
Политики, основани на данниBozhidar Bozhanov
 
Отворено законодателство
Отворено законодателствоОтворено законодателство
Отворено законодателствоBozhidar Bozhanov
 
Electronic governance steps in the right direction?
Electronic governance   steps in the right direction?Electronic governance   steps in the right direction?
Electronic governance steps in the right direction?Bozhidar Bozhanov
 
Сигурност на електронното управление
Сигурност на електронното управлениеСигурност на електронното управление
Сигурност на електронното управлениеBozhidar Bozhanov
 
Биометрична идентификация
Биометрична идентификацияБиометрична идентификация
Биометрична идентификацияBozhidar Bozhanov
 
Регулации и технологии
Регулации и технологииРегулации и технологии
Регулации и технологииBozhidar Bozhanov
 

More from Bozhidar Bozhanov (20)

Антикорупционен софтуер
Антикорупционен софтуерАнтикорупционен софтуер
Антикорупционен софтуер
 
Nothing is secure.pdf
Nothing is secure.pdfNothing is secure.pdf
Nothing is secure.pdf
 
Elasticsearch - Scalability and Multitenancy
Elasticsearch - Scalability and MultitenancyElasticsearch - Scalability and Multitenancy
Elasticsearch - Scalability and Multitenancy
 
Encryption in the enterprise
Encryption in the enterpriseEncryption in the enterprise
Encryption in the enterprise
 
Blockchain overview - types, use-cases, security and usabilty
Blockchain overview - types, use-cases, security and usabiltyBlockchain overview - types, use-cases, security and usabilty
Blockchain overview - types, use-cases, security and usabilty
 
Електронна държава
Електронна държаваЕлектронна държава
Електронна държава
 
Blockchain - what is it good for?
Blockchain - what is it good for?Blockchain - what is it good for?
Blockchain - what is it good for?
 
Algorithmic and technological transparency
Algorithmic and technological transparencyAlgorithmic and technological transparency
Algorithmic and technological transparency
 
Scaling horizontally on AWS
Scaling horizontally on AWSScaling horizontally on AWS
Scaling horizontally on AWS
 
Alternatives for copyright protection online
Alternatives for copyright protection onlineAlternatives for copyright protection online
Alternatives for copyright protection online
 
GDPR for developers
GDPR for developersGDPR for developers
GDPR for developers
 
Политики, основани на данни
Политики, основани на данниПолитики, основани на данни
Политики, основани на данни
 
Отворено законодателство
Отворено законодателствоОтворено законодателство
Отворено законодателство
 
Overview of Message Queues
Overview of Message QueuesOverview of Message Queues
Overview of Message Queues
 
Electronic governance steps in the right direction?
Electronic governance   steps in the right direction?Electronic governance   steps in the right direction?
Electronic governance steps in the right direction?
 
Сигурност на електронното управление
Сигурност на електронното управлениеСигурност на електронното управление
Сигурност на електронното управление
 
Opensource government
Opensource governmentOpensource government
Opensource government
 
Биометрична идентификация
Биометрична идентификацияБиометрична идентификация
Биометрична идентификация
 
Biometric identification
Biometric identificationBiometric identification
Biometric identification
 
Регулации и технологии
Регулации и технологииРегулации и технологии
Регулации и технологии
 

Recently uploaded

Basic Accountants in|TaxlinkConcept.pdf
Basic  Accountants in|TaxlinkConcept.pdfBasic  Accountants in|TaxlinkConcept.pdf
Basic Accountants in|TaxlinkConcept.pdftaxlinkcpa
 
如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书
如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书
如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书Fir La
 
如何办理伦敦大学毕业证(文凭)London学位证书
如何办理伦敦大学毕业证(文凭)London学位证书如何办理伦敦大学毕业证(文凭)London学位证书
如何办理伦敦大学毕业证(文凭)London学位证书Fis s
 
VIP Kolkata Call Girls Bidhannagar 8250192130 Available With Room
VIP Kolkata Call Girls Bidhannagar 8250192130 Available With RoomVIP Kolkata Call Girls Bidhannagar 8250192130 Available With Room
VIP Kolkata Call Girls Bidhannagar 8250192130 Available With Roomrran7532
 
Short-, Mid-, and Long-term gxxoals.pptx
Short-, Mid-, and Long-term gxxoals.pptxShort-, Mid-, and Long-term gxxoals.pptx
Short-, Mid-, and Long-term gxxoals.pptxHenryBriggs2
 
VIP Kolkata Call Girl Rishra 👉 8250192130 Available With Room
VIP Kolkata Call Girl Rishra 👉 8250192130  Available With RoomVIP Kolkata Call Girl Rishra 👉 8250192130  Available With Room
VIP Kolkata Call Girl Rishra 👉 8250192130 Available With Roomdivyansh0kumar0
 
如何办理东俄勒冈大学毕业证(文凭)EOU学位证书
如何办理东俄勒冈大学毕业证(文凭)EOU学位证书如何办理东俄勒冈大学毕业证(文凭)EOU学位证书
如何办理东俄勒冈大学毕业证(文凭)EOU学位证书Fir La
 
如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书
如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书
如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书Fir La
 
Cyberagent_For New Investors_EN_240424.pdf
Cyberagent_For New Investors_EN_240424.pdfCyberagent_For New Investors_EN_240424.pdf
Cyberagent_For New Investors_EN_240424.pdfCyberAgent, Inc.
 
The Concept of Humanity in Islam and its effects at future of humanity
The Concept of Humanity in Islam and its effects at future of humanityThe Concept of Humanity in Islam and its effects at future of humanity
The Concept of Humanity in Islam and its effects at future of humanityJohanAspro
 
如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书
如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书
如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书Fis s
 
WheelTug PLC Pitch Deck | Investor Insights | April 2024
WheelTug PLC Pitch Deck | Investor Insights | April 2024WheelTug PLC Pitch Deck | Investor Insights | April 2024
WheelTug PLC Pitch Deck | Investor Insights | April 2024Hector Del Castillo, CPM, CPMM
 
9654467111 Call Girls In Katwaria Sarai Short 1500 Night 6000
9654467111 Call Girls In Katwaria Sarai Short 1500 Night 60009654467111 Call Girls In Katwaria Sarai Short 1500 Night 6000
9654467111 Call Girls In Katwaria Sarai Short 1500 Night 6000Sapana Sha
 
OKC Thunder Reveal Game 2 Playoff T Shirts
OKC Thunder Reveal Game 2 Playoff T ShirtsOKC Thunder Reveal Game 2 Playoff T Shirts
OKC Thunder Reveal Game 2 Playoff T Shirtsrahman018755
 
9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR
9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR
9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCRSapana Sha
 
No 1 AMil Baba In Islamabad No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...
No 1 AMil Baba In Islamabad  No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...No 1 AMil Baba In Islamabad  No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...
No 1 AMil Baba In Islamabad No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...First NO1 World Amil baba in Faisalabad
 

Recently uploaded (20)

Basic Accountants in|TaxlinkConcept.pdf
Basic  Accountants in|TaxlinkConcept.pdfBasic  Accountants in|TaxlinkConcept.pdf
Basic Accountants in|TaxlinkConcept.pdf
 
如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书
如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书
如何办理密苏里大学堪萨斯分校毕业证(文凭)UMKC学位证书
 
如何办理伦敦大学毕业证(文凭)London学位证书
如何办理伦敦大学毕业证(文凭)London学位证书如何办理伦敦大学毕业证(文凭)London学位证书
如何办理伦敦大学毕业证(文凭)London学位证书
 
VIP Kolkata Call Girls Bidhannagar 8250192130 Available With Room
VIP Kolkata Call Girls Bidhannagar 8250192130 Available With RoomVIP Kolkata Call Girls Bidhannagar 8250192130 Available With Room
VIP Kolkata Call Girls Bidhannagar 8250192130 Available With Room
 
Short-, Mid-, and Long-term gxxoals.pptx
Short-, Mid-, and Long-term gxxoals.pptxShort-, Mid-, and Long-term gxxoals.pptx
Short-, Mid-, and Long-term gxxoals.pptx
 
VIP Kolkata Call Girl Rishra 👉 8250192130 Available With Room
VIP Kolkata Call Girl Rishra 👉 8250192130  Available With RoomVIP Kolkata Call Girl Rishra 👉 8250192130  Available With Room
VIP Kolkata Call Girl Rishra 👉 8250192130 Available With Room
 
Falcon Invoice Discounting - Best Platform
Falcon Invoice Discounting - Best PlatformFalcon Invoice Discounting - Best Platform
Falcon Invoice Discounting - Best Platform
 
如何办理东俄勒冈大学毕业证(文凭)EOU学位证书
如何办理东俄勒冈大学毕业证(文凭)EOU学位证书如何办理东俄勒冈大学毕业证(文凭)EOU学位证书
如何办理东俄勒冈大学毕业证(文凭)EOU学位证书
 
如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书
如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书
如何办理北卡罗来纳大学教堂山分校毕业证(文凭)UNC学位证书
 
Cyberagent_For New Investors_EN_240424.pdf
Cyberagent_For New Investors_EN_240424.pdfCyberagent_For New Investors_EN_240424.pdf
Cyberagent_For New Investors_EN_240424.pdf
 
The Concept of Humanity in Islam and its effects at future of humanity
The Concept of Humanity in Islam and its effects at future of humanityThe Concept of Humanity in Islam and its effects at future of humanity
The Concept of Humanity in Islam and its effects at future of humanity
 
如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书
如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书
如何办理(UTS毕业证书)悉尼科技大学毕业证学位证书
 
WheelTug PLC Pitch Deck | Investor Insights | April 2024
WheelTug PLC Pitch Deck | Investor Insights | April 2024WheelTug PLC Pitch Deck | Investor Insights | April 2024
WheelTug PLC Pitch Deck | Investor Insights | April 2024
 
Model Call Girl in Udyog Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Udyog Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Udyog Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Udyog Vihar Delhi reach out to us at 🔝9953056974🔝
 
9654467111 Call Girls In Katwaria Sarai Short 1500 Night 6000
9654467111 Call Girls In Katwaria Sarai Short 1500 Night 60009654467111 Call Girls In Katwaria Sarai Short 1500 Night 6000
9654467111 Call Girls In Katwaria Sarai Short 1500 Night 6000
 
Model Call Girl in Uttam Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Uttam Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Uttam Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Uttam Nagar Delhi reach out to us at 🔝9953056974🔝
 
OKC Thunder Reveal Game 2 Playoff T Shirts
OKC Thunder Reveal Game 2 Playoff T ShirtsOKC Thunder Reveal Game 2 Playoff T Shirts
OKC Thunder Reveal Game 2 Playoff T Shirts
 
9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR
9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR
9654467111 Low Rate Call Girls In Tughlakabad, Delhi NCR
 
No 1 AMil Baba In Islamabad No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...
No 1 AMil Baba In Islamabad  No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...No 1 AMil Baba In Islamabad  No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...
No 1 AMil Baba In Islamabad No 1 Amil Baba In Lahore No 1 Amil Baba In Faisl...
 
Call Girls in South Ex⎝⎝9953056974⎝⎝ Escort Delhi NCR
Call Girls in South Ex⎝⎝9953056974⎝⎝ Escort Delhi NCRCall Girls in South Ex⎝⎝9953056974⎝⎝ Escort Delhi NCR
Call Girls in South Ex⎝⎝9953056974⎝⎝ Escort Delhi NCR
 

Contexts and Dependency Injection for the JavaEE platform

  • 1. CDI – Contexts andCDI – Contexts and Dependency Injection for theDependency Injection for the JavaEE platform (JSR299)JavaEE platform (JSR299) Bozhidar Bozhanov Bulgarian Association of Software Developers www.devbg.org
  • 2. About meAbout me • Senior Java Developer at Fish4 • 3+ years experience with Spring and dependency injection • Implementor of JSR-299 as a university project • Committer at Hector (Java Cassandra API) • http://techblog.bozho.net
  • 3. Dependency injection?Dependency injection? • Classes define what are their dependencies, not how they obtain them • Object dependencies are set externally • Unit-test and mocking friendly • DI frameworks - objects are managed and have a lifecycle
  • 4. HistoryHistory • Theoretical basis - GoF Hollywood principle; Steffano Mazzocchi • Spring – 2002/2003, Rod Johnson • Pico Container - 2003 • Martin Fowler popularized the term - 2004 • JBoss Seam, Google Guice, EJB 3.0 • Contexts and Dependency Injection (JSR- 299, JavaEE 6) - 2006-2009
  • 5. Current problemsCurrent problems • Problematic integration between JavaEE components • „Crippled“ dependency-injection in EJB • No standard – only propriatary DI frameworks (spring, guice, seam) • Extended reliance on string qualifiers (no compile-time safety)
  • 6. JSR-299JSR-299 • What's a JSR? • CDI Initially named „Web Beans“ • Expert Group formed in June 2006, spec-lead is Gavin King • Early draft (2007), Public review (2008), Final draft (mid-2009), Ralease (Dec 2009) • Bob Lee (Guice) left the expert group • IBM voted „No“, Google voted „Yes“, VMware (SpringSource) and Eclipse didn't vote.
  • 7. What is CDIWhat is CDI • Type-safe DI framework (based on Seam, Guice and Spring) • Uses JSR-330 (Dependency Injection for Java), lead by Rod Johnson (Spring) and Bob Lee (Guice), which defines only DI annotations (for JavaSE) • DI JavaEE-wide – JSF managed beans, EJB, JavaEE Resources
  • 8. Implementations; web profileImplementations; web profile • Three implementations: JBoss Weld, Apache OpenWebBeans and Resin CanDI • Only one stable at the moment – Weld, used in Glassfish v3 and JBoss AS (5.2, 6) • JavaEE 6 has the so-called „profiles“. CDI is part of the „Web profile“ • CDI implementations are not limited to application servers (with the help of extensions)
  • 9. Java EE structure with CDIJava EE structure with CDI
  • 10. Beans and bean archivesBeans and bean archives • A bean archive has META-INF/beans.xml • All classes within a bean archive are beans, and eligible for injection • All classes in outside bean archives are not beans • Beans can have type(s), scope, EL name, qualifiers, interceptors. • Beans can be JSF beans, EJBs, JavaEE resources
  • 11. • @javax.inject.Inject is used:@javax.inject.Inject is used: InjectionInjection publicpublic classclass OrdersBean {OrdersBean { @Inject@Inject privateprivate OrdersDaoOrdersDao daodao;; }} • The „dao“ field is called „injection point“.The „dao“ field is called „injection point“. Injection point types are:Injection point types are: • FieldField • ConstructorConstructor • SetterSetter • InitializerInitializer
  • 12. Injection pointsInjection points publicpublic classclass OrdersBean {OrdersBean { @Inject@Inject privateprivate OrdersDaoOrdersDao daodao;; @Inject@Inject publicpublic OrdersBean(OrdersDao dao){}OrdersBean(OrdersDao dao){} @Inject@Inject publicpublic voidvoid init(OrdersDao dao) {}init(OrdersDao dao) {} @Inject@Inject publicpublic voidvoid setOrdersDao(OrdersDao dao){}setOrdersDao(OrdersDao dao){} }}
  • 13. • Inject into:Inject into: – POJOsPOJOs – EJB Session BeansEJB Session Beans – ServletsServlets • Injection candidates:Injection candidates: – POJOsPOJOs – EJB Session BeansEJB Session Beans – JavaEE ResourcesJavaEE Resources Injection targetsInjection targets
  • 14. Bean scopesBean scopes • Built-in scopes (normal vs pseudo): • @ApplicationScoped – i.e. Singleton • @RequestScoped – created on http request • @SessionScoped – within a HttpSession • @ConversationScoped – between request and session • @Dependent (default, pseudo) – the object lives as long as the object it is injected into • Custom scopes
  • 15. • @Named(@Named(""beanNamebeanName"")). Defaults to the. Defaults to the decapitalized, simple name of the classdecapitalized, simple name of the class • Used in EL expressions:Used in EL expressions: Bean nameBean name <<h:outputTexth:outputText valuevalue=="#{orderBean.order.price}""#{orderBean.order.price}" />/> • Used in injections (discouraged)Used in injections (discouraged) @Inject@Inject @Named@Named(("ordersBean""ordersBean")) privateprivate OrdersBeanOrdersBean orderBeanorderBean;;
  • 16. • Qualifiers are annotations (unlike in spring):Qualifiers are annotations (unlike in spring): QualifiersQualifiers @Qualifier //retention & target ommitted@Qualifier //retention & target ommitted publicpublic @interface@interface SynchronousSynchronous {}{} • Qualifiers are used to differentiate beans with the sameQualifiers are used to differentiate beans with the same type:type: @@InjectInject @@SynchronousSynchronous privateprivate CreditCardProcessor processor;CreditCardProcessor processor; @@SynchronousSynchronous publicpublic classclass SynchronousCreditCardProcessorSynchronousCreditCardProcessor implementsimplements CreditCardProcessor {..}CreditCardProcessor {..} @@AsynchronousAsynchronous publicpublic classclass AsyncCreditCardProcessorAsyncCreditCardProcessor implementsimplements CreditCardPRocessor {..}CreditCardPRocessor {..}
  • 17. • @Any@Any – all beans have this, unless they have– all beans have this, unless they have @New@New • @Default, @Named@Default, @Named • @New@New –– forces the container to return a new beanforces the container to return a new bean instance each timeinstance each time Built-in qualifiersBuilt-in qualifiers @@NewNew publicpublic classclass SomeBean {..}SomeBean {..} publicpublic classclass AnotherBean {AnotherBean { @@Inject SomeBean bean1;Inject SomeBean bean1; @@Inject SomeBean bean2;Inject SomeBean bean2; @@PostConstructPostConstruct voidvoid init() {init() { // false// false System.out.println(bean1 == bean2);System.out.println(bean1 == bean2); }} }}
  • 18. • Stereotypes are used to reduce the amountStereotypes are used to reduce the amount of boilerplate code:of boilerplate code: StereotypesStereotypes @@StereotypeStereotype //denoting a stereotype//denoting a stereotype @@NamedNamed // built-in qualifier// built-in qualifier @@RequestScopedRequestScoped // scope// scope publicpublic @interface@interface RequestScopedSecureBean {}RequestScopedSecureBean {} @@RequestScopedNamedRequestScopedNamed BeanBean publicpublic classclass OrdersBean {..}OrdersBean {..}
  • 20. • A way to utilize complex constructionA way to utilize complex construction • Allow non-beans to be injected (i.e. 3Allow non-beans to be injected (i.e. 3rdrd partyparty classes outside a bean-archive)classes outside a bean-archive) • Handles object disposalHandles object disposal ProducersProducers //this class is within a bean archive//this class is within a bean archive classclass ConnectionProducer {ConnectionProducer { @Produces@Produces Connection createConnection() {Connection createConnection() { // create and return jdbc connection// create and return jdbc connection }} // when the object gets out of scope// when the object gets out of scope voidvoid dispose(dispose(@Disposes@Disposes Connection con) {Connection con) { con.close();con.close(); }} }}
  • 21. • Allow injecting JavaEE resources:Allow injecting JavaEE resources: Producer fieldsProducer fields @@ProducesProduces @@SomeTopicSomeTopic @@Resource(name=Resource(name="topics/SomeTopic""topics/SomeTopic")) privateprivate Topic someTopic;Topic someTopic; @@ProducesProduces @@PersistenceContextPersistenceContext privateprivate EntityManager entityManager;EntityManager entityManager; @@ProducesProduces // non-JaveEE producer field// non-JaveEE producer field privateprivate Some3rdPartyBean bean =Some3rdPartyBean bean = newnew Some3rdPartyBean();Some3rdPartyBean();
  • 22. • Gives information about the injection pointGives information about the injection point Injection point metadataInjection point metadata @@Produces Logger createLogger(InjectionPointProduces Logger createLogger(InjectionPoint injectionPoint) {injectionPoint) { returnreturn Logger.getLogger(injectionPointLogger.getLogger(injectionPoint .getMember().getDeclaringClass());.getMember().getDeclaringClass()); }} @Produces@Produces @@HttpParam(HttpParam("""")) String getParamValue(ServletRequest request,String getParamValue(ServletRequest request, InjectionPoint ip) {InjectionPoint ip) { returnreturn request.getParameter(iprequest.getParameter(ip .getAnnotation(HttpParam..getAnnotation(HttpParam.class)class).value());.value()); }} }}
  • 23. • Decorators decorate all interfaces theyDecorators decorate all interfaces they implementimplement • @Delegate@Delegate is used to inject the originalis used to inject the original objectobject • Decorators must be explicitly listed inDecorators must be explicitly listed in beans.xml, in their respective orderbeans.xml, in their respective order • Decorators can be abstractDecorators can be abstract DecoratorsDecorators @@DecoratorDecorator publicpublic classclass LogDecoratorLogDecorator implementsimplements Logger {Logger { @@DelegateDelegate @@AnyAny privateprivate LoggerLogger loggerlogger;; @Override@Override publicpublic voidvoid log(String msg) {log(String msg) { loggerlogger.log(timestamp() +.log(timestamp() + ":"":" + msg);+ msg); }} }}
  • 24. • Interceptor bindings (can be nested or includedInterceptor bindings (can be nested or included in stereotypes)in stereotypes) InterceptorsInterceptors @@InterceptorBindingInterceptorBinding // + retention & target// + retention & target publicpublic @interface@interface TransactionalTransactional{}{} @@InterceptorBindings @TransactionalInterceptorBindings @Transactional publicpublic @interface@interface DataAccessDataAccess {}{} • Declaring the actual interceptor:Declaring the actual interceptor: @@TransactionalTransactional @@InterceptorInterceptor publicpublic classclass TransactionInterceptor {TransactionInterceptor { @@AroundInvokeAroundInvoke publicpublic Object manage(InvocationContext ctx)Object manage(InvocationContext ctx) throwsthrows Exception { .. }Exception { .. } }}
  • 25. • Declaring the interceptor on the target beanDeclaring the interceptor on the target bean Interceptors (2)Interceptors (2) @@TransactionalTransactional //all methods are transactional//all methods are transactional public classpublic class OrderService { .. }OrderService { .. } • Like decorators, must be enabled in beans.xmlLike decorators, must be enabled in beans.xml • Interceptors-to-intercepted targets: many-to-Interceptors-to-intercepted targets: many-to- manymany • Interceptors-to-interceptor bindings: many-to-Interceptors-to-interceptor bindings: many-to- manymany • Binding vsBinding vs @NonBinding@NonBinding interceptor attributesinterceptor attributes
  • 27. Programmatic lookupProgrammatic lookup @@InjectInject @@AnyAny privateprivate Instance<CreditCardProcessor> ccProc;Instance<CreditCardProcessor> ccProc; public voidpublic void processPayment(processPayment( Payment payment,Payment payment, booleanboolean synchronously) {synchronously) { Annotation qualifier = synchronouslyAnnotation qualifier = synchronously ?? newnew SynchronousLiteral()SynchronousLiteral() :: newnew AsynchronousLiteral();AsynchronousLiteral(); CreditCardProcessor actualProcessor =CreditCardProcessor actualProcessor = ccProc.select(qualifier).get();ccProc.select(qualifier).get(); actualProcessor.process(payment);actualProcessor.process(payment); }} classclass SynchronousLiteralSynchronousLiteral extendsextends AnnotationLiteral<Synchronous> {}AnnotationLiteral<Synchronous> {} • When qualifiers are to be examined atWhen qualifiers are to be examined at runtime:runtime:
  • 28. EventsEvents @@InjectInject @@EventQualifierEventQualifier privateprivate Event<SampleEvent> event;Event<SampleEvent> event; publicpublic voidvoid fireEvent() {fireEvent() { event.fire(new SimpleEvent());event.fire(new SimpleEvent()); }} • Event observer (with the appropriate qualifier)Event observer (with the appropriate qualifier) publicpublic voidvoid observes(observes( @@ObservesObserves @@EventQualifierEventQualifier SampleEvent event) { .. }SampleEvent event) { .. } }} • Event producer, making use of generics:Event producer, making use of generics:
  • 29. Events (2)Events (2) @@InjectInject @@Any Event<LoggedEvent> loggedEvent;Any Event<LoggedEvent> loggedEvent; publicpublic voidvoid login(user) {login(user) { LoggedEvent event =LoggedEvent event = newnew LoggedEvent(user);LoggedEvent(user); ifif (user.isAdmin()) {(user.isAdmin()) { loggedEvent.select(loggedEvent.select( newnew AdminLiteral()).fire(event);AdminLiteral()).fire(event); }} elseelse {{ loggedEvent.fire(event);loggedEvent.fire(event); }} }} • Dynamic choice of qualifiersDynamic choice of qualifiers • @Observes(notifyObserver=IF_EXISTS)@Observes(notifyObserver=IF_EXISTS) notifies only if an instance of the declaringnotifies only if an instance of the declaring beanbean
  • 30. Circular dependenciesCircular dependencies @@ApplicationScopedApplicationScoped publicpublic classclass Bean1 {Bean1 { @@InjectInject publicpublic Bean1(Bean2 bean2) {..}Bean1(Bean2 bean2) {..} }} @@ApplicationScopedApplicationScoped publicpublic classclass Bean2 {Bean2 { @@InjectInject publicpublic Bean2(Bean1 bean1) {..}Bean2(Bean1 bean1) {..} }} • CDI implementations must use proxies for allCDI implementations must use proxies for all scopes, exceptscopes, except @Dependent@Dependent
  • 31. DemoDemo (Programatic lookup, Events, Circular Dependencies)
  • 32. Portable extensionsPortable extensions • CDI allows plugable extensions that can access the context, hook to context events • Providing its own beans, interceptors and decorators to the container • Injecting dependencies into its own objects using the dependency injection service • Providing a context implementation for a custom scope • Augmenting or overriding the annotation- based metadata with metadata from some other source
  • 33. Portable extensions (2)Portable extensions (2) • http://seamframework.org/Weld/PortableExte nsionsPackage • XML configuration • Wicket integration • JavaSE and Servlet container support
  • 34. ConcernsConcerns • Lack of standardized XML configuration • Not many „extras“ available yet • Annotation mess • CDI interceptors might not be sufficient, compared to Spring AOP (AspectJ syntax) • (un)portable extensions may become exactly what spring is being critized for – size and complexity • Complex • Being a standard?
  • 35. • http://seamframework.org/service/File/105766 • http://www.slideshare.net/johaneltes/java-ee6-c • http://www.slideshare.net/mojavelinux/jsr299-cd • http://download.oracle.com/javaee/6/tutorial/doc ResourcesResources