10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

24
10/8/12 http://free.smartbiz.vn 1 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation

Transcript of 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

Page 1: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 http://free.smartbiz.vn 1

JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation

Page 2: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 2

Table Of Content

I. JSR-299 Overview: CDI JavaEE JSR-299.pngII. Beans & Bean ArchivesIII. Typesafe Dependency Injection

III.1. InjectionIII.2. Qualifiers III.3. Stereotypes

IV. Loose Coupling with Strong TypingIV.1. Producer MethodsIV.2. Interceptors: decouple orthogonal concern(AOP) IV.3. Decorators: decouple orthogonal concern(AOP)IV.4. Events: decouple producer from consumer

Page 3: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 3

I.1. DI & Current Problems

Dependency InjectionClasses define what are their dependencies,

not how they obtain themObject dependencies are set externallyUnit-test and mocking friendlyDI framework - object is managed & have lifecycle

Current Problems:Problematic integration between J2EE components“Crippled” dependency-injection in EJBNo standard –proprietary DI (spring, guice, seam)Reliance on string qualifiers (no compile-time safety)

Page 4: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 4

I.2. What is CDI - DI framework

Type-safe & loose-coupling; synthesizes best ideas from Seam, Guice & Spring.

Uses JSR-330 (Dependency Injection for Java), lead by Spring and Guice, which defines only DI annotations (for JavaSE)

DI JavaEE-wide – JSF managed beans, EJB, JavaEE Resources. Makes JavaEE much more flexible, testable, pluggable and extensible.

Page 5: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 5

II. Beans & Bean Archives

Bean Archive:Bean Archive has META-INF/beans.xmlAll classes within a bean archive are beans, and

eligible for injectionAll classes in outside bean archives are not beans

Beans can have:Scope, EL name, Type(s)Qualifiers, Interceptors.

Beans can be JSF beans, EJBs, JavaEE resources

Page 6: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 6

II.1. Bean Scopes

Built-in scopes (normal vs. pseudo):@ApplicationScoped – i.e. Singleton@RequestScoped – created on HttpRequest@SessionScoped – within a HttpSession@ConversationScoped – between request & session@Dependent (default, pseudo) – the object lives as

long as the object it is injected intoCustom scopes

Page 7: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 7

II.2. Bean Name

@Named("beanName"). Defaults to the decapitalized, simple name of the class

Used in EL expressions:

Used in injections (discouraged)

<h:outputText value="#{orderBean.order.price}" />

@Inject @Named("ordersBean")private OrdersBean orderBean;

Page 8: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 8

III.1. Injection

@javax.inject.Inject is used:

The “dao” field is called “injection point”. Injection point types are: Field Constructor Initializer Setter

public class OrdersBean {@Inject private OrdersDao dao;

}

Page 9: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 9

III.1. Injection Points

