CDI Contexts and Dependency Injection for the Java

  • Slides: 36
Download presentation
CDI – Contexts and Dependency Injection for the Java. EE platform (JSR 299) Bozhidar

CDI – Contexts and Dependency Injection for the Java. EE platform (JSR 299) Bozhidar Bozhanov Bulgarian Association of Software Developers www. devbg. org

About me • Senior Java Developer at Fish 4 • 3+ years experience with

About me • Senior Java Developer at Fish 4 • 3+ years experience with Spring and dependency injection • Implementor of JSR-299 as a university project • Committer at Hector (Java Cassandra API) • http: //techblog. bozho. net

Dependency injection? • Classes define what are their dependencies, not how they obtain them

Dependency injection? • Classes define what are their dependencies, not how they obtain them • Object dependencies are set externally • Unit-test and mocking friendly • DI frameworks - objects are managed and have a lifecycle

History • Theoretical basis - Go. F Hollywood principle; Steffano Mazzocchi • Spring –

History • Theoretical basis - Go. F Hollywood principle; Steffano Mazzocchi • Spring – 2002/2003, Rod Johnson • Pico Container - 2003 • Martin Fowler popularized the term - 2004 • JBoss Seam, Google Guice, EJB 3. 0 • Contexts and Dependency Injection (JSR-299, Java. EE 6) - 2006 -2009

Current problems • Problematic integration between Java. EE components • „Crippled“ dependency-injection in EJB

Current problems • Problematic integration between Java. EE components • „Crippled“ dependency-injection in EJB • No standard – only propriatary DI frameworks (spring, guice, seam) • Extended reliance on string qualifiers (no compile-time safety)

JSR-299 • What's a JSR? • CDI Initially named „Web Beans“ • Expert Group

JSR-299 • What's a JSR? • CDI Initially named „Web Beans“ • Expert Group formed in June 2006, spec-lead is Gavin King • Early draft (2007), Public review (2008), Final draft (mid-2009), Ralease (Dec 2009) • Bob Lee (Guice) left the expert group • IBM voted „No“, Google voted „Yes“, VMware (Spring. Source) and Eclipse didn't vote.

What is CDI • Type-safe DI framework (based on Seam, Guice and Spring) •

What is CDI • Type-safe DI framework (based on Seam, Guice and Spring) • Uses JSR-330 (Dependency Injection for Java), lead by Rod Johnson (Spring) and Bob Lee (Guice), which defines only DI annotations (for Java. SE) • DI Java. EE-wide – JSF managed beans, EJB, Java. EE Resources

Implementations; web profile • Three implementations: JBoss Weld, Apache Open. Web. Beans and Resin

Implementations; web profile • Three implementations: JBoss Weld, Apache Open. Web. Beans and Resin Can. DI • Only one stable at the moment – Weld, used in Glassfish v 3 and JBoss AS (5. 2, 6) • Java. EE 6 has the so-called „profiles“. CDI is part of the „Web profile“ • CDI implementations are not limited to application servers (with the help of extensions)

Java EE structure with CDI

Java EE structure with CDI

Beans and bean archives • A bean archive has META-INF/beans. xml • All classes

Beans and bean archives • A 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 type(s), scope, EL name, qualifiers, interceptors. • Beans can be JSF beans, EJBs, Java. EE resources

