Download as PDF, PPTX
JSR-299 (CDI), Weld and the Future of Seam Dan Allen Principal Software Engineer JBoss by Red Hat
Agenda ●くろまる Java EE today ●くろまる Where JSR-299 fits in ●くろまる JSR-299 themes ●くろまる CDI programming model tour ●くろまる CDI extensions ●くろまる Weld ●くろまる Seam 3 2 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Technology terminology ●くろまる JSR-299 (CDI) ●くろまる Contexts & Dependency Injection for the Java EE Platform ●くろまる Weld ●くろまる JSR-299 Reference Implementation & TCK ●くろまる Extended CDI support (Servlets, Java SE) ●くろまる Portable CDI enhancements for extension writers ●くろまる Seam 3 ●くろまる Portable extensions for Java EE ●くろまる Portable integrations with non-Java EE technologies 3 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
What is Java EE? ●くろまる Standard platform comprised of managed components & services ●くろまる Business logic as components 1. Less code 2. Higher signal-to-noise ratio 3. Powerful mechanisms for free 4. Portable knowledge 4 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Why reinvest? Java EE 5 5 Seam 2 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Stated goal of JSR-299 Web tier Transactional tier (JSF) (EJB) 6 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
What CDI provides ●くろまる Services for Java EE components ●くろまる Lifecycle management of stateful beans bound to well-defined contexts (including conversation context) ●くろまる A type-safe approach to dependency injection ●くろまる Interaction via an event notification facility ●くろまる Reduced coupling between interceptors and beans ●くろまる Decorators, which intercept specific bean instances ●くろまる Unified EL integration (bean names) ●くろまる SPI for developing extensions for the Java EE platform ●くろまる Java EE architecture flexible, portable, extensible 7 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
What CDI provides ●くろまる Services for Java EE components ●くろまる Lifecycle management of stateful beans bound to well-defined contexts (including conversation context) ●くろまる A type-safe approach to dependency injection ●くろまる Interaction via an event notification facility ●くろまる Reduced coupling between interceptors and beans ●くろまる Decorators, which intercept specific bean instances ●くろまる Unified EL integration (bean names) ●くろまる SPI for developing extensions for the Java EE platform ●くろまる Java EE architecture flexible, portable, extensible 8 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
CDI: The big picture ●くろまる Fill in ●くろまる Catalyze ●くろまる Evolve 9 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Why dependency injection? ●くろまる Weakest aspect of Java EE 5 ●くろまる Closed set of injectable resources ●くろまる @EJB ●くろまる @PersistenceContext, @PersistenceUnit ●くろまる @Resource (e.g., DataSource, UserTransaction) ●くろまる Name-based injection is fragile ●くろまる Lacked rules 10 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Leverage and extend Java’s type system @Annotation <TypeParam> This information is pretty useful! Type 11 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
JSR-299 theme @Produces @WishList Loose coupling... List<Product> getWishList() Event<Order> @InterceptorBinding @Inject @UserDatabase EntityManager @Observes @Qualifier ...with strong typing 12 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Loose coupling ●くろまる Decouple server and client ●くろまる Using well-defined types and "qualifiers" ●くろまる Allows server implementation to vary ●くろまる Decouple lifecycle of collaborating components ●くろまる Automatic contextual lifecycle management ●くろまる Stateful components interact like services ●くろまる Decouple orthogonal concerns (AOP) ●くろまる Interceptors & decorators ●くろまる Decouple message producer from consumer ●くろまる Events 13 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Strong typing ●くろまる Type-based injection ●くろまる Eliminate reliance on string-based names ●くろまる Refactor friendly ●くろまる Compiler can detect typing errors ●くろまる No special authoring tools required ●くろまる Casting mostly eliminated ●くろまる Semantic code errors detected at application startup ●くろまる Tooling can detect ambiguous dependencies (optional) 14 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Who's bean is it anyway? ●くろまる Everyone throwing around this term "bean" ●くろまる JSF ●くろまる EJB ●くろまる Seam ●くろまる Spring ●くろまる Guice ●くろまる Web Beans ●くろまる Need a "unified bean definition" 15 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Managed bean specification ●くろまる Common bean definition ●くろまる Instances managed by Managed the container Beans ●くろまる Common services ●くろまる Lifecycle callbacks ●くろまる Resource injections ●くろまる Interceptors JSF EJB CDI JAX-RS ●くろまる Foundation spec How managed beans evolved: http://www.infoq.com/news/2009/11/weld10 16 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
CDI bean ingredients ●くろまる Set of bean types ●くろまる Set of qualifiers ●くろまる Scope ●くろまる Bean EL name (optional) ●くろまる Set of interceptor bindings ●くろまる Alternative classification ●くろまる Bean implementation class Auto-discovered! 17 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Welcome to CDI, managed beans! public class Welcome { public String buildPhrase(String city) { return "Welcome to " + city + "!"; } } 18 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Welcome to CDI, EJB 3.1 session beans! @Stateless public class Welcome { public String buildPhrase(String city) { return "Welcome to " + city + "!"; } } 19 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
When is a bean recognized? ●くろまる Bean archive (WAR) ●くろまる Bean archive (JAR) beans.xml can be empty! 20 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Injection 101 public class Greeter { @Inject Welcome w; public void welcome() { System.out.println( w.buildPhrase("San Francisco")); } } 21 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Where can it be injected? ●くろまる Field ●くろまる Method parameter ●くろまる Constructor* ●くろまる Initializer ●くろまる Producer ●くろまる Observer 22 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
What can be injected? Managed bean Object returned by producer EJB session bean (local or remote) Java EE resource (DataSource, JMS destination, etc) JTA UserTransaction Persistence unit or context Security principle Bean Validation factory Web service reference Additional resources introduced through SPI 23 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
The bean vs "the other implementation" ●くろまる Multiple implementations of same interface ●くろまる One implementation extends another public class Welcome { public String buildPhrase(String city) { return "Welcome to " + city + "!"; } } public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } } 24 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Quiz: Which implementation gets injected? public class Greeter { private Welcome welcome; @Inject void init(Welcome welcome) { this.welcome = welcome; } ... } It's ambiguous! 25 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Working out an ambiguous resolution ●くろまる Qualifier ●くろまる Alternative ●くろまる Producer ●くろまる Veto (or hide) 26 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
qualifier n. an annotation used to resolve an API implementation variant at an injection point 27 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Defining a qualifier @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface Translating {} @interface means annotation @interface means annotation 28 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Qualifying an implementation @Translating public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } } ●くろまる makes type more specific ●くろまる assigns semantic meaning 29 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Qualifier as a "binding type" 30 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Explicitly request qualified interface public class Greeter { private Welcome welcome; No reference to implementation class! No reference to implementation class! @Inject void init(@Translating Welcome welcome) { this.welcome = welcome; } public void welcomeVisitors() { System.out.println( welcome.buildPhrase("San Francisco")); } } 31 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Alternative bean ●くろまる Swap replacement implementation per deployment ●くろまる Replaces bean and its producer methods and fields ●くろまる Disabled by default ●くろまる Must be activated in /META-INF/beans.xml In other words, an override 32 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Defining an alternative @Alternative public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } } 33 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Substituting the alternative ●くろまる Activated using beans.xml <beans> <alternatives> <class>com.acme.TranslatingWelcome</class> </alternatives> </beans> 34 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Assigning a bean (EL) name @Named("greeter") public class Greeter { private Welcome welcome; @Inject void init(Welcome welcome) { this.welcome = welcome; } public void welcomeVisitors() { System.out.println( welcome.buildPhrase("San Francisco")); } } 35 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Assigning a bean (EL) name by convention @Named public class Greeter { private Welcome welcome; Bean name is decapitalized Bean name is decapitalized simple class name simple class name @Inject void init(Welcome welcome) { this.welcome = welcome; } public void welcomeVisitors() { System.out.println( welcome.buildPhrase("San Francisco")); } } 36 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Welcome to CDI, JSF! ●くろまる Use the bean directly in the JSF view <h:form> <h:commandButton value="Welcome visitors" action="#{greeter.welcomeVisitors}"/> </h:form> 37 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
JSF managed beans CDI 38 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Stashing the bean in a context ●くろまる Bean saved for the duration of a request @Named @RequestScoped public class Greeter { @Inject private Welcome w; private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public void welcomeVisitors() { System.out.println(w.buildPhrase(city)); } } 39 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Collapsing layers with state management ●くろまる Now it’s possible for bean to hold state <h:form> <h:inputText value="#{greeter.city}"/> <h:commandButton value="Welcome visitors" action="#{greeter.welcomeVisitors}"/> </h:form> San Francisco Prints: Welcome to San Francisco! 40 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Mission accomplished: We have a deal! Web tier Business tier (JSF) (managed bean) 41 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Scope types and contexts ●くろまる Default scope - @Dependent ●くろまる Bound to lifecycle of bean holding reference ●くろまる Servlet scopes ●くろまる @ApplicationScoped ●くろまる @RequestScoped ●くろまる @SessionScoped ●くろまる JSF conversation scope - @ConversationScoped ●くろまる Custom scopes ●くろまる Define scope type annotation (e.g., @FlashScoped) ●くろまる Implement the context API in an extension 42 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Scope transparency ●くろまる Scopes not visible to client (no coupling) ●くろまる Scoped beans are proxied for thread safety 43 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Conversation context ●くろまる Request ≤ Conversation ≪ Session ●くろまる ●くろまる Boundaries demarcated by application ●くろまる Optimistic transaction ●くろまる Conversation-scoped persistence context ●くろまる No fear of exceptions on lazy fetch operations 44 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Controlling the conversation @ConversationScoped public class BookingAgent { @Inject @BookingDatabase EntityManager em; @Inject Conversation conversation; private Hotel selected; private Booking booking; public void select(Hotel h) { selected = em.find(Hotel.class, h.getId()); conversation.begin(); } ... 45 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Controlling the conversation ... public boolean confirm() { if (!isValid()) { return false; } em.persist(booking); conversation.end(); return true; } } 46 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
producer method n. a method whose return value produces an injectable object 47 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Producer method examples @Produces @RequestScoped public FacesContext getFacesContext() { From non-bean From non-bean return FacesContext.getInstance(); } @Produces public PaymentProcessor getPaymentProcessor( @Synchronous PaymentProcessor sync, Runtime selection Runtime selection @Asynchronous PaymentProcessor async) { return isSynchronous() ? sync : async; } @Produces @SessionScoped @WishList Dynamic result set Dynamic result set public List<Product> getWishList() { return em.createQuery("...").getResultList(); } 48 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Injecting producer return values @Inject FacesContext ctx; @Inject PaymentProcessor pp; @Inject @WishList List<Product> wishlist; Origin of product is hidden at injection point 49 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Bridging Java EE resources ●くろまる Use producer field to expose Java EE resource @Stateless public class UserEntityManagerProducer { @Produces @UserRepository @PersistenceContext(unitName = "users") EntityManager em; } @Stateless public class PricesTopicProducer { @Produces @Prices @Resource(name = "java:global/env/jms/Prices") Topic pricesTopic; } 50 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Injecting resources in type-safe way ●くろまる String-based resource names are hidden public class UserManager { @Inject @UserRepository EntityManager userEm; ... } public class StockDisplay { @Inject @Prices Topic pricesTopic; ... } 51 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Rethinking interceptors @Interceptors( SecurityInterceptor.class, TransactionInterceptor.class, LoggingInterceptor.class ) @Stateful public class BusinessComponent { ... } Um, what's the point? 52 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Define an interceptor binding type @InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface Secure {} 53 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Mark the interceptor implementation @Secure @Interceptor public class SecurityInterceptor { @AroundInvoke public Object aroundInvoke(InvocationContext ctx) throws Exception { // enforce security... ctx.proceed(); } } 54 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Interceptor wiring with proper semantics @Secure public class AccountManager { public boolean transfer(Account a, Account b) { ... } } 55 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Enabling and ordering interceptors ●くろまる Bean archive has no enabled interceptors by default ●くろまる Interceptors activated in beans.xml of bean archive ●くろまる Referenced by binding type ●くろまる Ordering is per-module ●くろまる Declared in module in which the interceptor is used <beans> <interceptors> <class>com.acme.SecurityInterceptor</class> <class>com.acme.TransactionInterceptor</class> </interceptors> </beans> Interceptors applied in order listed Interceptors applied in order listed 56 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Annotation jam! @Secure @Transactional @RequestScoped @Named public class AccountManager { public boolean transfer(Account a, Account b) { ... } } 57 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
stereotype n. an annotation used to group common architectural patterns (recurring roles) 58 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Define a stereotype to bundle annotations @Secure @Transactional @RequestScoped @Named @Stereotype @Retention(RUNTIME) @Target(TYPE) public @interface BusinessComponent {} 59 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Using a stereotype @BusinessComponent public class AccountManager { public boolean transfer(Account a, Account b) { ... } } 60 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Portable extensions ●くろまる SPI – Service Provider Interface ●くろまる Automatically discovered ●くろまる Application-scoped instance ●くろまる Observes events from CDI event bus ●くろまる Before/after bean discovery ●くろまる After deployment validation ●くろまる etc... ●くろまる Can override, augment, replace or veto beans 61 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
62 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Weld: JSR-299 Reference Implementation ●くろまる Implementation & TCK ●くろまる Weld (portable) extensions ●くろまる Apache software licensed (version 2.0) 63 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
64 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Seam’s mission statement To provide a fully integrated development platform for building rich Internet applications based upon the Java EE environment. 65 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Seam’s new modular ecosystem 66 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Portable modules ●くろまる Module per domain or integration ●くろまる Independently... ●くろまる lead ●くろまる versioned ●くろまる released ●くろまる Per-module structure ●くろまる Based on CDI ●くろまる API & implementation ●くろまる Reference documentation & examples 67 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Stack releases 68 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
What's on the menu so far? ●くろまる Drools ●くろまる JavaScript remoting ●くろまる jBPM ●くろまる Security ●くろまる JMS ●くろまる Servlet ●くろまる Faces ●くろまる Wicket ●くろまる International ●くろまる XML configuration ●くろまる Persistence ●くろまる Exception handling ...and more http://github.com/seam 69 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
XML-based configuration <beans ... xmlns:app="java:urn:com.acme"> <app:TranslatingWelcome> <app:Translating/> <app:defaultLocale>en-US</app:defaultLocale> </app:TranslatingWelcome> </beans> ●くろまる Define, specialize or override beans ●くろまる Add annotations (qualifiers, interceptor bindings, ...) ●くろまる Assign initial property values 70 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Cross-field validator in Seam Faces @FacesValidator("addressValidator") public class AddressValidator implements Validator { @Inject Directory directory; @Inject @InputField String city; @Inject @InputField String state; @Inject @InputField ZipCode zip; public void validate(FacesContext ctx, UIComponent c, Object v) throws ValidatorException { if (!directory.exists(city, state, zip) { throw new ValidatorException("Bad address"); } } } 71 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Wiring the validator to the inputs <h:form id="address"> City: <h:inputText id="city" value="#{bean.city}"/> State: <h:inputText id="state" value="#{bean.state}"/> Zip: <h:inputText id="zipCode" value="#{bean.zip}"/> <h:commandButton value="Update" action="#{addressController.update}"/> <s:validateForm validatorId="addressValidator" fields="zip=zipCode"> </h:form> 72 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Arquillian: Container-oriented testing for Java EE Throwing complexity over the wall Throwing complexity over the wall @RunWith(Arquillian.class) Wed @ 4:45 Wed @ 4:45 public class GreeterTestCase { Hilton, Golden Gate 4/5 Hilton, Golden Gate 4/5 @Deployment public static Archive<?> createDeployment() { return ShrinkWrap.create(JavaArchive.class) .addClasses(Greeter.class, GreeterBean.class); } @EJB private Greeter greeter; @Test public void shouldBeAbleToInvokeEJB() throws Exception { assertEquals("Hello, Earthlings", greeter.greet("Earthlings")); } } 73 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Summary ●くろまる Java EE 6 is leaner and more productive ●くろまる JSR-299 (CDI) provides a set of services for Java EE ●くろまる Bridges JSF and EJB ●くろまる Offers loose coupling with strong typing ●くろまる Provides a type-based event bus ●くろまる Catalyzed managed bean & interceptor specifications ●くろまる Extensive SPI for third-party integration with Java EE ●くろまる Weld: JSR-299 reference implementation & add-ons ●くろまる Seam 3: Portable extensions for Java EE 74 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
How do I get started? ●くろまる Download a Java EE 6 container ●くろまる JBoss AS 6 – http://jboss.org/jbossas ●くろまる GlassFish V3 – http://glassfish.org ●くろまる Generate a Java EE project using a Maven archetype ●くろまる http://tinyurl.com/goweld ●くろまる Read the Weld reference guide ●くろまる http://tinyurl.com/weld-reference-101 ●くろまる Browse the CDI JavaDoc ●くろまる http://docs.jboss.org/cdi/api/latest/ ●くろまる Check out the Seam 3 project ●くろまる http://seamframework.org/Seam3 75 JSR-299 (CDI), Weld and the Future of Seam | Dan Allen
Q&A Dan Allen Principal Software Engineer JBoss by Red Hat http://seamframework.org/Weld http://seamframework.org/Seam3