cdi and weld

31
Consulting ● Development ● IT Operations ● Training ● Support ● Products CDI . Dependency Injection in JEE6 [email protected]

Upload: jensaug

Post on 06-May-2015

2.721 views

Category:

Documents


1 download

DESCRIPTION

A 30 slide CDI (Context and Dependency Injection for the Java EE Platform) presentation Jens Augustsson from Redpill Linpro did in Copenhagen March 23 2011

TRANSCRIPT

Page 1: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

CDI .

Dependency Injection in JEE6

[email protected]

Page 2: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Today.

1. What it is2. Features3. Advices

Page 3: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

next. . .

1. What it is

Page 4: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Example.public class TextTranslator {

   private final SentenceParser sentenceParser;   private final Translator sentenceTranslator;

   @Inject   public TextTranslator(SentenceParser sentenceParser, 

Translator sentenceTranslator) {

      this.sentenceParser = sentenceParser;      this.sentenceTranslator = sentenceTranslator;   }

   public String translate(String text) {      StringBuilder sb = new StringBuilder();      for (String sentence: sentenceParser.parse(text)) {          sb.append(sentenceTranslator.translate(sentence));      }      return sb.toString();   }}

Page 5: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Example - 2.

public class SentenceParser {

   public List<String> parse(String text) { ... }

}

@Stateless

public class SentenceTranslator implements Translator {

   public String translate(String sentence) { ... }

}

Injection of: Managed Bean, EJB session beans

Injection to: MDB, interceptor, Servlet, JAX-WS SE, JSP (tag h / ev lis)

Page 6: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Martin Fowler.Coined the term ”Dependency Injection”

«The fundamental choice is between

Service Locator and Dependency Injection»

http://martinfowler.com/articles/injection.html

«Inversion of Control» ... «The Hollywood principle»

Page 7: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

CDI - JSR299.

”Context and Dependency Injection for the Java EE Platform”

«Loose coupling, strong typing»

Page 8: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

but. . .

Why care?

Page 9: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

JEE5 DI features.

Resource injection in JEE5✔ @EJB, @Resource, @PersistenceContext,

@PersistenceUnit

✔ Servlets, JSF backing beans and other EJBs

Problems✔ Cannot inject EJBs into Struts Actions

✔ Cannot inject DAOs or helper classes that were not written as EJBs

✔ Hard to integrate anything but strictly business components

Page 10: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Alternative DI frameworks.

Spring Core✔ The de facto standard

PicoContainer✔ Early one

HiveMind✔ Howard Lewis Ship & Tapestry

Seam 2✔ By the Hibernate Team

Guice✔ Crazy Bob Lee @ Google

Page 11: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

part of...

but I've heard the term. . . . .CDI

WebBeans

Weld

D4J

JSR-299

JSR-330

Seam 2

Seam 3

GuiceSpring Core

Java EE 6

inspired...

old name for... new name for...

implements...

name for...

created by...

uses...includes...

created by...

Page 12: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

next. . .

2. CDI Features

Page 13: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Injection points.Class constructor public class Checkout {      

   private final ShoppingCart cart;

   @Inject   public Checkout(ShoppingCart cart) {      this.cart = cart;   }}

Initializer method public class Checkout { private ShoppingCart cart;

@Inject void setShoppingCart(ShoppingCart cart) { this.cart = cart; }}

Direct field public class Checkout { private @Inject ShoppingCart cart;}

Page 14: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Bean types.

A user-defined class or interfaceIn a JEE module with a /META-INF/beans.xml

public class BookShop

extends Business

implements Shop<Book>, Auditable {

...

}

...but «there can be only one»...

Page 15: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Non-default qualifiers.

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

...to declared injection points.

@Inject @Asynchronous PaymentProcessor asyncPaymentProcessor;@Inject @Synchronous PaymentProcessor syncPaymentProcessor;

Custom annotations links...@Qualifier@Retention(RUNTIME)@Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Asynchronous {}

...the qualified bean...

Page 16: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Producer methods.Run time qualifier

public PaymentAction {@Inject @Preferred PaymentStrategy paymentStrategy;...

}