Injection • @javax. inject. Inject is used: public class Orders. Bean { @Inject private

Injection • @javax. inject. Inject is used: public class Orders. Bean { @Inject private Orders. Dao dao; } • The „dao“ field is called „injection point“. Injection point types are: • Field • Constructor • Setter • Initializer

Injection points public class Orders. Bean { @Inject private Orders. Dao dao; @Inject public

Injection points public class Orders. Bean { @Inject private Orders. Dao dao; @Inject public Orders. Bean(Orders. Dao dao){} @Inject public void init(Orders. Dao dao) {} @Inject public void set. Orders. Dao(Orders. Dao dao){} }

Injection targets • Inject into: – POJOs – EJB Session Beans – Servlets •

Injection targets • Inject into: – POJOs – EJB Session Beans – Servlets • Injection candidates: – POJOs – EJB Session Beans – Java. EE Resources

Bean scopes • Built-in scopes (normal vs pseudo): • @Application. Scoped – i. e.

Bean scopes • Built-in scopes (normal vs pseudo): • @Application. Scoped – i. e. Singleton • @Request. Scoped – created on http request • @Session. Scoped – within a Http. Session • @Conversation. Scoped – between request and session • @Dependent (default, pseudo) – the object lives as long as the object it is injected into • Custom scopes

Bean name • @Named("bean. Name"). Defaults to the decapitalized, simple name of the class

Bean name • @Named("bean. Name"). Defaults to the decapitalized, simple name of the class • Used in EL expressions: <h: output. Text value="#{order. Bean. order. price}" /> • Used in injections (discouraged) @Inject @Named("orders. Bean") private Orders. Bean order. Bean;

Qualifiers • Qualifiers are annotations (unlike in spring): @Qualifier //retention & target ommitted public

Qualifiers • Qualifiers are annotations (unlike in spring): @Qualifier //retention & target ommitted public @interface Synchronous {} • Qualifiers are used to differentiate beans with the same type: @Synchronous public class Synchronous. Credit. Card. Processor implements Credit. Card. Processor {. . } @Asynchronous public class Async. Credit. Card. Processor implements Credit. Card. PRocessor {. . } @Inject @Synchronous private Credit. Card. Processor processor;

Built-in qualifiers • @Any – all beans have this, unless they have @New •

Built-in qualifiers • @Any – all beans have this, unless they have @New • @Default, @Named • @New – forces the container to return a new bean instance each time @New public class Some. Bean {. . } public class Another. Bean { @Inject Some. Bean bean 1; @Inject Some. Bean bean 2; @Post. Construct void init() { // false System. out. println(bean 1 == bean 2); } }

Stereotypes • Stereotypes are used to reduce the amount of boilerplate code: @Stereotype //denoting

Stereotypes • Stereotypes are used to reduce the amount of boilerplate code: @Stereotype //denoting a stereotype @Named // built-in qualifier @Request. Scoped // scope public @interface Request. Scoped. Secure. Bean {} @Request. Scoped. Named Bean public class Orders. Bean {. . }

Demo (Beans, Injection, Qualifiers, Stereotypes, EL)

Demo (Beans, Injection, Qualifiers, Stereotypes, EL)

Producers • A way to utilize complex construction • Allow non-beans to be injected

Producers • A way to utilize complex construction • Allow non-beans to be injected (i. e. 3 rd party classes outside a bean-archive) • Handles object disposal //this class is within a bean archive class Connection. Producer { @Produces Connection create. Connection() { // create and return jdbc connection } // when the object gets out of scope void dispose(@Disposes Connection con) { con. close(); } }

Producer fields • Allow injecting Java. EE resources: @Produces @Some. Topic @Resource(name="topics/Some. Topic") private

Producer fields • Allow injecting Java. EE resources: @Produces @Some. Topic @Resource(name="topics/Some. Topic") private Topic some. Topic; @Produces @Persistence. Context private Entity. Manager entity. Manager; @Produces // non-Jave. EE producer field private Some 3 rd. Party. Bean bean = new Some 3 rd. Party. Bean();

Injection point metadata • Gives information about the injection point @Produces Logger create. Logger(Injection.

Injection point metadata • Gives information about the injection point @Produces Logger create. Logger(Injection. Point injection. Point) { return Logger. get. Logger(injection. Point. get. Member(). get. Declaring. Class()); } @Produces @Http. Param("") String get. Param. Value(Servlet. Request request, Injection. Point ip) { return request. get. Parameter(ip. get. Annotation(Http. Param. class). value()); } }

Decorators • Decorators decorate all interfaces they implement • @Delegate is used to inject

Decorators • Decorators decorate all interfaces they implement • @Delegate is used to inject the original object • Decorators must be explicitly listed in beans. xml, @Decorator in their respective order classcan Log. Decorator implements Logger • public Decorators be abstract @Delegate @Any private Logger logger; @Override public void log(String msg) { logger. log(timestamp() + ": " + msg); } } {

Interceptors • Interceptor bindings (can be nested or included in stereotypes) @Interceptor. Binding //

Interceptors • Interceptor bindings (can be nested or included in stereotypes) @Interceptor. Binding // + retention & target public @interface Transactional{} @Interceptor. Bindings @Transactional public @interface Data. Access {} • Declaring the actual interceptor: @Transactional @Interceptor public class Transaction. Interceptor { @Around. Invoke public Object manage(Invocation. Context ctx) throws Exception {. . } }

Interceptors (2) • Declaring the interceptor on the target bean @Transactional //all methods are

Interceptors (2) • Declaring the interceptor on the target bean @Transactional //all methods are transactional public class Order. Service {. . } • Like decorators, must be enabled in beans. xml • Interceptors-to-intercepted targets: many-tomany • Interceptors-to-interceptor bindings: many-tomany • Binding vs @Non. Binding interceptor attributes

Demo (Producers, Decorators, Interceptors)

Demo (Producers, Decorators, Interceptors)

Programmatic lookup • When qualifiers are to be examined at runtime: @Inject @Any private

Programmatic lookup • When qualifiers are to be examined at runtime: @Inject @Any private Instance<Credit. Card. Processor> cc. Proc; public void process. Payment( Payment payment, boolean synchronously) { Annotation qualifier = synchronously ? new Synchronous. Literal() : new Asynchronous. Literal(); Credit. Card. Processor actual. Processor = cc. Proc. select(qualifier). get(); actual. Processor. process(payment); } class Synchronous. Literal extends Annotation. Literal<Synchronous> {}

Events • Event producer, making use of generics: @Inject @Event. Qualifier private Event<Sample. Event>

Events • Event producer, making use of generics: @Inject @Event. Qualifier private Event<Sample. Event> event; public void fire. Event() { event. fire(new Simple. Event()); } • Event observer (with the appropriate qualifier) public void observes( @Observes @Event. Qualifier Sample. Event event) {. . } }

Events (2) • Dynamic choice of qualifiers @Inject @Any Event<Logged. Event> logged. Event; public

Events (2) • Dynamic choice of qualifiers @Inject @Any Event<Logged. Event> logged. Event; public void login(user) { Logged. Event event = new Logged. Event(user); if (user. is. Admin()) { logged. Event. select( new Admin. Literal()). fire(event); } else { logged. Event. fire(event); } } • @Observes(notify. Observer=IF_EXISTS) notifies only if an instance of the declaring bean

Circular dependencies • CDI implementations must use proxies for all scopes, except @Dependent @Application.

Circular dependencies • CDI implementations must use proxies for all scopes, except @Dependent @Application. Scoped public class Bean 1 { @Inject public Bean 1(Bean 2 bean 2) {. . } } @Application. Scoped public class Bean 2 { @Inject public Bean 2(Bean 1 bean 1) {. . } }

Demo (Programatic lookup, Events, Circular Dependencies)

Demo (Programatic lookup, Events, Circular Dependencies)

Portable extensions • CDI allows plugable extensions that can access the context, hook to

Portable extensions • CDI allows plugable extensions that can access the context, hook to context events • Providing its own beans, interceptors and decorators to the container • Injecting dependencies into its own objects using the dependency injection service • Providing a context implementation for a custom scope • Augmenting or overriding the annotationbased metadata with metadata from some other source

Portable extensions (2) • http: //seamframework. org/Weld/Portable. Exte nsions. Package • XML configuration •

Portable extensions (2) • http: //seamframework. org/Weld/Portable. Exte nsions. Package • XML configuration • Wicket integration • Java. SE and Servlet container support

Concerns • Lack of standardized XML configuration • Not many „extras“ available yet •

Concerns • Lack of standardized XML configuration • Not many „extras“ available yet • Annotation mess • CDI interceptors might not be sufficient, compared to Spring AOP (Aspect. J syntax) • (un)portable extensions may become exactly what spring is being critized for – size and complexity • Complex • Being a standard?

Resources • http: //seamframework. org/service/File/105766 • http: //www. slideshare. net/johaneltes/java-ee 6 -cdi • http:

Resources • http: //seamframework. org/service/File/105766 • http: //www. slideshare. net/johaneltes/java-ee 6 -cdi • http: //www. slideshare. net/mojavelinux/jsr 299 cdi-weld-the-future-of-seam-javaone-2010 • http: //download. oracle. com/javaee/6/tutorial/ doc/gjbnz. html

Questions?

Questions?