51
Introduction Starting with CDI More advanced features Summary Context and Dependency Injection for Java EE Marcin Kwiatkowski Department of Computer Science Wroclaw University of Technology May 2010 Marcin Kwiatkowski CDI for Java EE

Context and Dependency Injection for Java EEsens.e-informatyka.pl/wp-content/uploads/WIRP2/cdi.pdf · Introduction Starting with CDI More advanced features Summary Context and Dependency

Embed Size (px)

Citation preview

IntroductionStarting with CDI

More advanced featuresSummary

Context and Dependency Injection for Java EE

Marcin Kwiatkowski

Department of Computer ScienceWroclaw University of Technology

May 2010

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

Outline1 Introduction

TerminologyInitial goalServices provided by CDI

2 Starting with CDICDI beansInjecting beansEL IntegrationScope types and contexts

3 More advanced featuresProducersInterceptors and DecoratorsEventsStereotypes

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

TerminologyInitial goalServices provided by CDI

Outline1 Introduction

TerminologyInitial goalServices provided by CDI

2 Starting with CDICDI beansInjecting beansEL IntegrationScope types and contexts

3 More advanced featuresProducersInterceptors and DecoratorsEventsStereotypes

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

TerminologyInitial goalServices provided by CDI

Terminology.

Web BeansOriginal name of the specification

JSR-299Context and Dependency Injection for Java EE (CDI)

WeldJSR-299 Reference Implementation

SeamPortable Extensions to CDI

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

TerminologyInitial goalServices provided by CDI

Original goal of JSR-299.

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

TerminologyInitial goalServices provided by CDI

What does CDI provide?

ServicesAn improved lifecycle for stateful objects, bound towell-definied contextsA type safe approach to dependency injectionObject interaction via an event notification facilityBetter approach to binding interceptors to objectsEL Integration

SPI for developing portable extensions to the container

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

TerminologyInitial goalServices provided by CDI

To summarize

CDI relieves the user of an unfamiliar API of the need to answerthe following questions:

What is the lifecycle of this object?How many simultaneous clients can it have?How do I get access to it from a client?Do I need to explicitly destroy it?Where should i keep the reference to it?How can I define an alternative implementation?

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Outline1 Introduction

TerminologyInitial goalServices provided by CDI

2 Starting with CDICDI beansInjecting beansEL IntegrationScope types and contexts

3 More advanced featuresProducersInterceptors and DecoratorsEventsStereotypes

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

What are valid bean types?

Almost any plain Java class (POJO)EJB session beansObject returned by producer method or fieldsJNDI resources (e. g. DataSource, JMS)Persistence unitsAdditional Types definied by SPI

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Example of CDI Managed bean

