CDI . Standardized Dependency Injection in JEE6 - - PowerPoint PPT Presentation

cdi
SMART_READER_LITE
LIVE PREVIEW

CDI . Standardized Dependency Injection in JEE6 - - PowerPoint PPT Presentation

CDI . Standardized Dependency Injection in JEE6 jens.augustsson@redpill-linpro.com Consulting Development IT Operations Training Support Products CDI . 1. What it is 2. Features 3. Advices Consulting Development


slide-1
SLIDE 1

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

CDI .

Standardized Dependency Injection in JEE6

jens.augustsson@redpill-linpro.com

slide-2
SLIDE 2

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

CDI.

  • 1. What it is
  • 2. Features
  • 3. Advices
slide-3
SLIDE 3

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

Jens X Augustsson.

JBoss AS 6

jens.augustsson@redpill-linpro.com

Seam jBPM Hibernate Spring Core

slide-4
SLIDE 4

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

next...

  • 1. What it is
slide-5
SLIDE 5

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(); } }

slide-6
SLIDE 6

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)

slide-7
SLIDE 7

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

new Instance(), anyone?.

«The fundamental choice is between Service Locator and Dependency Injection» (Martin Fowler)

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

Dependencies Container managed Configuration Life cyle ...

slide-8
SLIDE 8

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

part of...

«but I've heard...»

CDI WebBeans Weld D4J JSR-299 JSR-330 Seam 2 Seam 3 Guice Spring Core Java EE 6

inspired...

  • ld name for...

new name for... implements... name for... created by... extends... includes... created by...

Hibernate JPA

standardized next project...

JBoss AS 6

supports

slide-9
SLIDE 9

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

next...

  • 2. CDI Features
slide-10
SLIDE 10

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; }

slide-11
SLIDE 11

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

Injectable bean types.

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

public class CreditCardPaymentService implements PaymentService { ... }

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

... @Inject CreditCardPaymentService ps; ... ... @Inject PaymentService ps; ...

  • r?

declare use

slide-12
SLIDE 12

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

Non-default qualifiers.

@Preferred public class CreditCardPaymentService implements PaymentService { public void process(Payment payment) { ... } }

...links a declared injection point...

... @Inject @Preferred PaymentService ps; ...

Your custom annotations...

@Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface Preferred {}

...to a qualified bean

CDI anno JavaSE annos Your anno

slide-13
SLIDE 13

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

Qualifiers with members.

@PayBy(CREDIT) public class CreditCardProcessor implements PaymentProcessor { public void process(Payment payment) { ... } }

...links a declared injection point...

... private @Inject @PayBy(CREDIT) PaymentProcessor checkPayment; ...

Your custom annotation and enumeration...

@Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface PayBy { PaymentMethod value();

...to a qualified bean

Your enum

slide-14
SLIDE 14

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

Producer methods.

Run time qualifier

public PaymentAction { @Inject @Preferred PaymentService userPaymentService; ... } public AnyClass { @Inject User user; @Produces @Preferred public PaymentService getUserPaymentService() { return user.getPaymentServices().get(0); } }

slide-15
SLIDE 15

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; Your anno CDI anno JEE anno

... @Inject @CustomerDatabase Datasource ds; ...

slide-16
SLIDE 16

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

JEE integration.

Built-in beans

the current JTA UserTransaction a Principal representing the current caller identity the default Bean ValidationFactory a Validator for the default ValidationFactory

slide-17
SLIDE 17

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

Scopes and Contexts.

Scope determines...

When an instance is created

When an instance is destroyed

Which injected references refer to an instance

CDI features an extensible context model

First: The ”dependent” pseudo-scope

public class Calculator { ... } @Dependent public class Calculator { ... }

=

slide-18
SLIDE 18

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

Scopes misc.

The @New qualifier

public class PaymentCalc { @Inject Calculator calculator; @Inject @New Calculator newCalculator; }

Also: Built-in scopes

@RequestScoped

@SessionScoped

@ApplicationScoped

@ConversationScoped JEE defined Defined by you

@SessionScoped public class Calculator { ... }

slide-19
SLIDE 19

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

Conversation Scope.

@ConversationScoped @Stateful public class OrderBuilder { private Order order; private @Inject Conversation conversation; private @PersistenceContext EntityManager em; public Order createOrder() {

  • rder = new Order();

conversation.begin(); return order; } public void addLineItem(Product product, int quantity) {

  • rder.add(new LineItem(product, quantity));

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

slide-20
SLIDE 20

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

Interceptors.

business method interception lifecycle callback interception timeout method interception (ejb3)

slide-21
SLIDE 21

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() { ... } } CDI anno Your anno

slide-22
SLIDE 22

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

Interceptors - 3.

@MySecurity @Interceptor public class MySecurityInterceptor { @AroundInvoke public Object manageSecurity(InvocationContext ctx) throws Exception { ... } }

Implementation - business method: Implementation - lifecycle: @PostConstruct, @PreDestroy... Implementation - timeout: @AroundTimeout

slide-23
SLIDE 23

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

Decorators .

Interceptors capture orthogonal application concerns The reverse is true of decorators

§ @Decorator public 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) ); } } }

slide-24
SLIDE 24

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

Events.

Become observable....

public void handleDocs(@Observes @Updated Document document) { ... }

Become observer....

@Inject @Updated Event<Document> documentEvent; ... document.setLastModified(new Date()); documentEvent.fire(document);

public void handleDocs(@Observes(during = AFTER_SUCCESS) @Updated Document doc) { .. }

Conditional observations...

Optional qualifier

slide-25
SLIDE 25

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

Stereotypes.

Declare

@Stateless @Transactional(requiresNew=true) @Secure @Stereotype @Target(TYPE) @Retention(RUNTIME) public @interface BusinessLogic {} @BusinessLogic public class UserService { ... }

Use Predefined by CDI: @Model

@Named @RequestScoped @Documented @Stereotype @Target(TYPE,METHOD,FIELD) @Retention(RUNTIME) public @interface Model {} Predefine scope and interceptors EJB your CDI JSE

slide-26
SLIDE 26

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

next...

  • 3. Advices
slide-27
SLIDE 27

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

Personal experiences.

Good stuff

Seam improvement – no outjection, method-time injection etc. Great for use with other frameworks – like jBPM XML-hell is /actually/ gone

But be careful

Start off with managed beans – switch when needed Annotations are adjectives (@Preferred), not nouns (@CreditCardPayment) 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...

slide-28
SLIDE 28

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 :-) Generate CDI project using Seam Forge or M2Eclipse And read more!

Dan Allens slideshare: Google ”Dan Allen slideshare cdi” Gavin King and Bob Lee flamewar: Google ”Gavin King Bob Lee jsr"

slide-29
SLIDE 29

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

End.

jens.augustsson@redpill-linpro.com