Context &Dependency InjectionA Cocktail of Guice and Seam, themissing ingredients for Java EE 6           Werner Keil     ...
Without Dependency InjectionExplicit Constructorclass Stopwatch {     final TimeSource timeSource;     Stopwatch () {     ...
Without Dependency InjectionUsing a Factoryclass Stopwatch {     final TimeSource timeSource;     Stopwatch () {       tim...
Without Dependency InjectionMock Datavoid testStopwatch() {   TimeSource original = DTS.getInstance();     DefaultTimeSour...
With Dependency Injection@Injectclass Stopwatch {      final TimeSource timeSource;      @Inject Stopwatch(TimeSource time...
JSR-330Definition @Inject      Identifies injectable constructors, methods, and fields .       This works for both stati...
JSR-330Implementation @Provider      Provides instances of an (injectable) type. Allows                 Retrieving mult...
DEMOwww.catmedia.us          8
JSR-330Configuration1. Minimal but usable API: A small API surface seems   more important than making it as convenient as ...
JSR-330Configuration (2)3. Abstract classes instead of interfaces: 2 main types      (InjectionConfigurer and InjectionSp...
JSR-330Configuration (3)5. Names are different from Guices configuration API:   This is mostly to keep this separate from...
More about JSR-330, see      http://code.google.com/p/atinject                        orhttp://jcp.org/en/jsr/summary?id=3...
Formerly known as WebBeans…www.catmedia.us                   13
JSR-299Services The lifecycle and interactions of stateful components  bound to well-defined lifecycle contexts, where th...
JSR-299Services (2) Integration with the Unified Expression Language (EL),  allowing any component to be used directly wi...
• Sophisticated,• Type Safe,• Dependency  Injection,…www.catmedia.us    16
IN MEMORIAMPietro Ferrero Jr.                  11 September 1963 – 18 April 2011www.catmedia.us                           ...
JSR-299Bean Attributes   A (nonempty) set of bean types   A (nonempty) set of bindings   A scope   A deployment type ...
JSR-299Context• A custom implementation of Context may be  associated with a scope type by calling  BeanManager.addContext...
JSR-299Context (2)• BeanManager.getContext() retrieves an active context  object associated with the a given scope:public ...
JSR-299Restricted Instantiation@SessionScopedpublic class PaymentStrategyProducer {  private PaymentStrategyType  paymentS...
JSR-299Restricted Instantiation (2)@Produces PaymentStrategy  getPaymentStrategy(@CreditCard  PaymentStrategy creditCard,@...
JSR-299Restricted Instantiation (3)[…]         case ONLINE: return online;         default: throw new    IllegalStateExcep...
JSR-299Event Observer• Then the following observer method will always be  notified of the event:• public void afterLogin(@...
JSR-299Event Binding• As elsewhere, binding types may have annotation  members:@BindingType@Target(PARAMETER)@Retention(RU...
JSR-299Event Binding (2) Actually @Role could extend @Named from JSR-330 JSRs here potentially not consequently streamli...
JSR-299Portable Extensionspublic interface Bean<T>extends Contextual<T> {  public Set<Type> getTypes();  public Set<Annota...
JSR-299Portable Extensions (2)    public Class<? extends Annotation>     getDeploymentType();  public String getName();  p...
DEMOwww.catmedia.us          31
More about JSR-299, see       http://www.seamframework.org/                            JCP http://jcp.org/en/jsr/summary?i...
Further Reading     • Java.net       http://www.java.net/     • Java™ EE Patterns and Best Practices       http://kenai.co...
Thank you!                  Contact & Questions                    jcp@catmedia.us                        Twitter         ...
Upcoming SlideShare
Loading in...5
×

Context and Dependency Injection

1,260

Published on

A Cocktail of Guice and Seam, the missing ingredients for Java EE 6

Published in: Technology, Education
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,260
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
34
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Context and Dependency Injection

  1. 1. Context &Dependency InjectionA Cocktail of Guice and Seam, themissing ingredients for Java EE 6 Werner Keil 21/04/2011
  2. 2. Without Dependency InjectionExplicit Constructorclass Stopwatch { final TimeSource timeSource; Stopwatch () { timeSource = new AtomicClock(...); } void start() { ... } long stop() { ... }}www.catmedia.us 2
  3. 3. Without Dependency InjectionUsing a Factoryclass Stopwatch { final TimeSource timeSource; Stopwatch () { timeSource = DefaultTimeSource.getInstance(); } void start() { ... } long stop() { ... }} Somewhat like in java.util.Calendarwww.catmedia.us 3
  4. 4. Without Dependency InjectionMock Datavoid testStopwatch() { TimeSource original = DTS.getInstance(); DefaultTimeSource.setInstance(new MockTimeSource()); try { Stopwatch sw = new Stopwatch(); ... } finally { DTS.setInstance(original); }}www.catmedia.us 4
  5. 5. With Dependency Injection@Injectclass Stopwatch { final TimeSource timeSource; @Inject Stopwatch(TimeSource timeSource) { this.timeSource = TimeSource; } void start() { ... } long stop() { ... } }www.catmedia.us 5
  6. 6. JSR-330Definition @Inject  Identifies injectable constructors, methods, and fields . This works for both static and non-static elements. @Qualifier  Identifies qualifier annotations to declare binding types of your API @Named  A name (string) based qualifier  Others may be declared application - or domain-specificwww.catmedia.us 6
  7. 7. JSR-330Implementation @Provider  Provides instances of an (injectable) type. Allows  Retrieving multiple instances.  Lazy or optional retrieval of an instance.  Breaking circular dependencies.  Abstracting scope @Singleton  Identifies a type that the injector only instantiates once.  See the well-known Design Patternwww.catmedia.us 7
  8. 8. DEMOwww.catmedia.us 8
  9. 9. JSR-330Configuration1. Minimal but usable API: A small API surface seems more important than making it as convenient as possible for clients. There are only two methods in the proposed API that could be considered convenience, added because they seemed to pull their weight  InjectionConfigurer.inject and InjectionSpec.inject(Object)2. Builder-style API: so-called "fluent APIs“ • Open to other styles.www.catmedia.us 9
  10. 10. JSR-330Configuration (2)3. Abstract classes instead of interfaces: 2 main types  (InjectionConfigurer and InjectionSpec) are abstract classes instead of interfaces.  This allows new methods to be added later in a binary- compatible way.4. Separate configuration API • The API does not specify how an instance of InjectionConfigurer is obtained. • Otherwise we have to standardize the injector API itself, something outside of the stated scope of JSR-330.www.catmedia.us 10
  11. 11. JSR-330Configuration (3)5. Names are different from Guices configuration API: This is mostly to keep this separate from existing configuration APIs, but also so that new concepts (like "Binding") dont have to be defined.www.catmedia.us 11
  12. 12. More about JSR-330, see http://code.google.com/p/atinject orhttp://jcp.org/en/jsr/summary?id=330www.catmedia.us 12
  13. 13. Formerly known as WebBeans…www.catmedia.us 13
  14. 14. JSR-299Services The lifecycle and interactions of stateful components bound to well-defined lifecycle contexts, where the set of contexts is extensible A sophisticated, type safe dependency injection mechanism, including a facility for choosing between various components that implement the same Java interface at deployment time An event notification modelwww.catmedia.us 14
  15. 15. JSR-299Services (2) Integration with the Unified Expression Language (EL), allowing any component to be used directly within a JSF or JSP page The ability to decorate injected components A web conversation context in addition to the three standard web contexts defined by the Java Servlets specification An SPI allowing portable extensions to integrate cleanly with the Java EE environmentwww.catmedia.us 15
  16. 16. • Sophisticated,• Type Safe,• Dependency Injection,…www.catmedia.us 16
  17. 17. IN MEMORIAMPietro Ferrero Jr. 11 September 1963 – 18 April 2011www.catmedia.us 17
  18. 18. JSR-299Bean Attributes A (nonempty) set of bean types A (nonempty) set of bindings A scope A deployment type Optionally, a bean EL name A set of interceptor bindings A bean implementationwww.catmedia.us 18
  19. 19. JSR-299Context• A custom implementation of Context may be associated with a scope type by calling BeanManager.addContext().public void addContext(Context context);www.catmedia.us 19
  20. 20. JSR-299Context (2)• BeanManager.getContext() retrieves an active context object associated with the a given scope:public Context getContext(Class<? extends Annotation> scopeType);→ Context used in a broader meaning than some other parts of Java (Enterprise)www.catmedia.us 20
  21. 21. JSR-299Restricted Instantiation@SessionScopedpublic class PaymentStrategyProducer { private PaymentStrategyType paymentStrategyType; public void setPaymentStrategyType( PaymentStrategyType type) { paymentStrategyType = type; }www.catmedia.us 21
  22. 22. JSR-299Restricted Instantiation (2)@Produces PaymentStrategy getPaymentStrategy(@CreditCard PaymentStrategy creditCard,@Cheque PaymentStrategy cheque,@Online PaymentStrategy online) { switch (paymentStrategyType) { case CREDIT_CARD: return creditCard; case CHEQUE: return cheque;[…]www.catmedia.us 22
  23. 23. JSR-299Restricted Instantiation (3)[…] case ONLINE: return online; default: throw new IllegalStateException(); } }}www.catmedia.us 23
  24. 24. JSR-299Event Observer• Then the following observer method will always be notified of the event:• public void afterLogin(@Observes LoggedInEvent event) { ... }• Whereas this observer method may or may not be notified, depending upon the value of user.getRole():• public void afterAdminLogin(@Observes @Role("admin") LoggedInEvent event) { ... }www.catmedia.us 24
  25. 25. JSR-299Event Binding• As elsewhere, binding types may have annotation members:@BindingType@Target(PARAMETER)@Retention(RUNTIME)public @interface Role { String value();}www.catmedia.us 25
  26. 26. JSR-299Event Binding (2) Actually @Role could extend @Named from JSR-330 JSRs here potentially not consequently streamlined…?www.catmedia.us 26
  27. 27. JSR-299Portable Extensionspublic interface Bean<T>extends Contextual<T> { public Set<Type> getTypes(); public Set<Annotation> getBindings(); public Class<? extends Annotation> getScopeType();www.catmedia.us 27
  28. 28. JSR-299Portable Extensions (2) public Class<? extends Annotation> getDeploymentType(); public String getName(); public Class<?> getBeanClass(); public boolean isNullable();public Set<InjectionPoint> getInjectionPoints();}www.catmedia.us 28
  29. 29. DEMOwww.catmedia.us 31
  30. 30. More about JSR-299, see http://www.seamframework.org/ JCP http://jcp.org/en/jsr/summary?id=299 orhttp://www.developermarch.com/devel opersummit/sessions.html#session66 (cancelled ;-/)www.catmedia.us 32
  31. 31. Further Reading • Java.net http://www.java.net/ • Java™ EE Patterns and Best Practices http://kenai.com/projects/javaee-patterns /www.catmedia.us 33
  32. 32. Thank you! Contact & Questions jcp@catmedia.us Twitter @wernerkeilwww.catmedia.us 34
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×