• Save
J2ee standards > CDI
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

J2ee standards > CDI

on

  • 7,773 views

 

Statistics

Views

Total Views
7,773
Views on SlideShare
7,229
Embed Views
544

Actions

Likes
4
Downloads
0
Comments
0

4 Embeds 544

http://savecode.wordpress.com 414
http://www.scoop.it 126
http://www.365dailyjournal.com 3
https://twitter.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

J2ee standards > CDI Presentation Transcript

  • 1. CDI
    Contexts and Dependency Injection
    CDI, formerly known as JSR 299, is an attempt at describing a true standard on Dependency Injection.
  • 2. Introduction
    CDI is the Java standard for dependency injection (DI) and interception (AOP).
    CDI is similar to core Spring and Guice frameworks. Like JPA did for ORM, CDI simplifies and sanitizes the API for DI and AOP.
  • 3. CDI to manage the dependencies
    CDI needs an bean.xml file to be in META-INF of your jar file or classpath or WEB-INF of your web application. This file can be completely empty.
    Use the @Inject annotation to annotate a setXXXsetter method in injected class
  • 4. @Inject
    By default, CDI would look for a class that implements the ATMTransport interface, once it finds this it creates an instance and injects this instance of ATMTransport using the setter method setTransport. If we only had one possible instance of ATMTransport in our classpath, we would not need to annotate any of the ATMTransport implementations. Since we have three, namely, StandardAtmTransport, SoapAtmTransport, and JsonAtmTransport, we need to mark two of them as @Alternatives and one as @Default.
    public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {                private ATMTransport transport;        @Inject        public void setTransport(ATMTransport transport) {                this.transport = transport;        }      }
    Using @Inject to inject via constructor args and fields
    @Inject public AutomatedTellerMachineImpl(ATMTransport transport) {                this.transport = transport;}
  • 5. @Default and @Alternative
    Use the @Default annotation to annotate the StandardAtmTransport
    @Defaultpublic class StandardAtmTransport implements ATMTransport{
    Use the @Alternative to annotate the SoapAtmTransport, and JsonRestAtmTransport.
    @Alternativepublic class JsonRestAtmTransport implements ATMTransport {
  • 6. @Named
    The @Named annotation is used by JEE 6 application to make the bean accessible via the Unified EL (EL stands for Expression language and it gets used by JSPs and JSF components).
    @Named("atm")public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{
    It should be noted that if you use the @Named annotations and don't provide a name, then the name is the name of the class with the first letter lower case so this: makes the name automatedTellerMachineImpl.
  • 7. @Produces
    Instead of relying on a constructor, you can delegate to a factory class to create the instance. To do this with CDI, you would use the @Produces from your factory class as follows:
    public class TransportFactory{                        @Produces ATMTransportcreateTransport() {                System.out.println("ATMTransport created with producer");                return new StandardAtmTransport();        }}
    On calling @Inject   private ATMTransport transport; it calls the factory method.
  • 8. Defining @Alternative
    The @Alternative CDI annotation allows you to have multiple matching dependencies for a given injection point. This means you can define beans that provide implementations for the same interface without worrying about ambigious dependency errors. When you mark a class with the @Alternative annotation, it is effectively disabled and cannot be considered for injection. The only exception is for the class that is defined in the beans.xml configuration file.
    <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
            <alternatives>                <class>org.cdi.advocacy.JsonRestAtmTransport
    </class>        </alternatives>
    </beans>
    Once this bean is identified, it is then used in any injection point that matches for this bean. No other beans for similar injection points can be declared as the ‘active’ alternative.
  • 9. @Qualifier
    All objects and producers in CDI have qualifiers. If you do not assign a qaulifier it by default has the qualifier @Default and @Any.
    You may decide that at times you want to inject Soap or Json or the Standard transport. You don't want to list them as an alternative.
    Qualifiers can be used to discriminate exaclty what gets injected. You can write custom qualifiers.
    @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Soap {}
    @Soappublic class SoapAtmTransport implements ATMTransport {
  • 10. Injecting SoapAtmTransport using new @Soap qualifier via constructor arg
    @Inject public AutomatedTellerMachineImpl(@Soap ATMTransport transport) {                this.transport = transport;        }
    OR
    @Inject @Soapprivate ATMTransport transport;
  • 11. Class uses two qualifiers
    @SuperFast @StandardFrameRelaySwitchingFlubberpublic class SuperFastAtmTransport implements ATMTransport {        public void communicateWithBank(byte[] datapacket) {                System.out.println("communicating with bank via the Super Fast transport " );        }}
    Usage :
    @Inject @SuperFast @StandardFrameRelaySwitchingFlubberprivate ATMTransport transport;
  • 12. To solve Explosion of Qualifiers
    CDI allows you to discriminate on members of a qualifier to reduce the explosion of qualifiers. Instead of having three qualifier you could have one qualifier and an enum. Then if you need more types of transports, you only have to add an enum value instead of another class.
    Let's demonstrate how this works by creating a new qualifier annotation called Transport. The Transport qualifier annotation will have a single member, an enum called type. The type member will be an new enum that we define called TransportType.
    @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Transport {        TransportType type() default TransportType.STANDARD;}
    public enumTransportType {        JSON, SOAP, STANDARD;}
    Usage :
    @Transport(type=TransportType.SOAP)public class SoapAtmTransport implements ATMTransport {
     @Inject @Transport(type=TransportType.STANDARD)private ATMTransport transport;
  • 13. Advanced: Using @Produces and InjectionPoint
    @Inject @TransportConfig(retries=2)private ATMTransport transport;
    @Produces ATMTransportcreateTransport(InjectionPointinjectionPoint) {
                    Bean<?> bean = injectionPoint.getBean();TransportConfigtransportConfig = Bean.getBeanClass().getAnnotation (TransportConfig.class);StandardAtmTransport transport = new StandardAtmTransport();                transport.setRetries(transportConfig.retries());return transport;
    }
  • 14. @Nonbinding
    Using @Nonbinding to combine a configuration annotation and a qualifier annotation into one annotation
    For e.g. - Transport qualifier annotation using @Nonbinding to add configuration retries param.
  • 15. @Any
    @Any finds all of the transports in the system.
    Once you inject the instances into the system, you can use the select method of instance to query for a particular type.
    @Inject @Any private Instance<ATMTransport> allTransports;
    @PostConstruct        protected void init() {                transport = allTransports.select(new AnnotationLiteral<Default>(){}).get();                                if (transport!=null) {                        System.out.println("Found standard transport");                        return;                }                                transport = allTransports.select(new AnnotationLiteral<Json>(){}).get();                                if (transport!=null) {                        System.out.println("Found JSON standard transport");                        return;                }                                transport = allTransports.select(new AnnotationLiteral<Soap>(){}).get();                                                if (transport!=null) {                        System.out.println("Found SOAP standard transport");                        return;                }}
  • 16. @Decorator
    Java EE 6 lets us create decorators through CDI, as part of their AOP features. If we want to implement cross cutting concerns that are still close enough to the business, we can use this feature of Java EE 6.
    @Decorator public class TicketServiceDecorator implements TicketService {
    @Inject @Delegate private TicketServiceticketService;
    @Inject private CateringServicecateringService;
    @Override public Ticket orderTicket(String name) {
    Ticket ticket = ticketService.orderTicket(name);
    cateringService.orderCatering(ticket); return ticket;
    }
    }
  • 17. Injecting Java EE resources into a bean
    All managed beans may take advantage of Java EE component environment injection using @Resource, @EJB, @PersistenceContext, @PeristenceUnit, @PostConstruct and @PreDestroy and @WebServiceRef.
    Example :
    @Transactional @Interceptor public class TransactionInterceptor {    @Resource UserTransaction transaction;
       @AroundInvoke public Object manageTransaction(InvocationContext ctx) throws Exception { ... } }
    @SessionScopedpublic class Login implements Serializable {
       @Inject Credentials credentials;    @PersistenceContext EntityManager userDatabase;     }
  • 18. Dirty truth
    CDI is part of JEE 6. It could easily be used outside of a JEE 6 container. The problem is that there is no standard interface to use CDI outside of a JEE 6 container so the three main implementations Caucho Resin Candi, Red Hat JBoss Weld and Apache OpenWebBeans all have their own way to run a CDI container standalone.
  • 19. Conclusion
    Dependency Injection (DI) refers to the process of supplying an external dependency to a software component.
    CDI is the Java standard for dependency injection and interception (AOP). It is evident from the popularity of DI and AOP that Java needs to address DI and AOP so that it can build other standards on top of it. DI and AOP are the foundation of many Java frameworks.