240 likes | 458 Views
JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation. 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
E N D
JSR-299 CDI Java Contexts & Dependency Injection JBoss Weld Implementation http://free.smartbiz.vn
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 www.smartbiz.vn
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) www.smartbiz.vn
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, JavaEEResources. Makes JavaEEmuch more flexible, testable, pluggable and extensible. www.smartbiz.vn
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, JavaEEresources www.smartbiz.vn
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 www.smartbiz.vn
II.2. Bean Name <h:outputText value="#{orderBean.order.price}"/> @Inject@Named("ordersBean") privateOrdersBeanorderBean; @Named("beanName"). Defaults to the decapitalized, simple name of the class Used in EL expressions: Used in injections (discouraged) www.smartbiz.vn
III.1. Injection publicclass OrdersBean { @Injectprivate OrdersDao dao; } • @javax.inject.Inject is used: • The “dao” field is called “injection point”. Injection point types are: • Field • Constructor • Initializer • Setter www.smartbiz.vn
III.1. Injection Points publicclassOrdersBean { @InjectprivateOrdersDaodao; //Field @Inject publicOrdersBean(OrdersDaodao){}//Construct @Inject publicvoidinit(OrdersDaodao){} //Initial @Inject publicvoidsetOrdersDao (OrdersDaodao){} //Setter } www.smartbiz.vn
III.1. Injection Targets • Inject into: • POJOs • EJB Session Beans • Servlets • Injection candidates: • POJOs • EJB Session Beans • JavaEEResources www.smartbiz.vn
III.2. Qualifiers (like extension of interface) @Qualifier //akin to factory method pattern public@interfaceSynchronous {} @Synchronous publicclass SynchronousCreditCardProcessor implementsCreditCardProcessor {..} @Asynchronous publicclassAsyncCreditCardProcessor implementsCreditCardPRocessor {..} @Inject @Synchronous private CreditCardProcessor processor; Lookup of specific implementation at runtime Qualifiers - differentiate beans with same type www.smartbiz.vn
III.2. Built-in Qualifiers @New publicclassSomeBean {..} publicclassAnotherBean { @Inject SomeBean bean1; @Inject SomeBean bean2; @PostConstructvoidinit() { log.info(bean1 == bean2); // false } } @Any – all beans, unless they have @New @Default, @Named @New – forces the container to return a new bean instance each time www.smartbiz.vn
III.3. Stereotypes @Stereotype //denoting a stereotype @Named //built-in qualifier @RequestScoped//scope //enabled for a particular deployment @Alternative public@interfaceRequestScopedSecureBean {} @RequestScopedNamed Bean publicclassOrdersBean {..} Architectural “patterns” with recurring roles Stereotypes are used to reduce the amount of boilerplate code: www.smartbiz.vn
III.4. Programmatic lookup @Inject @Any private Instance<CreditCardProcessor> ccProc; public voidprocessPayment( Payment payment, boolean synchronously) { Annotation qualifier = synchronously ? newSynchronousLiteral() : newAsynchronousLiteral(); CreditCardProcessoractualProcessor = ccProc.select(qualifier).get(); actualProcessor.process(payment); } classSynchronousLiteralextends AnnotationLiteral<Synchronous> {} When qualifiers are to be examined at runtime: www.smartbiz.vn
IV.1. Producer Methods //This class is within a bean archive classConnectionProducer { //similar Seam’s @Factory annotation @Produces Connection createConnection() { } void dispose(@Disposes Connection conn) { conn.close(); // when gets out of scope } } Write producer methods/fields if more logic is needed at instance creation time:utilize complex construction, non-beans injection. Handles object disposal www.smartbiz.vn
IV.1. Producer Fields @Produces @Prices @Resource(name="java:global/env/jms/Prices") private Topic pricesTopic; @Produces @UserDatabase @PersistenceContext privateEntityManageruserDatabase; @Produces // non-JavaEEproducer field private Some3rdPartyBean bean = newSome3rdPartyBean(); Allow injecting JavaEE resources: www.smartbiz.vn
IV.2. Interceptors /** Used to identify which Interceptors * should be applied to a bean. */ @InterceptorBinding// + Retention & Target public @interfaceTransactional{ @Nonbinding booleanrequiresNew(); } @Transactional @Interceptor public class TransactionInterceptor { @AroundInvoke public Object invoke(InvocationContextctx){ … return context.proceed(); …} } Interceptor bindings Declaring the actual interceptor: www.smartbiz.vn
IV.2. Interceptors @Transactional //all methods are transactional public classOrderService { .. } 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 www.smartbiz.vn
IV.3. Decorators @Decorator publicclassLogDecoratorimplements Logger { @Delegate @Any private Logger logger; @Override publicvoid log(String msg) { logger.log(timestamp() + ":" + msg); } } 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 www.smartbiz.vn
IV.4. Events (Observer/Observable) // 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); } Event producer: raise events then delivered to .. Event observer: delivered to event observers www.smartbiz.vn
IV.4. Events @Inject @Any Event<LoggedEvent> loggedEvent; publicvoid login(user) { LoggedEvent event = new LoggedEvent(user); if (user.isAdmin()) { loggedEvent.select( newAdminLiteral()).fire(event); } else { loggedEvent.fire(event);} } Dynamic choice of qualifiers @Observes(notifyObserver=IF_EXISTS) notifies only if an instance of the declaring bean exists in the current context www.smartbiz.vn
Weld Runtime Environments www.smartbiz.vn
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? www.smartbiz.vn
THANK YOU ! http://free.smartbiz.vn