public class Hel lo {public S t r i n g getMessage ( ) {

return " He l lo " ;}

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Example of CDI EJB bean

@Statelesspublic class Hel lo {

public S t r i n g getMessage ( ) {return " He l lo " ;

}}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How is a bean recognized?

META-INF/beans.xml marker fileIt can be empty!

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Injection

public class Greater {

@Inject He l lo h e l l o ;

public void printMessage ( ) {System . out . p r i n t l n ( h e l l o . getMessage ( ) ) ;

}}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

What does strong typing mean in CDI world?

Type-based injectionEliminate reliance on string-based names

Compiler can detect typing errorsNo special authoring tools requiredCasting mostly eliminated

Semantic code errors detected at application startupTooling can detect ambiguous dependencies

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Where can beans be injected?

FieldsMethods

ConstructorInitializerProducerObserver

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How about ambiguous dependencies?

public class SynchronousPaymentProcessor implements PaymentProcessor {public void process ( Payment payment ) {}

}

public class AsynchronousPaymentProcessor implements PaymentProcessor {public void process ( Payment payment ) {}

}

public class Checkout {@Inject PaymentProcessor paymentProcessor ;

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

The Qualifier annotations

public class Checkout {@Inject @Synchronous PaymentProcessor

paymentProcessor ;}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How to define a qualifier

@Qual i f ie r@Retention (RUNTIME)@Target ( { TYPE,METHOD, FIELD ,PARAMETER} )public @inter face Synchronous { }

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How to use qualifier?

@Synchronouspublic class SynchronousPaymentProcessor implements

PaymentProcessor {public void process ( Paymentpayment ) {}

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Mock implementation

public class MockPaymentProcessor implementsPaymentProcessor {

public void process ( Payment payment ) {}

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Alternatives

Swap replacement per deploymentReplaces bean and its producer methods and fieldsDisabled by default

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How to define an alternative bean?

@Alternat ive@Synchronous@Asynchronouspublic class MockPaymentProcessor implements

PaymentProcessor {public voidprocess ( Paymentpayment ) {}

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Alternatives need to be activated

<beans>< a l t e r n a t i v e s >

<c lass>demo . MockPaymentProcessor< / c lass>< / a l t e r n a t i v e s >

< / beans>

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How to name a bean?

@Named( " shoppingCart " )@SessionScopedpublic class ShoppingCart implements S e r i a l i z a b l e {}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How to name a bean?

@Named@SessionScopedpublic class ShoppingCart implements S e r i a l i z a b l e {}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

How to use beans from JSF view?

<h: form><h:dataTable value=" #{ shoppingCart . i tems } " var= " i tem "

>

< / h:dataTable>< / h: form>

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

What is a scope?

According to the CDI specification, a scope determines:When a new instance of any bean with that scope iscreatedWhen an existing instance of any bean with that scope isdestroyedWhich injected references refer to any instance of a beanwith that scope

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Build-in scopes

@RequestScoped@SessionScoped@ApplicationScoped@ConversationScoped*@Dependent*

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

CDI beansInjecting beansEL IntegrationScope types and contexts

Scope transparency

Scopes are not visible to clientsNo coupling between scope and use of typeScoped beans are proxied for thread safety

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Outline1 Introduction

TerminologyInitial goalServices provided by CDI

2 Starting with CDICDI beansInjecting beansEL IntegrationScope types and contexts

3 More advanced featuresProducersInterceptors and DecoratorsEventsStereotypes

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

What are producer methods?

Method whose return value produces an injectable objectUse when:

The objects to be injected are not required to be instancesof beansThe concrete type of the objects to be injected may vary atruntimeThe objects require some custom initialization that cannotbe performed by the bean constructor

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Example of producer methods

@Produces@RequestScopedpublic FacesContext getFacesContext ( ) {

return FacesContext . ge t Ins tance ( ) ;}

@Producespublic PaymentProcessor getPaymentProcessor (

@SynchronousPaymentProcessorsync ,@AsynchronousPaymentProcessorasync {

return isSynchronous ( ) ? sync : anync ;}

@Produces@SessionScoped@WishListpublic L i s t <Product > getWishL is t ( ) {

return em. createQuery ( " . . . " ) . g e t R e s u l t L i s t ( ) ;}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Producer fields

@Statelesspublic class UserRepositoryProducer {

@Produces@UserRepository@PresistenceContext ( unitName=" userPU " )Ent i tyManager em;

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Interception points

Business method interceptionLife-cycle callback interceptionTimeout method interception*

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Examples of interceptors

public class Transac t i on In te r cep to r {@AroundInvokepublic Object manageTransaction ( Invoca t ionContex t c t x ) throws Except ion { }

}

public class Dependency In jec t ion In te rcep to r {@PostConstructpublic void in jectDependencies ( Invoca t ionContex t c t x ) { }

}

public c lassT imeou t In te rcep to r {@AroundTimeoutpublic Object manageTransaction ( Invoca t ionContex t c t x ) throws Except ion { }

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Interceptor bindings

@InterceptorB ind ing@Retention (RUNTIME)@Target ( { TYPE,METHOD} )public @inter face Secure {}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

How to implement interceptor?

@Secure@Interceptorpublic class S e c u r i t y I n t e r c e p t o r {

@AroundInvokepublic Object aroundInvoke ( Invoca t ionCon tex tc tx )

throws Except ion {/ / do s e c u r i t y s t u f freturn cx t . proceed ( ) ;

}}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

How to use Interceptor?

@Securepublic class AccountManager {

public boolean t r a n s f e r ( Account a , Account b ) { }}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

How to activate Interceptor?

<beans>< i n t e r c e p t o r s >

<c lass>demo . S e c u r i t y I n t e r c e p t o r < / c lass><c lass>demo . T ransac t i on In te r cep to r < / c lass>

< / i n t e r c e p t o r s >< / beans>

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

What are decorators?

Intercept invocation only for a certain Java interfacePerfect for modeling business concerns

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Example of Decorator

public inter face Account {public void withdraw ( BigDecimal amount ) ;public void depos i t ( BigDecimal amount ) ;public BigDecimal getBalance ( ) ;

}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Example of Decorator

@Decoratorpublic abstract class LargeTransact ionDecorator implements Account {

@Inject @Delegate @Any Account account ;@PersistenceContext Ent i tyManager em;

public void withdraw ( BigDecimal amount ) {account . withdraw ( amount ) ;i f ( amount . compareTo (LARGE_AMOUNT) >0) {

em. p e r s i s t (new LoggedWithdraw ( amount ) ) ;}

}

public void depos i t ( BigDecimal amount ) {account . depos i t ( amount ) ;i f ( amount . comareTo (LARGE_AMOUNT) >0) {

em. p e r s i s t (new LoggedDeposit ( amount ) ) ;}

}}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Activating Decorators

<beans><decorators>

<c lass>demo . LargeTransact ionDecorator< / c lass>< / decora tors>

< / beans>

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Events

Fully Decouple producers and observersObservers can specify which notifications they will receiveObservers can be notified immediately or at the end oftransaction*

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Event producer

public class GroundContro l le r {@Inject @Landing Event< F l i g h t >f l i g h t L a n d i n g ;

public void c learForLanding ( S t r i n g f l i g h t N o ) {f l i g h t L a n d i n g . f i r e (new F l i g h t ( f l i g h t N o ) ) ;

}}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Event observer

public class GateServices {public void onIncommingFl ight ( @Observes @Landing

F l i g h t f l i g h t , Cater ingServ ice ca te r i ngServ i ce ) {Gate gate = . . . ;f l i g h t . setGate ( getGate ( ) ) ;ca te r i ngServ i ce . d ispatch ( gate ) ;

}}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Annotation hell

@Secure@Transactional@RequestScoped@Namedpublic class AccountManager ( ) {}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

What are Stereotypes?

Identify recurring beans rolesEncapsulate combination of:

Default scopeSet of interceptor bindings

May also specify that:All beans with the stereotype are namedAll beans with the stereotype are alternatives

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Defining stereotype

@Secure@Transactional@RequestScoped@Named@Stereotype@Retention (RUNTIME)@Target (TYPE)public @inter face BusinessComponent {}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

ProducersInterceptors and DecoratorsEventsStereotypes

Using stereotype

@BusinessComponentpublic class AccountManager {}

Marcin Kwiatkowski CDI for Java EE

IntroductionStarting with CDI

More advanced featuresSummary

How to get started?

JSR-299 Specificationhttp://jcp.org/en/jsr/detail?id=299

Weld documentationhttp://seamframework.org/Weld/Documentation

Weld Maven archetypes

http://sfwk.org/Decumentation/WeldQuickstartForMavenUsers

Marcin Kwiatkowski CDI for Java EE