public class OrdersBean { @Inject private OrdersDao dao; //Field

@Inject public OrdersBean(OrdersDao dao){}//Construct

@Inject public void init(OrdersDao dao){} //Initial @Inject public void setOrdersDao (OrdersDao dao){} //Setter}

Page 10: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 10

III.1. Injection Targets

Inject into:POJOsEJB Session BeansServlets

Injection candidates:POJOsEJB Session BeansJavaEE Resources

Page 11: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 11

III.2. Qualifiers (like extension of interface)

Lookup of specific implementation at runtime

Qualifiers - differentiate beans with same type

@Qualifier //akin to factory method pattern public @interface Synchronous {}

@Inject @Synchronous private CreditCardProcessor processor;

@Synchronouspublic class SynchronousCreditCardProcessor implements CreditCardProcessor {..}@Asynchronouspublic class AsyncCreditCardProcessor implements CreditCardPRocessor {..}

Page 12: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 12

III.2. Built-in Qualifiers

@Any – all beans, unless they have @New @Default, @Named @New – forces the container to return

a new bean instance each time@New public class SomeBean {..}

public class AnotherBean { @Inject SomeBean bean1; @Inject SomeBean bean2; @PostConstruct void init() { log.info(bean1 == bean2); // false }}

Page 13: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 13

III.3. Stereotypes

Architectural “patterns” with recurring roles Stereotypes are used to reduce the amount of

boilerplate code:@Stereotype //denoting a stereotype@Named //built-in qualifier@RequestScoped //scope//enabled for a particular deployment @Alternative public @interface RequestScopedSecureBean {}@RequestScopedNamed Beanpublic class OrdersBean {..}

Page 14: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 14

III.4. Programmatic lookup When qualifiers are to be examined at runtime:@Inject @Anyprivate Instance<CreditCardProcessor> ccProc;public void processPayment( Payment payment, boolean synchronously) { Annotation qualifier = synchronously ? new SynchronousLiteral() : new AsynchronousLiteral(); CreditCardProcessor actualProcessor = ccProc.select(qualifier).get(); actualProcessor.process(payment);}class SynchronousLiteral extends AnnotationLiteral<Synchronous> {}

Page 15: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 15

IV.1. Producer Methods

Write producer methods/fields if more logic is needed at instance creation time: utilize complex construction, non-beans injection.

Handles object disposal//This class is within a bean archiveclass ConnectionProducer { //similar Seam’s @Factory annotation @Produces Connection createConnection() { } void dispose(@Disposes Connection conn) { conn.close(); // when gets out of scope }}

Page 16: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 16

IV.1. Producer Fields

Allow injecting JavaEE resources:

@Produces @Prices @Resource(name="java:global/env/jms/Prices")private Topic pricesTopic;

@Produces @UserDatabase @PersistenceContextprivate EntityManager userDatabase;

@Produces // non-JavaEE producer fieldprivate Some3rdPartyBean bean = new Some3rdPartyBean();

Page 17: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 17

IV.2. InterceptorsInterceptor bindings

Declaring the actual interceptor:

/** Used to identify which Interceptors * should be applied to a bean. */@InterceptorBinding // + Retention & Targetpublic @interface Transactional{ @Nonbinding boolean requiresNew(); }

@Transactional @Interceptorpublic class TransactionInterceptor { @AroundInvoke public Object invoke(InvocationContext ctx){ … return context.proceed(); …}}

Page 18: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 18

IV.2. Interceptors

Declaring the interceptor on the target bean

Like decorators, must be enabled in beans.xml Interceptors-to-intercepted targets:

many-to-many Interceptors-to-interceptor bindings:

many-to-many Binding vs @NonBinding interceptor attributes

@Transactional //all methods are transactionalpublic class OrderService { .. }

Page 19: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 19

IV.3. Decorators Decorators decorate all interfaces they implement @Delegate is used to inject the original object Decorators must be explicitly listed in beans.xml,

in their respective order Decorators can be abstract

@Decoratorpublic class LogDecorator implements Logger { @Delegate @Any private Logger logger; @Override public void log(String msg) { logger.log(timestamp() + ":" + msg); }}

Page 20: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 20

IV.4. Events (Observer/Observable)

Event producer: raise events then delivered to ..

Event observer: delivered to event observers

// qualifiers to narrow event consumers called @Inject @Any Event<Greeting> greeting; public void sayHello(String name){ greeting.fire( new Greeting("hello”+ name));} //”Fire” an event, producer will be notified

public void onGreeting ( //observes @Observes Greeting greeting, User user){ log.info(user + “ says “ + greeting); }

Page 21: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 21

IV.4. Events

Dynamic choice of qualifiers

@Observes(notifyObserver=IF_EXISTS) notifies only if an instance of the declaring bean exists in the current context

@Inject @Any Event<LoggedEvent> loggedEvent;public void login(user) { LoggedEvent event = new LoggedEvent(user); if (user.isAdmin()) { loggedEvent.select( new AdminLiteral()).fire(event); } else { loggedEvent.fire(event);}}

Page 22: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 22

Weld Runtime Environments

Page 23: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 www.smartbiz.vn 23

Concerns

Lack of standardized XML configurationNot many “extras” available yetAnnotation messCDI 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?

Page 24: 10/8/12 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation.

10/8/12 http://free.smartbiz.vn 24

THANK YOU !