Download presentation
Presentation is loading. Please wait.
Published byBarbara McKenzie Modified over 9 years ago
1
10/8/12http://free.smartbiz.vn1 JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation
2
10/8/12www.smartbiz.vn2 Table Of Content I. JSR-299 Overview: CDI JavaEE JSR-299.png II. Beans & Bean Archives III. Typesafe Dependency Injection III.1. Injection III.2. Qualifiers III.3. Stereotypes IV. Loose Coupling with Strong Typing IV.1. Producer Methods IV.2. Interceptors: decouple orthogonal concern(AOP) IV.3. Decorators: decouple orthogonal concern(AOP) IV.4. Events: decouple producer from consumer
3
10/8/12www.smartbiz.vn3 I.1. DI & Current Problems Dependency Injection Classes define what are their dependencies, not how they obtain them Object dependencies are set externally Unit-test and mocking friendly DI framework - object is managed & have lifecycle Current Problems: Problematic integration between J2EE components “Crippled” dependency-injection in EJB No standard –proprietary DI (spring, guice, seam) Reliance on string qualifiers (no compile-time safety)
4
10/8/12www.smartbiz.vn4 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.
5
10/8/12www.smartbiz.vn5 II. Beans & Bean Archives Bean Archive: 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: Scope, EL name, Type(s) Qualifiers, Interceptors. Beans can be JSF beans, EJBs, JavaEE resources
6
10/8/12www.smartbiz.vn6 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 into Custom scopes
7
10/8/12www.smartbiz.vn7 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}" /> value="#{orderBean.order.price}" /> @Inject @Named("ordersBean") private OrdersBean orderBean;
8
10/8/12www.smartbiz.vn8 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; }
9
10/8/12www.smartbiz.vn9 III.1. Injection Points public class OrdersBean { @Inject private OrdersDao dao; //Field @Inject private OrdersDao dao; //Field @Inject @Inject public OrdersBean(OrdersDao dao){}//Construct public OrdersBean(OrdersDao dao){}//Construct @Inject @Inject public void init(OrdersDao dao){} //Initial public void init(OrdersDao dao){} //Initial @Inject @Inject public void setOrdersDao public void setOrdersDao (OrdersDao dao){} //Setter (OrdersDao dao){} //Setter}
10
10/8/12www.smartbiz.vn10 III.1. Injection Targets Inject into: POJOs EJB Session Beans Servlets Injection candidates: POJOs EJB Session Beans JavaEE Resources
11
10/8/12www.smartbiz.vn11 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; @Synchronous public class SynchronousCreditCardProcessor implements CreditCardProcessor {..} implements CreditCardProcessor {..} @Asynchronous public class AsyncCreditCardProcessor implements CreditCardPRocessor {..} implements CreditCardPRocessor {..}
12
10/8/12www.smartbiz.vn12 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 bean1; @Inject SomeBean bean2; @Inject SomeBean bean2; @PostConstruct void init() { @PostConstruct void init() { log.info(bean1 == bean2); // false log.info(bean1 == bean2); // false }}
13
10/8/12www.smartbiz.vn13 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 {} @RequestScopedNamedBean public class OrdersBean {..}
14
10/8/12www.smartbiz.vn14 III.4. Programmatic lookup When qualifiers are to be examined at runtime: @Inject @Any private Instance ccProc; public void processPayment( Payment payment, boolean synchronously) { Payment payment, boolean synchronously) { Annotation qualifier = synchronously Annotation qualifier = synchronously ? new SynchronousLiteral() ? new SynchronousLiteral() : new AsynchronousLiteral(); : new AsynchronousLiteral(); CreditCardProcessor actualProcessor = CreditCardProcessor actualProcessor = ccProc.select(qualifier).get(); ccProc.select(qualifier).get(); actualProcessor.process(payment); actualProcessor.process(payment);} class SynchronousLiteral extends AnnotationLiteral {} AnnotationLiteral {}
15
10/8/12www.smartbiz.vn15 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 archive class ConnectionProducer { //similar Seam’s @Factory annotation //similar Seam’s @Factory annotation @Produces Connection createConnection() { @Produces Connection createConnection() { } void dispose(@Disposes Connection conn) { void dispose(@Disposes Connection conn) { conn.close(); // when gets out of scope conn.close(); // when gets out of scope }}
16
10/8/12www.smartbiz.vn16 IV.1. Producer Fields Allow injecting JavaEE resources: @Produces @Prices @Resource(name="java:global/env/jms/Prices") private Topic pricesTopic; @Produces @UserDatabase @PersistenceContext private EntityManager userDatabase; @Produces // non-JavaEE producer field private Some3rdPartyBean bean = new Some3rdPartyBean();
17
10/8/12www.smartbiz.vn17 IV.2. Interceptors Interceptor bindings Declaring the actual interceptor: /** Used to identify which Interceptors * should be applied to a bean. */ * should be applied to a bean. */ @InterceptorBinding // + Retention & Target public @interface Transactional{ @Nonbinding boolean requiresNew(); } @Nonbinding boolean requiresNew(); } @Transactional @Interceptor public class TransactionInterceptor { @AroundInvoke @AroundInvoke public Object invoke(InvocationContext ctx){ public Object invoke(InvocationContext ctx){ … return context.proceed(); …} … return context.proceed(); …}}
18
10/8/12www.smartbiz.vn18 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 transactional public class OrderService {.. }
19
10/8/12www.smartbiz.vn19 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 @Decorator public class LogDecorator implements Logger { @Delegate @Any private Logger logger; @Delegate @Any private Logger logger; @Override @Override public void log(String msg) { public void log(String msg) { logger.log(timestamp() + ":" + msg); logger.log(timestamp() + ":" + msg); }}
20
10/8/12www.smartbiz.vn20 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; public void sayHello(String name){ greeting.fire( new Greeting("hello”+ name)); greeting.fire( new Greeting("hello”+ name)); } //”Fire” an event, producer will be notified public void onGreeting ( //observes @Observes Greeting greeting, User user){ @Observes Greeting greeting, User user){ log.info(user + “ says “ + greeting); log.info(user + “ says “ + greeting);}
21
10/8/12www.smartbiz.vn21 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; public void login(user) { LoggedEvent event = new LoggedEvent(user); LoggedEvent event = new LoggedEvent(user); if (user.isAdmin()) { if (user.isAdmin()) { loggedEvent.select( loggedEvent.select( new AdminLiteral()).fire(event); new AdminLiteral()).fire(event); } else { loggedEvent.fire(event);} } else { loggedEvent.fire(event);}}
22
10/8/12www.smartbiz.vn22 Weld Runtime Environments
23
10/8/12www.smartbiz.vn23 Concerns 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?
24
10/8/12http://free.smartbiz.vn24 THANK YOU !
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.