@Singleton @Managedpublic PaymentServiceBean imlements PaymentService {

PaymentStrategy paymentStrategy = PaymentStrategy.CREDIT_CARD;

@Produces @Preferred @SessionScopedpublic PaymentStrategy getPaymentStrategy(CreditCardPaymentStrategy ccps,

CheckPaymentStrategy cps, PayPalPaymentStrategy ppps) {

switch (paymentStrategy) { case CREDIT_CARD: return ccps; case CHEQUE: return cps; case PAYPAL: return ppps; default: return null; } }

Page 17: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Scopes and Contexts.

Built-in scopes✔ (@Dependent)

✔ @RequestScoped

✔ @SessionScoped

✔ @ApplicationScoped

✔ @ConversationScoped

Scope determines...✔ When a new instance of any bean with that scope is created

✔ When an existing instance of any bean with that scope is destroyed

✔ Which injected references refer to any instance of a bean with that scope

✔ CDI features an extensible context model

Page 18: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Conversation Scope.@ConversationScoped @Statefulpublic class OrderBuilder {   private Order order;   private @Inject Conversation conversation;   private @PersistenceContext EntityManager em;

   public Order createOrder() {      order = new Order();      conversation.begin();      return order;   }      public void addLineItem(Product product, int quantity) {      order.add(new LineItem(product, quantity));   }

   public void saveOrder() {      em.persist(order);      conversation.end();   }

   @Remove   public void destroy() {}}

Page 19: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Interceptors.

business method interceptionlifecycle callback interceptiontimeout method interception (ejb3)

Page 20: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Interceptors - 2.

@InterceptorBinding@Target({METHOD, TYPE})@Retention(RUNTIME)public @interface MySecurity {}

Binding

public class ShoppingCart { @MySecurity public void checkout() { ... }}

Page 21: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Interceptors - 3.

@MySecurity @Interceptorpublic class MySecurityInterceptor {

@AroundInvoke public Object manageSecurity(InvocationContext ctx) throws Exception { ... }

}

Implementation - business method:

Implementation - lifecycle: @PostConstruct, @PreDestroy...

Implementation - timeout: @AroundTimeout

Page 22: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Decorators .Interceptors capture orthogonal application concerns The reverse is true of decorators§

@Decoratorpublic abstract class LargeTransactionDecorator implements Account {

@Inject @Delegate @Any Account account; @PersistenceContext EntityManager em; public void withdraw(BigDecimal amount) { account.withdraw(amount); if ( amount.compareTo(LARGE_AMOUNT)>0 ) { em.persist( new LoggedWithdrawl(amount) ); } }

public void deposit(BigDecimal amount); account.deposit(amount); if ( amount.compareTo(LARGE_AMOUNT)>0 ) { em.persist( new LoggedDeposit(amount) ); } }

}

Page 23: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Events.Become observable....

public void onAnyDocumentEvent(@Observes Document document) { ... }

Become observer....

@Inject @Any Event<Document> documentEvent;

documentEvent.fire(document);

...

public void refreshOnDocumentUpdate(@Observes(receive = IF_EXISTS) @Updated Document d) { ... }

public void addProduct(@Observes(during = AFTER_SUCCESS) @Created Product product) { .. }

Many conditional observations...

Page 24: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Stereotypes.

Declare@Stateless@Transactional(requiresNew=true)@Secure@Target(TYPE)@Retention(RUNTIME)@Stereotypepublic @interface BusinessLogic {}

@BusinessLogic public class UserService { ... }

Use

Predefined by CDI: @Interceptor, @Decorator and @Model

@Named@RequestScoped@Documented@Stereotype@Target(TYPE,METHOD,FIELD)@Retention(RUNTIME)public @interface Model {}

Predefine scope and interceptors

Page 25: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

JEE comp env resources.@Produces @Resource(lookup="java:global/env/jdbc/CustomerDatasource") @CustomerDatabase Datasource customerDatabase;

@Produces @PersistenceUnit(unitName="CustomerDatabase") @CustomerDatabase EntityManagerFactory customerDatabasePersistenceUnit;

@Produces @WebServiceRef(lookup="java:app/service/Catalog")Catalog catalog;

@Produces @EJB(ejbLink="../their.jar#PaymentService") PaymentService paymentService;

Page 26: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

next. . .

3. Advices

Page 27: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Similarities – with Seam2.

Spring IoC users: CDI more type-safe and annotation-driven

Seam users: CDI has a lot more advanced features

Guice users: CDI more geared towards enterprise development

Page 28: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Similarities – with D4J .

Only five annotations!

@Inject@Qualifier@Named@Scope@Singleton

Page 29: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Personal experiences.

Good stuffSeam improvement – no outjection, method-time injection etc.

Great for use with other frameworks – like jBPM

XML-hell is /actually/ gone

Be carefulStart off with managed beans – switch when needed

Avoid injection from ”thinner” context – use @Dependent

Weld documentation not finished

Avoid ”upgrade” JBoss AS 5.x

XML Configuration in Seam 3 Module

Annotation Frustration...

Page 30: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

Get started!.

In JBoss 6.0.0.Final (Weld 1.1.0.Beta2)

In GlassFish Server 3.1 (Weld 1.1.0.Final)

Embed Weld in Tomcat, Jetty... Android almost :-)

And read more!

Dan Allens slideshare: Google ”Dan Allen slideshare cdi”

Gavin King and Bob Lee flamewar: Google ”Gavin King Bob Lee jsr"

Page 31: CDI and Weld

Consulting ● Development ● IT Operations ● Training ● Support ● Products

End.

[email protected]