<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Antonio's Blog</title>
	
	<link>http://agoncal.wordpress.com</link>
	<description>A blog mainly about Java</description>
	<lastBuildDate>Thu, 02 Feb 2012 18:28:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain="agoncal.wordpress.com" port="80" path="/?rsscloud=notify" registerProcedure="" protocol="http-post" />
<image>
		<url>http://1.gravatar.com/blavatar/5dd5107518dc70737e9e52b02a1d369a?s=96&amp;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Antonio's Blog</title>
		<link>http://agoncal.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://agoncal.wordpress.com/osd.xml" title="Antonio's Blog" />
	
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/AntonioGoncalves" /><feedburner:info uri="antoniogoncalves" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://agoncal.wordpress.com/?pushpress=hub" /><feedburner:browserFriendly></feedburner:browserFriendly><item>
		<title>WYTIWYR : What You Test Is What You Run</title>
		<link>http://agoncal.wordpress.com/2012/01/16/wytiwyr-what-you-test-is-what-you-run/</link>
		<comments>http://agoncal.wordpress.com/2012/01/16/wytiwyr-what-you-test-is-what-you-run/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 14:58:04 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[arquillian]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[java ee 6]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1291</guid>
		<description><![CDATA[I&#8217;m fed up with unit testing ! It&#8217;s 2012 and my first resolution of the year is to finally tell the truth about testing : unit testing is pretty much useless when your code runs inside a container. How do you unit test an EJB which relies on the container services (i.e transaction, injection, security&#8230;) ? [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1291&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/agoncal/agoncal-sample-arquilian/tree/master/01-wytiwyr"><img class="size-full wp-image-652 alignright" title="Download the code" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a><strong>I&#8217;m fed up with unit testing !</strong></p>
<p>It&#8217;s 2012 and my first resolution of the year is to finally tell the truth about testing : <strong><a href="http://en.wikipedia.org/wiki/Unit_testing">unit testing</a> is pretty much useless when your code runs inside a container</strong>. How do you unit test an EJB which relies on the container services (i.e transaction, injection, security&#8230;) ? Well, you mock the database access, you mock your security layer, you mock your dependencies, you mock your validation layer&#8230; to test what ? A bit of business logic. Yes. Unit test is interesting when you have complex business logic to test so you can have quick feedback. Otherwise, it&#8217;s a waste of time which doesn&#8217;t test your container services. So I&#8217;m not saying unit testing is completely useless, I&#8217;m saying that<strong> <a href="http://en.wikipedia.org/wiki/Integration_testing">integration testing</a> is also to be considered when you run your code inside a Java EE container</strong>.</p>
<p>In this post I&#8217;ll show you how to unit test an EJB with <a href="http://code.google.com/p/mockito/">Mockito</a> and how to do <strong>integration test with and without <a href="http://www.jboss.org/arquillian">Arquillian</a></strong>.</p>
<h1>Use case</h1>
<p>So let&#8217;s take a simple use case (but of course, in real life it&#8217;s more complex) : I have a <tt>Book</tt> entity with a complex named query (well, sort of) and an EJB that queries the entity (CRUD operations + calling the named query). Because my JPQL query is complex and I have a bug in production, I want to reproduce the bug and correct the JPQL query. Because I like Java EE 6 and CDI I use extensively some artifacts that need to be injected (such as a <tt>Logger</tt>, <tt>DataSourceDefinition</tt> and so on).</p>
<p><a href="http://agoncal.files.wordpress.com/2012/01/classdiag.png"><img class="aligncenter size-full wp-image-1328" title="Class diagram" src="http://agoncal.files.wordpress.com/2012/01/classdiag.png?w=468&#038;h=211" alt="" width="468" height="211" /></a></p>
<p>As you can see in the class diagram, I have the following classes :</p>
<ul>
<li><tt>ItemEJB</tt> : a stateless EJB with a <tt>@Path</tt> annotation to add REST services. It manipulates the <tt>Book</tt> entity.</li>
<li><tt>Book</tt> : entity with JPA annotation for persistence and query as well as JAXB annotations for XML marshaling.</li>
<li><tt>IsbnGenerator</tt> : CDI bean that generates an ISBN number for the book.</li>
<li><tt>DatabasePopulator</tt> : startup singleton that persists a few books into the database.</li>
<li><tt>ApplicationConfig</tt> : helper class annotated with <tt>@ApplicationPath</tt> to declare all REST services under the <tt>/rs</tt> URL.</li>
<li><tt>DatabaseResource</tt> : produces an injectable <tt>EntityManager</tt>.</li>
<li><tt>LogResource</tt> : produces an injectable logger.</li>
</ul>
<h2>The Book entity</h2>
<p>The <tt>Book</tt> entity is pretty simple but some things have to be highlighted :</p>
<p><pre class="brush: java; highlight: [3,9,11];">
@Entity
@NamedQueries({
@NamedQuery(name = Book.FIND_ALL_SCIFI, query = &quot;SELECT b FROM Book b WHERE 'scifi' member of b.tags ORDER BY b.id DESC&quot;)
})
public class Book {

  public static final String FIND_ALL_SCIFI = &quot;Book.findAllScifiBooks&quot;;

  @Id @GeneratedValue
  private Long id;
  @NotNull
  private String title;
  private Float price;
  private String description;
  private String isbn;
  @ElementCollection
  private List tags = new ArrayList();
  ..
</pre></p>
<p>This entity has a named query which retreives all the scifi books from the database and I need to test it (this query is pretty simple but imagine an harder one). The JPA provider will generate an id automatically thanks to <tt>@GeneratedValue</tt>. The integration between JPA with Bean Validation will make sure I cannot insert a <tt>Book</tt> with a null title (thanks to <tt>@NotNull</tt>). These services have to be mocked in unit testing (not in integration test as you will see).</p>
<h2>The ItemEJB</h2>
<p>The ItemEJB is a Stateless EJB with REST capabilites doing CRUD operations and invoking the entity named query :</p>
<p><pre class="brush: java; highlight: [1,5,11];">
@Stateless
public class ItemEJB {

  @Inject
  private EntityManager em;

  @Inject
  private IsbnGenerator numberGenerator;

  @Inject
  private Logger logger;

  public Book createBook(Book book) {
    book.setIsbn(numberGenerator.generateNumber());
    em.persist(book);
    return book;
  }

  public void removeBook(Book book) {
    em.remove(em.merge(book));
  }

  public List findAllScifiBooks() {
    logger.info(&quot;###### findAllScifiBooks &quot;);
    return em.createNamedQuery(Book.FIND_ALL_SCIFI, Book.class).getResultList();
  }
  ...
}
</pre></p>
<p>This POJO uses several services from the container. First of all, every method is transactional (without any extra boiler plate code, just because it&#8217;s annotated with <tt>@Stateless</tt>). Then, this EJB gets injected an <tt>EntityManager</tt> that has been produced (see below), a helper class (the <tt>IsbnGenerator</tt> POJO) and a logger (I&#8217;ll use the good old <tt>java.util.logging</tt> so my code doesn&#8217;t have external dependencies). Again, these services will have to be mocked in unit testing.</p>
<h2>DataSource</h2>
<p>I need a datasource to access a database. Because I want to do some testing, Derby in-memory database will do. And because I&#8217;m pretty lazy and don&#8217;t want to create a datasource inside my container using the admin console, I use the <tt><a href="http://docs.oracle.com/javaee/6/api/javax/annotation/sql/DataSourceDefinition.html">@DataSourceDefinition</a></tt> annotation to make my life easier :</p>
<p><pre class="brush: java; highlight: [1,7];">
@DataSourceDefinition(name = &quot;java:app/jdbc/sampleArquilianWytiwyrDS&quot;,
className = &quot;org.apache.derby.jdbc.EmbeddedDriver&quot;,
url = &quot;jdbc:derby:memory:sampleArquilianWytiwyrDB;create=true;user=app;password=app&quot;
)
public class DatabaseResource {

  @Produces
  @PersistenceContext(unitName = &quot;sampleArquilianWytiwyrPU&quot;)
  private EntityManager em;
}
</pre></p>
<p>As you can see I produce my <tt>EntityManager</tt> so it can be injected with <tt>@Inject</tt>. In unit testing this class is pretty much useless as no datasource can be used and injection as to be mocked.</p>
<h1>Testing scenario</h1>
<p>As I said, I want to test a complex scenario with all the container services available (so this is not unit testing per se). Here is the scenario :</p>
<ul>
<li>I get all the scifi books from the database (using the named query that looks for the <em>scifi</em> tag)</li>
<li>I persist three books : one that fills the query, another one that doesn&#8217;t and a third one that has a null title which will not get persisted (due to Bean Validation <tt>ConstraintViolationException</tt>)</li>
<li>I get all the scifi books from the database again and make sure there is an extra one</li>
<li>I remove all the entities from the database</li>
<li>I get all the scifi books from the database again and make sure we have the initial number of books</li>
</ul>
<h1>Implementing the scenario with unit testing</h1>
<div>I&#8217;m going to say this again to make sure I don&#8217;t receive thousands of emails from unit testing fanatics : the scenario described above is not a unit test, but I want to show how you can unit test your EJB with Mockito (and how painful and useless it is). So let&#8217;s go, I&#8217;ll start with the code and explain it later :</div>
<div><pre class="brush: java; highlight: [4,12,19];">
@RunWith(MockitoJUnitRunner.class)
public class ItemEJBTest {

  @Mock
  private EntityManager mockedEntityManager;
  @Mock
  private TypedQuery mockedQuery;
  private ItemEJB itemEJB;

  @Before
  public void initDependencies() throws Exception {
    itemEJB = new ItemEJB();
    itemEJB.setEntityManager(mockedEntityManager);
    itemEJB.setNumberGenerator(new IsbnGenerator());
    itemEJB.setLogger(Logger.getLogger(ItemEJB.class.getName()));
  }

  @Test
  public void shouldFindAllScifiBooks() throws Exception {

    List books = new ArrayList();

    // Finds all the scifi books
    when(mockedEntityManager.createNamedQuery(Book.FIND_ALL_SCIFI, Book.class)).thenReturn(mockedQuery);
    when(mockedQuery.getResultList()).thenReturn(books);
    int initialNumberOfScifiBooks = itemEJB.findAllScifiBooks().size();

    // Creates the books
    Book scifiBook = new Book(&quot;Scifi book&quot;, 12.5f, &quot;Should fill the query&quot;, 345, false, &quot;English&quot;, &quot;scifi&quot;);
    Book itBook = new Book(&quot;Non scifi book&quot;, 42.5f, &quot;Should not fill the query&quot;, 457, false, &quot;English&quot;, &quot;it&quot;);
    Book nullBook = new Book(null, 12.5f, &quot;Null title should fail&quot;, 457, true, &quot;English&quot;, &quot;scifi&quot;);

    // Persists the books
    itemEJB.createBook(scifiBook);
    itemEJB.createBook(itBook);
    verify(mockedEntityManager, times(2)).persist(any());

    try {
      doThrow(ConstraintViolationException.class).when(mockedEntityManager).persist(nullBook);
      itemEJB.createBook(nullBook);
      fail(&quot;should not persist a book with a null title&quot;);
    } catch (ConstraintViolationException e) {
    }

    // Finds all the scifi books again and make sure there is an extra one
    books.add(scifiBook);
    when(mockedQuery.getResultList()).thenReturn(books);
    assertEquals(&quot;Should have one extra scifi book&quot;, initialNumberOfScifiBooks + 1, itemEJB.findAllScifiBoks().size());

    // Deletes the books
    itemEJB.removeBook(scifiBook);
    itemEJB.removeBook(itBook);
    verify(mockedEntityManager, times(2)).remove(any());

    // Finds all the scifi books again and make sure we have the same initial numbers
    books = new ArrayList();
    when(mockedQuery.getResultList()).thenReturn(books);
    assertEquals(&quot;Should have initial number of scifi books&quot;, initialNumberOfScifiBooks, itemEJB.findAllScifiBooks().size());
  }
}
</pre></p>
<p>Some explanation :</p>
<ul>
<li>line number 4 and 6 : thanks to <tt>@RunWith(MockitoJUnitRunner.class)</tt>, I&#8217;m mocking the database access by mocking my <tt>EntityManager</tt> and <tt>TypedQuery</tt> with the <tt>@Mock</tt> annotation</li>
<li> line number 12 :  in the <tt>initDependencies</tt> method that&#8217;s where we lose all the container services : we do a new of the <tt>ItemEJB</tt> (<tt>itemEJB = new ItemEJB()</tt>) instead of injecting or lookingup the EJB. Instanciating <tt>ItemEJB</tt> is not seen by the container, so it&#8217;s just a POJO without any container services. And because we run in isolation, we have to manually mock or instanciate the dependencies using setters (<tt>setEntityManager</tt>, <tt>setNumberGenerator</tt> and <tt>setLogger</tt>).</li>
<li>line number 19 : <tt>shouldFindAllScifiBooks</tt> implements our testing scenario. As you can see, I use an <tt>ArrayList</tt> to add my books and Mockito returns this list (instead of the query result). I then persist my books (<tt>verify(mockedEntityManager, times(2)).persist(any())</tt>) and I want to make sure I get a <tt>ConstraintViolationException</tt> when persisting a book with a null title (that why I have <tt>doThrow(ConstraintViolationException.class).when(mockedEntityManager).persist(nullBook)</tt>). To test that my query returns an extra book I just add the object to the list (<tt>books.add(scifiBook)</tt>) and remove it afterwards (<tt>books.remove(scifiBook)</tt>).</li>
</ul>
<p>As you can see, I haven&#8217;t tested my JPQL query, the code is not that nice, and I have to do many Mockito tricks to simulate what I want. <a href="http://www.mockobjects.com/2007/04/test-smell-everything-is-mocked.html">Isn&#8217;t that a test smell</a> ? <a href="http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/">A Mockery</a> ? <strong>We shouldn&#8217;t mock third-party libraries</strong>. So let&#8217;s do integration tests.</p>
<h1>Implementing the scenario with integration testing</h1>
</div>
<p>I can hear you saying &#8220;<strong>Integration test in Java EE is difficult, don&#8217;t do that</strong>&#8220;. This was true in the past but not anymore. Integration testing use to be nearly impossible, that&#8217;s why we had no choice but unit test and mock all the services. But <strong>today, thanks to Java EE 6, we can easily do integration testing</strong>. How ? By using standard (and some time non standard) APIs or testing frameworks such as <a href="http://www.jboss.org/arquillian">Arquillian</a> :</p>
<ul>
<li><tt>EJBContainer.createEJBContainer()</tt> : creates an in-memory EJB container where you can deploy and use your EJB</li>
<li><tt>Persistence.createEntityManagerFactory()</tt> : creates a JPA provider so you can manipulate entities</li>
<li><tt>Validation.buildDefaultValidatorFactory()</tt> : gets a validator to validate your beans</li>
<li><tt>ActiveMQConnectionFactory</tt> : creates an in-memory JMS broker (non-standard)</li>
<li><tt>ServletTester</tt> : Jetty helper class to test your servlets and web services in-memory (non-standard, I whish we had a standard <tt>WebContainer</tt> API like in EJBs)</li>
</ul>
<h2>Without Arquillian (i.e EJBContainer)</h2>
<p>Let&#8217;s start with the simplest standard integration test for an EJB : using the <tt>javax.ejb.embeddable.EJBContainer</tt> API. This <a href="http://docs.oracle.com/javaee/6/api/javax/ejb/embeddable/EJBContainer.html">API</a> was created in <a href="http://jcp.org/en/jsr/summary?id=318">EJB 3.1</a> and is used to execute an EJB application in an embeddable container (in a standard way). Here is the code of our scenarion with the EJBContainer (BTW I&#8217;m using <a href="http://glassfish.java.net/">GlassFish 3.1</a> as the implementation) :</p>
<p><pre class="brush: java; highlight: [3,7,15,22,26,43];">
public class ItemEJBWithoutArquillianIT {

    private static EJBContainer ec;
    private static Context ctx;

    @BeforeClass
    public static void initContainer() throws Exception {
        Map properties = new HashMap();
        properties.put(EJBContainer.MODULES, new File[]{new File(&quot;target/classes&quot;), new File(&quot;target/test-classes&quot;)});
        ec = EJBContainer.createEJBContainer(properties);
        ctx = ec.getContext();
    }

    @AfterClass
    public static void closeContainer() throws Exception {
        if (ec != null) {
            ec.close();
        }
    }

    @Test
    public void shouldFindAllScifiBooks() throws Exception {

        // Check JNDI dependencies
        assertNotNull(ctx.lookup(&quot;java:global/classes/ItemEJB&quot;));
        assertNotNull(ctx.lookup(&quot;java:global/jdbc/sampleArquilianWytiwyrDS&quot;));

        // Looks up for the EJB
        ItemEJB itemEJB = (ItemEJB) ctx.lookup(&quot;java:global/classes/ItemEJB&quot;);

        // Finds all the scifi books
        int initialNumberOfScifiBooks = itemEJB.findAllScifiBooks().size();

        // Creates the books
        Book scifiBook = new Book(&quot;Scifi book&quot;, 12.5f, &quot;Should fill the query&quot;, 345, false, &quot;English&quot;, &quot;scifi&quot;);
        Book itBook = new Book(&quot;Non scifi book&quot;, 42.5f, &quot;Should not fill the query&quot;, 457, false, &quot;English&quot;, &quot;it&quot;);
        Book nullBook = new Book(null, 12.5f, &quot;Null title should fail&quot;, 457, true, &quot;English&quot;, &quot;scifi&quot;);

        // Persists the books
        itemEJB.createBook(scifiBook);
        itemEJB.createBook(itBook);
        try {
            itemEJB.createBook(nullBook);
            fail(&quot;should not persist a book with a null title&quot;);
        } catch (Exception e) {
            assertTrue(e.getCause() instanceof ConstraintViolationException);
        }

        // Finds all the scifi books again and make sure there is an extra one
        assertEquals(&quot;Should have one extra scifi book&quot;, initialNumberOfScifiBooks + 1, itemEJB.findAllScifiBooks().size());

        // Deletes the books
        itemEJB.removeBook(scifiBook);
        itemEJB.removeBook(itBook);

        // Finds all the scifi books again and make sure we have the same initial numbers
        assertEquals(&quot;Should have initial number of scifi books&quot;, initialNumberOfScifiBooks, itemEJB.findAllScifiBooks().size());
    }
}
</pre></p>
<p>Some explanation :</p>
<ul>
<li>line number 7 : here I create my embedded EJB container and get the JNDI context. As you can see, I don&#8217;t have to mock anything (<tt>EntityManager</tt>, injection and so on) because from now on my code will be running in an embedded container (which is the same container that you will be running in production, but in runtime mode instead of in-memory)</li>
<li>line number 15 : closes the EJB container once the test is passed</li>
<li>line number 22 : in this method I implement our testing scenario, with no mocks. I lookup my EJB using JNDI and invoke the needed methods (<tt>findAllScifiBooks</tt>, <tt>createBook</tt> and <tt>removeBook</tt>) which will be intercepted by the container that will give me all the services (transactions, injection, lifecycle&#8230;)</li>
<li>line number 26 : because I&#8217;m running inside a container, I can even lookup my datasource (because it has been deployed thanks to <tt>@DataSourceDefinition</tt></li>
<li>line number 43 : if I persist a book with a null title, Bean Validation will throw a constraint violation (a real one, I don&#8217;t have to mock it)</li>
</ul>
<h2>With Arquillian</h2>
<p><a href="http://www.jboss.org/arquillian">Arquillian</a> is a JBoss project that can execute test cases inside a container (embedded, local or remote). And when I say a container, it can run the same test in several ones (GlassFish, JBoss&#8230;). In my case I&#8217;m using GlassFish, so as you can see, Arquillian is not stuck to JBoss. I will write about multiple server deployment later, but for now, let&#8217;s see how an integration test with Arquillian differs from one with the <tt>EJBContainer</tt> API :</p>
<p><pre class="brush: java; highlight: [1,4,8,17];">
@RunWith(Arquillian.class)
public class ItemEJBWithArquillianIT {

    @Inject
    private ItemEJB itemEJB;

    @Deployment
    public static JavaArchive createTestArchive() {
        JavaArchive archive = ShrinkWrap.create(JavaArchive.class)
                .addPackage(Book.class.getPackage())
                .addAsManifestResource(EmptyAsset.INSTANCE, &quot;beans.xml&quot;)
                .addAsResource(&quot;META-INF/persistence.xml&quot;, &quot;META-INF/persistence.xml&quot;);
        return archive;
    }

    @Test
    public void shouldFindAllScifiBooks() throws Exception {

        // Check JNDI dependencies
        Context ctx = new InitialContext();
        assertNotNull(ctx.lookup(&quot;java:global/jdbc/sampleArquilianWytiwyrDS&quot;));

        // Finds all the scifi books
        int initialNumberOfScifiBooks = itemEJB.findAllScifiBooks().size();

        // Creates the books
        Book scifiBook = new Book(&quot;Scifi book&quot;, 12.5f, &quot;Should fill the query&quot;, 345, false, &quot;English&quot;, &quot;scifi&quot;);
        Book itBook = new Book(&quot;Non scifi book&quot;, 42.5f, &quot;Should not fill the query&quot;, 457, false, &quot;English&quot;, &quot;it&quot;);
        Book nullBook = new Book(null, 12.5f, &quot;Null title should fail&quot;, 457, true, &quot;English&quot;, &quot;scifi&quot;);

        // Persists the books
        itemEJB.createBook(scifiBook);
        itemEJB.createBook(itBook);
        try {
            itemEJB.createBook(nullBook);
            fail(&quot;should not persist a book with a null title&quot;);
        } catch (Exception e) {
            assertTrue(e.getCause() instanceof ConstraintViolationException);
        }

        // Finds all the scifi books again and make sure there is an extra one
        assertEquals(&quot;Should have one extra scifi book&quot;, initialNumberOfScifiBooks + 1, itemEJB.findAllScifiBooks().size());

        // Deletes the books
        itemEJB.removeBook(scifiBook);
        itemEJB.removeBook(itBook);

        // Finds all the scifi books again and make sure we have the same initial numbers
        assertEquals(&quot;Should have initial number of scifi books&quot;, initialNumberOfScifiBooks, itemEJB.findAllScifiBooks().size());
    }
}
</pre></p>
<p>Some explanation :</p>
<ul>
<li>line number 4 : thanks to Arquillian, I can inject a reference of my EJB instead of looking it up. My test runs inside the container, so I can use the injection service of this container</li>
<li>line number 8 : the createTestArchive method uses <a href="http://www.jboss.org/shrinkwrap">ShrinkWrap</a> to create an archive which will then be deployed by Arquillian in the container</li>
<li>line number 17 : the code of the integration test is nearly the same as the one we say before</li>
</ul>
<div>In this example it&#8217;s difficult to see the benefit of Arquillian as both test classes (with <tt>EJBContainer</tt> and with Arquillian) are similar. Arquillian is not standard, the <tt>EJBContainer</tt> API is. But I&#8217;ll spend more blogs explaining you the benefit in the long run.</div>
<h1>Some metrics</h1>
<p>Ok, some metrics now. How much does it cost to run a unit test vs integration tests ? I measured each of these tests (on my fantastic Mac Book Pro &#8211; i7 &#8211; 8Gb RAM &#8211; SSD drive) and here is the execution time :</p>
<ul>
<li>unit testing : <strong>195 milliseconds</strong> to run</li>
<li>integration test <strong>without</strong> Arquillian : <strong>5.3 seconds</strong> (that&#8217;s <strong>27 times slower</strong> than unit testing)</li>
<li>integration test <strong>with</strong> Arquillian : <strong>6.1 seconds</strong> (that&#8217;s <strong>31 times slower</strong> than unit testing)</li>
</ul>
<div>As you can see, <strong>unit testing is by far much faster to execute</strong>. Unit testing gives you a quick feedback and you can really develop and test continuously. It&#8217;s still time consuming to do with integration test.</div>
<h1>Conclusion</h1>
<p><a href="https://github.com/agoncal/agoncal-sample-arquilian/tree/master/01-wytiwyr"><img class="alignright size-full wp-image-652" title="Download the code" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a>There is unit testing and integration testing. <strong>Historically integration testing was pretty much impossible in Java EE</strong> and you had to do many different tricks. That&#8217;s why we used extensively unit testing and <a href="http://www.markhneedham.com/blog/2009/12/13/tdd-only-mock-types-you-own/">mocked even objects that we don&#8217;t owe</a> (like the <tt>EntityManager</tt>). But since Java EE 6, thanks to all our container factories (<tt>EJBContainer</tt>, <tt>EntityManagerFactory</tt>, <tt>ValidatorFactory</tt>&#8230;) we can now easily use these container and their services in an embedded mode. <strong>Unit testing is good to test business code</strong> or code in isolation (mocking external components) but we have to remember that we have <strong>easy integration testing</strong> now and we should use it to test code interacting with external components or services.</p>
<p>But the world is not perfect&#8230; yet. The big advantage of unit testing is the quick feedback because unit tests run faster. But, because you are mocking so many services, you don&#8217;t have a clue how your code will behave in production. Integration test uses the container and the container services, so you know that <strong>What You Test Is What You Run</strong>.</p>
<p>I little bit of hope now. A few month ago I wrote a (long) post about <a title="O Java EE 6 Application Servers, Where Art Thou?" href="http://agoncal.wordpress.com/2011/10/20/o-java-ee-6-application-servers-where-art-thou/">startup time of most of the Java EE 6 application servers</a>. <strong>Most of the application servers startup in less than 4 seconds</strong>. If you look at the application servers history, that is a huge improvment in the last years. Same thing will happen with embedded containers and integration test framework such as Arquillian : they will get faster and faster, and soon, running your in-memory database and in-memory container will cost you little resources. <strong>Having fast integration tests that&#8217;s what we want !</strong></p>
<h2>Thanks</h2>
<p>I would like to thank <a href="http://blog.arkey.fr/">Brice Duteil</a>, a Mockito committer who gave me some advices on Mockito.</p>
<h2>References</h2>
<ul>
<li><a href="http://www.davesquared.net/2011/04/dont-mock-types-you-dont-own.html">Don&#8217;t mock types you don&#8217;t own</a></li>
<li><a href="http://www.markhneedham.com/blog/2009/12/13/tdd-only-mock-types-you-own">TDD: Only mock types you own</a></li>
<li><a href="http://www.mockobjects.com/2007/04/test-smell-everything-is-mocked.html">Test Smell: Everything is mocked</a></li>
<li><a href="http://jasonrudolph.com/blog/testing-anti-patterns-how-to-fail-with-100-test-coverage/">Testing Anti-Patterns: How to Fail With 100% Test Coverage</a></li>
<li><a href="http://www.markhneedham.com/blog/2009/12/13/tdd-only-mock-types-you-own/">TDD: Only mock types you own</a></li>
<li><a href="http://www.mockobjects.com/2007/04/test-smell-everything-is-mocked.html">Test Smell: Everything is mocked</a></li>
<li><a href="http://www.jboss.org/arquillian">Arquillian</a></li>
<li><a href="http://www.jboss.org/shrinkwrap">ShrinkWrap</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1291/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1291/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1291/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1291/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1291/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1291/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1291/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1291&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2012/01/16/wytiwyr-what-you-test-is-what-you-run/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">Download the code</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2012/01/classdiag.png" medium="image">
			<media:title type="html">Class diagram</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">Download the code</media:title>
		</media:content>
	</item>
		<item>
		<title>O Java EE 6 Application Servers, Where Art Thou?</title>
		<link>http://agoncal.wordpress.com/2011/10/20/o-java-ee-6-application-servers-where-art-thou/</link>
		<comments>http://agoncal.wordpress.com/2011/10/20/o-java-ee-6-application-servers-where-art-thou/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 13:34:49 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[geronimo]]></category>
		<category><![CDATA[glassfish]]></category>
		<category><![CDATA[java ee 6]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[jeus]]></category>
		<category><![CDATA[jonas]]></category>
		<category><![CDATA[resin]]></category>
		<category><![CDATA[siwpas]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[tomee]]></category>
		<category><![CDATA[was]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1185</guid>
		<description><![CDATA[Nearly two years ago (time flies), when Java EE 6 came out, I wrote a post about application servers where I did some micro benchmarking (basically, startup time). I had plenty of comments and recently I had many people asking for some updates. Witht Java EE 6 booming, with some cloud vendors moving to Java [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1185&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Nearly two years ago (time flies), when Java EE 6 came out, <a title="O Application Servers, Where Art Thou?" href="http://agoncal.wordpress.com/2009/12/12/o-application-servers-where-art-thou/">I wrote a post about application servers</a> where I did some micro benchmarking (basically, startup time). I had plenty of comments and recently I had many people asking for some updates. Witht Java EE 6 booming, <a href="http://blog.cloudbees.com/2011/09/java-ee6-in-cloud-in-production-today.html">with some cloud vendors moving to Java EE 6</a>, it was time to update this microbenchmark and focus on Java EE 6 application servers. BTW, if you want to know what Java EE 6 is, you can <a href="http://www.slideshare.net/agoncal/whats-new-in-java-ee-6-9554370">check the slides of a presentation</a>I gave a few times.</p>
<h1>The benchmark</h1>
<p>Same disclaimer as last time : <em>This is not a real benchmark !</em> so I&#8217;ll copy paste the paragraph <a title="O Application Servers, Where Art Thou?" href="http://agoncal.wordpress.com/2009/12/12/o-application-servers-where-art-thou/">I wrote last time</a> :</p>
<p>In this test I’m just concerned about the usability of an application server for a developer. The idea is to download it, install it, start it and take some measurements : <strong>size of download, ease of installation, size of disk, startup time, size of RAM..</strong>. That’s all. No deployment of an application, no fancy twists to gain performance&#8230; Because some of these application servers are resource consuming, I’m doing all my tests on a Windows XP SP3 virtual machine (running on Virtual Box 4.1). It is a fresh install of Windows XP sp3 with 1Gb of RAM and not too many software installed. So when I boot there are 27 processes running and using 230 Mb of RAM (leaving 770 Mb free). Virtualizing can be slower, so keep in mind that startup time can be a bit faster that what I’m giving you here. I use <strong>JDK 1.6.0_27</strong> (when it’s not bundled with the server). No optimization at all is made (I haven’t twisted the JVM, or antyhing application server parameter, everything comes out of the box).</p>
<p>To calculate the startup time, I don’t do any fancy rocket science either. <strong>I just start the server a few times, check how long it takes and use the best startup time</strong>. Also remember that some servers do not load any container at startup, making them very fast to start. That&#8217;s why I first trigger the web admin console (when there&#8217;s one) so I&#8217;m sure at least one web application is deployed (I did a print screen of the admin console when there&#8217;s one). Then I just stop and start the server a few times and get the best startup time (by reading the logs). To calculate the memory footprint, I just use the Windows task manager and check the size of the java.exe process.</p>
<h1>Which application servers ?</h1>
<p>If you look at the <a href="http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html">Java EE Compatibility page at Oracle</a>, you&#8217;ll see that there are a bunch of application servers that actually have passed the Java E E6 TCK (<a href="http://www.sun.com/software/products/glassfishv3/">Oracle GlassFish Server 3.1.1</a>, <a href="http://www.caucho.com/resin/">Caucho Resin 4.0.17</a>, <a href="http://www.jboss.org/jbossas/downloads.html">JBoss Application Server 7</a>, <a href="http://openejb.apache.org/downloads.html">Apache TomEE 1.0.0-beta-1</a>,  <a href="http://www.tmax.co.kr/tmax_en/jeus">TMAX JEUS 7</a>, <a href="http://www-01.ibm.com/software/webservers/appserv/was/">IBM WebSphere Application Server 8.0</a>, <a href="http://www.fujitsu.com/global/services/software/interstage/">Fujitsu Interstage Application Server</a>) and some still haven&#8217;t (<a href="http://geronimo.apache.org/apache-geronimo-v30-m1-release.html">Geronimo 3</a>, <a href="http://wiki.jonas.ow2.org/xwiki/bin/view/Main/Downloads">JOnAS 5.3</a>, <a href="http://siwpas.mechsoft.com.tr/">Siwpas</a>). On this list some application servers implement the full Java EE 6 and others just implement the Web Profile 1.0.</p>
<h2>GlassFish 3.1.1</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/glassfish.png" target="_blank"><img class="alignright size-thumbnail wp-image-1201" title="GlassFish admin console" src="http://agoncal.files.wordpress.com/2011/10/glassfish.png?w=150&#038;h=99" alt="" width="150" height="99" /></a><a href="https://glassfish.dev.java.net">GlassFish 3</a> is the open source reference implementation for Java EE 6. The 3.1 release has added clustering capabilities. Being the reference implementation, GlassFish 3.x implements both Java EE 6 and the Web Profile 1.0, that&#8217;s why you have two different bundles you can download (one of 80.6 Mb and the other 45.8 Mb).</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>3.1.1</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Java EE 6 &amp; Web Profile 1.0</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.oracle.com">Oracle</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>Dual license CDDL and GPL</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://glassfish.java.net/docs/project.html">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://glassfish.java.net/downloads/3.1.1-final.html">Zipfile, executables</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>80.6 Mb (Java EE 6) 45.8 Mb (Web Profile)</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip or exe</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>96.1 Mb (Java EE 6) 57.8 Mb (Web Profile)</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute %GLASSFISH_HOME%\bin\asadmin start-domain</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%GLASSFISH_HOME%\domains\domain1\logs</td>
</tr>
<tr>
<td>Best startup time</td>
<td>2 953ms (Java EE 6) 1 914ms (Web Profile)</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>83 MB (Java EE 6) 69 MB (Web Profile)</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>Admin console</td>
<td>http://localhost:4848</td>
</tr>
</tbody>
</table>
<h2>Resin 4.0.23</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/resin.png" target="_blank"><img class="alignright size-thumbnail wp-image-1202" title="Resin admin console" src="http://agoncal.files.wordpress.com/2011/10/resin.png?w=150&#038;h=95" alt="" width="150" height="95" /></a><a href="http://caucho.com/resin-4.0/">Resin 4</a> was one of the first web server (such as Jetty or Tomcat) to move to the Web Profile 1.0. For me it&#8217;s the success story that confirmed that profiles in Java EE were needed. It&#8217;s really difficult to go from a Web Server to a full Java EE 6 application server (remember that there&#8217;s still Entity CMPs in EE 6) but much easier to implement the Web Profile. Resin is very CDI centric and based on the Caucho implementation called <a href="http://www.caucho.com/resin/candi/">CanDI</a>.</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>4.0.23</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Web Profile 1.0</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.caucho.com">Caucho</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>GPL License</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://www.caucho.com/documentation/">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://www.caucho.com/download/">Zip, tgz, deb</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>24.2 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip the file</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>32 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute %RESIN_HOME%\java -jar lib/resin.jar start</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%RESIN_HOME%\log</td>
</tr>
<tr>
<td>Best startup time</td>
<td>1 845ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>2 processes : 68.5 MB + 39 MB</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>Admin console</td>
<td>http://localhost:8080/resin-admin/</td>
</tr>
</tbody>
</table>
<h2>JBoss 7.0.2-Final</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/jboss.png" target="_blank"><img class="alignright size-thumbnail wp-image-1203" title="JBoss admin console" src="http://agoncal.files.wordpress.com/2011/10/jboss.png?w=150&#038;h=91" alt="" width="150" height="91" /></a>It looks like <a href="http://www.jboss.org/as7">JBoss 7</a> is, finally, a nice millésime. For those of you who waited so long for JBoss 5 to get certified and then didn&#8217;t see any JBoss 6, JBoss 7 is what you need with a fantastic startup time compared to the older versions (in my <a href="http://agoncal.wordpress.com/2009/12/12/o-application-servers-where-art-thou/">previous benchmard</a>JBoss 5 was the slowest app servers, slower than WebSphere 7). Another novelty is an admin console (sexier than the good old JMX Console).</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>7.0.2-Final</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Web Profile 1.0</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.jboss.org">JBoss/RedHat</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>LGPL</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://www.jboss.org/jbossas/docs/7-x">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://www.jboss.org/jbossas/downloads">Zipfile</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>70.7 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>77.9 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute %JBOSS_HOME%\bin\standalone</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%JBOSS_HOME%\standalone\log</td>
</tr>
<tr>
<td>Best startup time</td>
<td>2 782ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>70.7 MB</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>JMX console</td>
<td>http://localhost:9990/console</td>
</tr>
</tbody>
</table>
<h2>TomEE 1.0.0-beta-1</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/tomee.png" target="_blank"><img class="alignright size-thumbnail wp-image-1217" title="TomEE admin console" src="http://agoncal.files.wordpress.com/2011/10/tomee.png?w=150&#038;h=109" alt="" width="150" height="109" /></a>Like Resin, <a href="http://openejb.apache.org/3.0/apache-tomee.html">Apache TomEE</a>is the perfect success story for the Web Profile. TomEE is no more than Tomcat + OpenWebBeans + OpenEJB + OpenJPA + MyFaces + other bits. It really shows that Java EE is a jigsaw puzzle where you can take open standards, bundle them together and become a certified Web Profile application server.</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>1.0.0-beta-1</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Web Profile 1.0</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.apache.org/">Apache</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>Apache Software License</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://openejb.apache.org/3.0/index.html">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://openejb.apache.org/downloads.html">Zip, tar.gz</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>24.2 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip the file</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>29.2 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute %TOMEE_HOME%\bin\startup.bat</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%TOMEE_HOME%\logs</td>
</tr>
<tr>
<td>Best startup time</td>
<td>3 288ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>65 MB</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>Admin console (*)</td>
<td>http://localhost:8080/manager/html</td>
</tr>
</tbody>
</table>
<p>(*) Looks like to be able to log on to the admin console, you need to change the %TOMCAT_HOME%\conf\tomcat-users.xml configuration files and add a manager-script role to a user. <strong>But I couldn&#8217;t make it work</strong>.</p>
<h2>Geronimo v3.0-M1</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/geronimo.png" target="_blank"><img class="alignright size-thumbnail wp-image-1230" title="Geronimo admin console" src="http://agoncal.files.wordpress.com/2011/10/geronimo.png?w=150&#038;h=111" alt="" width="150" height="111" /></a><a href="http://geronimo.apache.org/">Geronimo</a> is not already Java EE 6 ceritified (still in Miletone 1). Geronimo comes in 2 flavours, one with Jetty the other one with Tomcat. And like TomEE, Geronimo <a href="https://cwiki.apache.org/GMOxDOC30/component-versions.html">bundles several open source implementations</a>of Java EE.</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>3.0-M1</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Not yet certified</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.apache.org/">Apache</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>Apache Software License</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="https://cwiki.apache.org/GMOxDOC30/documentation.html">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://geronimo.apache.org/apache-geronimo-v30-m1-release.html">Zip, tar</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>66.9 Mb (Geronimo + Tomcat)</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip the file</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>76.4 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>%GERONIMO_HOME%\bin\geronimo start</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%GERONIMO_HOME%\var\log</td>
</tr>
<tr>
<td>Best startup time</td>
<td>12 467ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>159 Mb</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>Admin console (*)</td>
<td>http://localhost:8080/console-base</td>
</tr>
</tbody>
</table>
<p>(*) user/pwd : system/manager</p>
<h2>JOnAS 5.3.0-M4</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/jonas.png" target="_blank"><img class="alignright size-thumbnail wp-image-1234" title="Jonas" src="http://agoncal.files.wordpress.com/2011/10/jonas.png?w=150&#038;h=104" alt="" width="150" height="104" /></a><a href="http://wiki.jonas.ow2.org/">JOnAS</a>is till not Java EE 6 certified. It provides a full Java EE 5 execution stack plus some Java EE 6 previews (JPA 2.0, CDI, &#8230;), supporting EJB3 (and not EJB 3.1 yet).</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>5.3.0-M4</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Not yet certified</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.ow2.org/">OW2</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>LGPL</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://wiki.jonas.ow2.org/xwiki/bin/view/Main.Documentation/JOnAS5">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://wiki.jonas.ow2.org/xwiki/bin/view/Main/Downloads">Zip, tar.gz</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>211 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip the file</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>231 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>%JONAS_HOME%\bin\jonas start</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%JONAS_HOME%\logs</td>
</tr>
<tr>
<td>Best startup time</td>
<td>11 036ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>107 Mb</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:9000/</td>
</tr>
<tr>
<td>Admin console (*)</td>
<td>http://localhost:9000/jonasAdmin</td>
</tr>
</tbody>
</table>
<p>(*) user/pwd : jonas/jonas</p>
<h2>Siwpas Enterprise 2.0.0-GA</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/siwpas.png" target="_blank"><img class="alignright size-thumbnail wp-image-1237" title="Siwpas admin console" src="http://agoncal.files.wordpress.com/2011/10/siwpas.png?w=150&#038;h=121" alt="" width="150" height="121" /></a><a href="http://siwpas.mechsoft.com.tr/">Siwpas</a> (Simple Web Profile Application Server) is quite new compared to the good old application servers. But like most of them, it embeds well known open source stacks, most from Apache  (Tomcat, OpenEJB, OpenWebBeans, MyFaces, OpenJPA, Apache BeanValidation). It&#8217;s open source but you&#8217;ll still need a 30 days trial license to startup the enterprise version of the server.</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>2.0.0-GA</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Web Profile 1.0 (Not yet certified)</td>
</tr>
<tr>
<td>Who is behind?</td>
<td>Mechsoft</td>
</tr>
<tr>
<td>Open source?</td>
<td></td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://siwpas.mechsoft.com.tr/index.php?option=com_content&amp;view=article&amp;id=69&amp;Itemid=118">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://siwpas.mechsoft.com.tr/index.php?option=com_phocadownload&amp;view=section&amp;id=1&amp;Itemid=107">Zip, exe, tar.gz</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>34.2 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip the file</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>38.2 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>%SIWPAS_HOME%\bin\startup</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%SIWPAS_HOME%\logs</td>
</tr>
<tr>
<td>Best startup time</td>
<td>8 598ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>72.8 Mb</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>Admin console (*)</td>
<td>http://localhost:8080/console</td>
</tr>
</tbody>
</table>
<p>(*) user/pwd : admin/admin</p>
<h2>Websphere 8.0.0.1</h2>
<p><a href="http://agoncal.files.wordpress.com/2011/10/websphere.png" target="_blank"><img class="alignright size-thumbnail wp-image-1212" title="Websphere admin console" src="http://agoncal.files.wordpress.com/2011/10/websphere.png?w=150&#038;h=86" alt="" width="150" height="86" /></a><a href="http://www-01.ibm.com/software/webservers/appserv/was/features/">Websphere 8</a> is the Java EE 6 application server of IBM. Like the previous versions, you need a big bandwith to download one gigabyte of modules that get installed in nearly 2 hours. I noticed that there is a <a href="http://www-01.ibm.com/software/webservers/appserv/developer/index.html">developer edition</a> but once installed it looks like the 2.2 Gb of the full server (I might got lost in the maze of the IBM website). There is also a <a href="http://www-01.ibm.com/software/webservers/appserv/community/">Community Edition</a> and it looks like it&#8217;s based on <a href="http://geronimo.apache.org/">Geronimo</a> (and the executable to install it is also 116 Mb). IBM, please, make it simple.</p>
<p>Thanks to <a href="http://twitter.com/#!/sebsto">@sebsto</a> I found a gem : it looks like IBM is working on a version <a href="https://www.ibm.com/developerworks/mydeveloperworks/blogs/wasdev/entry/home?lang=en">WAS 8.5 Alpha</a> that would look like the other app servers (light and easy to install). I&#8217;ll stay tuned on this one.</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>8</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Java EE 6</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.ibm.com/">IBM</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>Commercial product</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://www-01.ibm.com/software/webservers/appserv/was/#">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="https://www.ibm.com/developerworks/downloads/ws/was/">Exe file for WAS</a> &amp; <a href="http://www-01.ibm.com/software/webservers/appserv/developer/index.html">WAS for developers</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>116 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Execute + Wizard install (with all the defaults) which downloads more stuff (took nearly 1:40 hour)</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>2.2 Gb</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute %WEBSPHERE_HOME%\AppServer\profiles\AppSrv01\bin\startServer.bat server1 -profileName AppSrv01</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%WEBSPHERE_HOME%\AppServer\profiles\AppSrv01\logs\server1</td>
</tr>
<tr>
<td>Best startup time</td>
<td>42 s</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>155 Mb</td>
</tr>
<tr>
<td>Admin console</td>
<td>https://localhost:9043/ibm/console</td>
</tr>
</tbody>
</table>
<h2>Jeus 7</h2>
<p>A bit unknown but in version 7.0 (so it shows this application server has been around for long time), <a href="http://us.tmaxsoft.com/jsp/product/detailcontents.jsp?psCd=00PD04&amp;menuCd=00PDMSJE">Jeus 7</a>from TMaxSoft was a bit difficult to startup (create an account on the web site, download, install, run a wizard and read the README.txt to make it started). Then I discovered that there is no Jeus 7 for Windows so I downloaded the Linux version and installed it on Ubuntu (so the results of the microbenchmark are not very accurate compare to the other made on Windows).</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>7</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Java EE 6</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://us.tmaxsoft.com">TmaxSoft</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>Commercial</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://us.tmaxsoft.com/jsp/product/detailcontents.jsp?psCd=00PD04&amp;menuCd=00PDMSJE">Documentation</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://us.tmaxsoft.com/jsp/product/detailcontents.jsp?psCd=00PD04&amp;menuCd=00PDMSJE">bin file</a> (only available on Linux)</td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>126 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Execute the file and answer a wizard</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>198 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute $JEUS_HOME/bin/jeus -u administrator -p &lt;pwd you declared in the wizard&gt;</td>
</tr>
<tr>
<td>Location of log files</td>
<td>$JEUS_HOME/domains/jeus-domain1/logs</td>
</tr>
<tr>
<td>Best startup time</td>
<td>23 783ms (but again that was on Ubuntu, not in Windows)</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>147 Mb</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8088/ (but looks like there&#8217;s no page)</td>
</tr>
<tr>
<td>Admin console</td>
<td>Not sure there&#8217;s a admin console, but jeusadmin tool helps you to manage the server</td>
</tr>
</tbody>
</table>
<h2>Interstage</h2>
<p>I couldn&#8217;t even find where to <a href="http://www.fujitsu.com/global/services/software/interstage/">click and download the server</a>, so if anybody knows, I&#8217;ll be ready to give it a try.</p>
<h2>Where the hell is Tomcat ?</h2>
<p>Tomcat 7 is not a Java EE 6 application server nor does it implement the Web Profile 1.0. It is just a Servlet 3.0 container, so it&#8217;s shouldn&#8217;t appear in this blog post. But, everybody likes Tomcat, everybody feels Tomcat is way much faster than any server on earth (even faster than <a href="http://www.popsci.com/science/article/2011-09/baffling-cern-results-show-neutrinos-moving-faster-speed-light">Neutrinos</a> or <a href="http://www.engadget.com/2011/10/17/remember-those-faster-than-light-neutrinos-great-now-forget-e">maybe not</a>). So I had to put it in this benchmark just to be a source of comparaison. And, indeed, Tomcat is the fastest application server of the list (3 times faster than GlassFish or 4 times faster than JBoss). But it only does Servlet 3 while the others implement between 12 (Web Profile) or 28 (Java EE 6) specifications.</p>
<table border="1">
<tbody>
<tr>
<td>Version</td>
<td>7.0.22</td>
</tr>
<tr>
<td>What do you get ?</td>
<td>Servlet 3</td>
</tr>
<tr>
<td>Who is behind?</td>
<td><a href="http://www.apache.org/">Apache</a></td>
</tr>
<tr>
<td>Open source?</td>
<td>Apache Software License</td>
</tr>
<tr>
<td>Documentation</td>
<td><a href="http://tomcat.apache.org/tomcat-7.0-doc/index.html">Documentation Index</a></td>
</tr>
<tr>
<td>Download</td>
<td><a href="http://tomcat.apache.org/download-70.cgi">Zip, tar.gz</a></td>
</tr>
<tr>
<td>Size of the downloaded file</td>
<td>7.5 Mb</td>
</tr>
<tr>
<td>Installation mode</td>
<td>Unzip the file</td>
</tr>
<tr>
<td>Size once installed on drive</td>
<td>11.3 Mb</td>
</tr>
<tr>
<td>How to start it</td>
<td>Execute %TOMCAT_HOME%\bin\startup.bat</td>
</tr>
<tr>
<td>Location of log files</td>
<td>%TOMCAT_HOME%\logs</td>
</tr>
<tr>
<td>Best startup time</td>
<td>694 ms</td>
</tr>
<tr>
<td>Size of the process in RAM at startup</td>
<td>34.6 Mb</td>
</tr>
<tr>
<td>Welcome page</td>
<td>http://localhost:8080/</td>
</tr>
<tr>
<td>Admin console</td>
<td>http://localhost:8080/manager/html</td>
</tr>
</tbody>
</table>
<h1>Summary</h1>
<p>As a summary I will show you two graphs with startup time and resource consumption so it&#8217;s easier to compare.</p>
<h2>Startup time</h2>
<p>When you are a developer, startup up time matters (it doesn&#8217;t when you are in production). Thanks to tools like <a href="http://zeroturnaround.com/jrebel/">JRebel</a> or the hot deployment of our IDEs, we tend to restart our app servers less and less. But, sometimes it happens (PermGens, classpath mess up, memory leaks, refreshing app server cache&#8230;). I didn&#8217;t put WAS 8 nor Jeus 7 in the graph below because they would just break the scale (42 and 23 seconds). It&#8217;s interesting to notice that <strong>4 app servers (Resin, GlassFish, JBoss and TomEE) start in less that 5 seconds</strong> (Jonas &amp; Geronimo are still in Milestone). Resin is 3 times slower than Tomcat, but again, it comes with the Web Profile.</p>
<p style="text-align:center;"><a href="http://agoncal.files.wordpress.com/2011/10/2011appserverstartup.png"><img class="size-full wp-image-1248 aligncenter" title="Startup time" src="http://agoncal.files.wordpress.com/2011/10/2011appserverstartup.png?w=468" alt=""   /></a></p>
<h2>Size once installed on the drive &amp; size of process in RAM</h2>
<p>The size of the application installed on your disk is not very accurate : some app servers come with documentation, samples&#8230; others no. But still, that gives you an overview of how big an app server can be (again, I couldn&#8217;t put WAS in this diagram as it will break the scale with its 2.2 Gb). The memory consumption is more interesting. Without any JVM or server twists, when you startup, <strong>they nearly all take less that 100Mb of RAM</strong>(see how close TomEE, GlassFish, JBoss and Siwpas are).</p>
<p style="text-align:center;"><a href="http://agoncal.files.wordpress.com/2011/10/2011appservermemory.png"><img class="aligncenter size-full wp-image-1251" title="Memory usage" src="http://agoncal.files.wordpress.com/2011/10/2011appservermemory.png?w=468" alt=""   /></a></p>
<h1>Conclusion</h1>
<p>First of all, as you can see there is no Weblogic. Unfortunatelly Weblogic is the last big player to be certified Java EE 6. I don&#8217;t know the roadmap, hopefully I&#8217;ll soon be able to update this blog entry with the latest version of Weblogic. Second, this is not a real benchmark : I didn&#8217;t deploy any application nor I did some stress tests. One task I would like to do is to deploy a Java EE 6 application on all these servers and see how portable the code is. But that&#8217;s for another blog.</p>
<p>What did I want to show in this blog ? Well, that <strong>application servers have changed</strong>. Except for WAS, Weblogic or Jeus, all the others are fast at startup and take few resources (memory).</p>
<p>And why did I want to show this ? Because I&#8217;m fed up to still hear in 2011 : &#8220;Tomcat is light, Java EE app servers are not&#8221;. As you can see, <strong>in terms of startup and memory, the gap between Tomcat and Resin, GlassFish or JBoss is really small</strong>.</p>
<p>How is it going to affect your development life ? Do you remember when 7/8 years ago we had to mock our database accesses because we didn&#8217;t want to install a fat oracle database on our laptop ? These days are over now because we use in-memory databases such as <a href="http://www.h2database.com">H2</a> or <a href="http://db.apache.org/derby/">Derby</a>. Same thing is happening with application servers : <strong>soon app servers will be running in memory</strong> and we won&#8217;t be mocking anything. We will fire a test case, app servers and databases in memory, and that&#8217;s it. And with tools like <a href="http://www.jboss.org/arquillian">Arquilian</a>, it looks like this future is already happening.</p>
<p>Long live Java EE 6 and Java EE 6 application servers !</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1185/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1185&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/10/20/o-java-ee-6-application-servers-where-art-thou/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/glassfish.png?w=150" medium="image">
			<media:title type="html">GlassFish admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/resin.png?w=150" medium="image">
			<media:title type="html">Resin admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/jboss.png?w=150" medium="image">
			<media:title type="html">JBoss admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/tomee.png?w=150" medium="image">
			<media:title type="html">TomEE admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/geronimo.png?w=150" medium="image">
			<media:title type="html">Geronimo admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/jonas.png?w=150" medium="image">
			<media:title type="html">Jonas</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/siwpas.png?w=150" medium="image">
			<media:title type="html">Siwpas admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/websphere.png?w=150" medium="image">
			<media:title type="html">Websphere admin console</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/2011appserverstartup.png" medium="image">
			<media:title type="html">Startup time</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/10/2011appservermemory.png" medium="image">
			<media:title type="html">Memory usage</media:title>
		</media:content>
	</item>
		<item>
		<title>Injection with CDI (Part III)</title>
		<link>http://agoncal.wordpress.com/2011/09/25/injection-with-cdi-part-iii/</link>
		<comments>http://agoncal.wordpress.com/2011/09/25/injection-with-cdi-part-iii/#comments</comments>
		<pubDate>Sun, 25 Sep 2011 20:38:10 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cdi]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1139</guid>
		<description><![CDATA[If you follow this blog you should know that latelly I&#8217;ve been writing (and talking) about CDI (Contexts and Dependency Injection). CDI has many aspects to it but until now I&#8217;ve focused on how to boostrap CDI in several environments, how to add CDI to an existing Java EE 6 application,  and more recently how [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1139&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionIII.zip"><img class="size-full wp-image-652 alignleft" title="Download the code" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a>If you follow this blog you should know that latelly I&#8217;ve been writing (and <a title="To inject or not to inject: CDI is the question" href="http://agoncal.wordpress.com/2011/05/23/to-inject-or-not-to-inject-cdi-is-the-question/">talking</a>) about CDI (<a href="http://jcp.org/en/jsr/summary?id=299">Contexts and Dependency Injection</a>). CDI has many aspects to it but until now I&#8217;ve focused on <a title="Bootstrapping CDI in several environments" href="http://agoncal.wordpress.com/2011/01/12/bootstrapping-cdi-in-several-environments/">how to boostrap CDI in several environments</a>, how to <a title="Adding CDI to an existing Java EE 6 application" href="http://agoncal.wordpress.com/2011/02/07/adding-cdi-to-an-existing-java-ee-6-application/">add CDI to an existing Java EE 6 application</a>,  and more recently <strong>how to use injection</strong> with CDI. Actually this post is the third on CDI Injection : <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">Part I</a> focused on default injection and qualifiers, and <a title="Injection with CDI (Part II)" href="http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/">Part II</a> on all the possible injection points (field, constructor and setters). In this post I&#8217;ll explain <strong>producers</strong> or &#8220;<em>how you can inject anything anywhere in a type safe manner</em>&#8220;.</p>
<h1>Injecting just beans ?</h1>
<p>Until now I&#8217;ve shown you how to inject beans with a simple <tt>@Inject</tt>. If we focus on the book number generator example I&#8217;ve been using, we have a Servlet and a RESTService being injected an implementation of the <tt>NumberGenerator</tt> interface. Thanks to <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">qualifiers</a>, the servlet can specifically ask to get the <tt>IsbnGenerator</tt> by specifying the <tt>@ThirteenDigit</tt> qualifier on the injection point and the rest service an <tt>IssnGenerator</tt> with a <tt>@EightDigits </tt>(check my <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">first</a> post). The following class diagram shows you some combinations of bean injection :</p>
<p style="text-align:center;"><a href="http://agoncal.files.wordpress.com/2011/07/producer01.gif"><img class="aligncenter size-full wp-image-1143" title="Injecting beans" src="http://agoncal.files.wordpress.com/2011/07/producer01.gif?w=468" alt=""   /></a></p>
<p>But as you can see, all this is <strong>are beans injecting other beans</strong>. Can we just inject beans with CDI ? The answer is no, <strong>you can inject anything anywhere</strong>.</p>
<h1>Producers</h1>
<p>Yes, you can inject anything anywhere, the only thing you have to do is <em>produce</em> the <em>thing</em> you want to inject. For that, CDI has <strong>producers</strong> (a nice implementation of the <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory pattern</a>) A producer exposes any sort of :</p>
<ul>
<li><strong>Class</strong> : unrestricted set of bean types, superclass, and all interfaces it implements directly or indirectly</li>
<li><strong>Interface</strong> : unrestricted set of bean types, interfaces it extends directly or indirectly, and <tt>java.lang.Object</tt></li>
<li><strong>Primitive and Java array type</strong></li>
</ul>
<p>So by that you can inject a <tt>java.util.Date</tt>, <tt>java.lang.String</tt> or even an <tt>int</tt>. Let&#8217;s start by producing and injecting some data types and primitives.</p>
<h1>Producing data types and primitives</h1>
<p>One example of <em>injecting anything anywhere</em> is the possibility to inject data types or primitives. So let&#8217;s inject a <tt>String</tt> and an <tt>int</tt>. For that I need to add extra classes to our model. Until now, the <tt>IsbnGenerator</tt> would generate a random number like <strong>13-124-454644-4</strong>. I can say that this number is made of a <tt>String</tt> that acts like a prefix (<strong>13-124</strong>) and an <tt>int</tt> that acts like a suffix (<strong>4</strong>). The following class diagram shows the two new classes <tt>PrefixGenerator</tt> and <tt>PostfixGenerator</tt>that will be used by the number generators :</p>
<p style="text-align:center;"><a href="http://agoncal.files.wordpress.com/2011/07/producer02.gif"><img class="aligncenter size-full wp-image-1154" title="Producing primitives and data types" src="http://agoncal.files.wordpress.com/2011/07/producer02.gif?w=468" alt=""   /></a></p>
<p>If we look at the code of the <tt>PrefixGenerator</tt> for example, you can see that the class itself is not annotated by any qualifier, but the methods are. The method <tt>getIsbnPrefix</tt> returns a <tt>String</tt> that is qualified with <tt>@ThirteenDigits</tt>. This String is produced by CDI (thanks to <tt>@Produces</tt>), meaning that you can now inject it with <tt>@Inject</tt> using its qualifier (<tt>@ThirteenDigits</tt>)</p>
<p><pre class="brush: java; highlight: [3,8];">
public class PrefixGenerator {

    @Produces @ThirteenDigits
    public String getIsbnPrefix() {
        return &quot;13-84356&quot;;
    }

    @Produces @EightDigits
    public String getIssnPrefix() {
        return &quot;8&quot;;
    }
}
</pre></p>
<p>And now look carefully at the class  <tt>PostfixGenerator</tt>. The code is exactly the same as previously except in this case we produce an <tt>int</tt>that can now be injected.</p>
<p><pre class="brush: java; highlight: [3,8];">
public class PostfixGenerator {

    @Produces @ThirteenDigits
    public int getIsbnPostfix() {
        return 13;
    }

    @Produces @EightDigits
    public int getIssnPostfix() {
        return 8;
    }
}
</pre></p>
<p>So now let&#8217;s change the way an ISBN number is generated. The bean IsbnGenerator now injects both a <tt>String</tt> and an <tt>int</tt> with <tt>@Inject @ThirteenDigits</tt>. You understand now what <strong>strong typing</strong> means with CDI.  Using the same syntax (<tt>@Inject @ThirteenDigits</tt>), CDI knows that it needs to inject a <tt>String</tt>, an <tt>int</tt> or an implementation of a <tt>NumberGenerator</tt>.</p>
<p><pre class="brush: java; highlight: [1,4,7];">
@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {

    @Inject @ThirteenDigits
    private String prefix;

    @Inject @ThirteenDigits
    private int postfix;

	public String generateNumber() {
        return prefix + &quot;-&quot; + Math.abs(new Random().nextInt()) + &quot;-&quot; + postfix;
    }
}
</pre></p>
<h1>Injecting Java EE resources with producer fields</h1>
<p>So if CDI can inject anything anywhere, if CDI can even inject Strings and integers, what about Java EE resources ? That&#8217;s another story and producers are here to help. As I&#8217;ve said before, CDI is all about type safety : CDI doesn&#8217;t like Strings, so <strong>there is no way to inject a resource by its JNDI name</strong> such as <tt>@Inject(name="jms/OrderQueue")</tt>. A common example is the entity manager. This is how you must inject it in Java EE 6 if you don&#8217;t use CDI :</p>
<p><pre class="brush: java; highlight: [4];">
@Stateless
public class ItemEJB {

    @PersistenceContext(unitName = &quot;cdiPU&quot;)
    private EntityManager em;
    ...
}
</pre></p>
<p>So why can&#8217;t you just <tt>@Inject</tt> an entity manager? If you remember my <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">first</a> post about ambiguous injection, this is the same problem. You can have several persistence units (named with a string), so if you just use an <tt>@Inject</tt>, CDI will not know which persistence unit to inject. Instead you must produce the entity manager first, give it a name (if you don&#8217;t want the <tt>@Default</tt>) and then an <tt>@Inject</tt> as follow :</p>
<p><pre class="brush: java; highlight: [3,4,5];">
public class DatabaseProducer {

    @Produces
    @PersistenceContext(unitName = &quot;cdiPU&quot;)
    @BookStoreDatabase
    private EntityManager em;
}
</pre></p>
<p>The <tt>DatabaseProducer</tt> class uses the <tt>@PersistenceContext</tt> to inject the entity manager with the persistence unit <tt>cdiPU</tt>. It gives it a name using a qualifier (<tt>@BookStoreDatabase</tt>) and produces it so it can now be injected in an EJB as follow :</p>
<p><pre class="brush: java; highlight: [4,5];">
@Stateless
public class ItemEJB {

    @Inject
    @BookStoreDatabase
    private EntityManager em;
    ...
}
</pre></p>
<p>Another nice use case is to produce JMS factories and destinations. <tt>@Resource</tt> allows you to get a JNDI reference to a specific JMS factory or destination, the qualifier <tt>@Order</tt> gives it a name, and the <tt>@Produces</tt> allows you to inject it :</p>
<p><pre class="brush: java; highlight: [3,6];">
public class JMSResourceProducer {

    @Produces @Order @Resource(name = &quot;jms/OrderConnectionFactory&quot;)
    private QueueConnectionFactory orderConnectionFactory;

    @Produces @Order @Resource(name = &quot;jms/OrderQueue&quot;)
    private Queue orderQueue;
}
</pre></p>
<p>Now your EJB can use <tt>@Inject</tt> in a type-safe way :</p>
<p><pre class="brush: java; highlight: [4,7];">
@Stateless
public class ItemEJB {

    @Inject @Order
    private QueueConnectionFactory orderConnectionFactory;

    @Inject @Order
    private Queue orderQueue;
    ...
}
</pre></p>
<h1>Producing Java EE resources with producer methods</h1>
<p>The examples above are pretty simple : produce a field and you can then inject it. That&#8217;s called producer field. But sometimes you need a more complex business logic to produce a bean, that&#8217;s what we called producer method. Let&#8217;s take another use case. When you need to send a JMS message you always end up injecting a JMS Factory, a destination (queue or topic) creating a connection, then a session and so on until you actually send your message. Because this code is repetitive and error prone, why not externalize all of if into a single class and produce a session so the other components can use when sending a message. This class could look something like that :</p>
<p><pre class="brush: java; highlight: [3,6,9,14];">
public class JMSResourceProducer {

    @Resource(name = &quot;jms/OrderConnectionFactory&quot;)
    private QueueConnectionFactory orderConnectionFactory;
    @Produces @Order @Resource(name = &quot;jms/OrderQueue&quot;)
    private Queue orderQueue;

    @Produces @Order
    public QueueConnection createOrderConnection() throws JMSException {
        return orderConnectionFactory.createQueueConnection();
    }

    @Produces @Order
    public QueueSession createOrderSession(@Order QueueConnection conn) throws JMSException {
        return conn.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
    }
}
</pre></p>
<p>First, the class uses the <tt>@Resource</tt> to get a reference of the <tt>QueueConnectionFactory</tt> and <tt>Queue</tt>. For the same reason I just explain above, you can have several JMS factories and destinations and you must distinguish them by their JNDI name. And because CDI does not allow you to give a string name on an injection point, you must still use <tt>@Resource</tt> instead of <tt>@Inject</tt>. The <tt>createOrderConnection</tt> method take a <tt>QueueConnectionFactory</tt> creates a <tt>QueueConnection</tt> and produces it (while giving it the name of <tt>@Order</tt>). If you look carefully at the method <tt>createOrderSession</tt> it takes the produced <tt>QueueConnection</tt> and creates a <tt>QueueSession</tt>. An external component then just needs to inject the JMS session without going through the process of creating it :</p>
<p><pre class="brush: java; highlight: [4,7];">
@Stateless
public class ItemEJB {

    @Inject @Order
    private QueueSession session;

    @Inject @Order
    private Queue orderQueue;

    private void sendOrder(Book book) throws Exception {
        QueueSender sender = session.createSender(orderQueue);
        TextMessage message = session.createTextMessage();
        message.setText(marshall(book));
        sender.send(message);
    }
    ...
}
</pre></p>
<h1>Producing and&#8230; disposing</h1>
<p>I can hear you saying &#8220;ok, that&#8217;s nice, I have an external class doing all the plumbing and creating a connection and a session&#8230;. <strong>but who is going to close it ?</strong>&#8220;. Indeed, someone needs to free these resources by closing them. And that&#8217;s when CDI brings you another nice bit of magic : <tt>@Disposes</tt>.</p>
<p><pre class="brush: java; highlight: [18,22];">
public class JMSResourceProducer {

    @Resource(name = &quot;jms/OrderConnectionFactory&quot;)
    private QueueConnectionFactory orderConnectionFactory;
    @Produces @Order @Resource(name = &quot;jms/OrderQueue&quot;)
    private Queue orderQueue;

    @Produces @Order
    public QueueConnection createOrderConnection() throws JMSException {
        return orderConnectionFactory.createQueueConnection();
    }

    @Produces @Order
    public QueueSession createOrderSession(@Order QueueConnection conn) throws JMSException {
        return conn.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
    }

    public void closeOrderSession(@Disposes @Order QueueConnection conn) throws JMSException {
        conn.close();
    }

    public void closeOrderSession(@Disposes @Order QueueSession session) throws JMSException {
        session.close();
    }
}
</pre></p>
<p>To ask CDI to close a resource you just need to create a method which signature is the same as the one that created it (<tt>createOrderSession(@Order QueueConnection conn)</tt> creates a session and <tt>closeOrderSession(@Order QueueConnection conn)</tt> closes it) and add a <tt>@Disposes</tt>. CDI will dispose the resources in the right order (session first, connection second) for you. I haven&#8217;t mentioned it yet but CDI will create and dispose resources depending on the scope (resquest, session, application, conversation&#8230;). But that&#8217;s for another post.</p>
<h1>Conclusion</h1>
<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionIII.zip"><img class="alignright size-full wp-image-652" title="Download the code" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a>As you&#8217;ve seen in my previous posts (<a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">Part I</a>, <a title="Injection with CDI (Part II)" href="http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/">Part II</a>), CDI is about injection (I&#8217;ll explain other topics later). So far I&#8217;ve been showing you how to inject beans, but you know now that you can inject anything (String, integer, entity manager, JMS factories&#8230;) anywhere (in POJOs, Servlets, EJBs&#8230;). You just need to produce what you need to inject (either with field producers or method producers).<br />
The next article will cover <strong>alternatives</strong>, so stay tuned.</p>
<h1>Download</h1>
<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionIII.zip">Download the code</a>, give it a try, and give me some feedback.</p>
<h1>References</h1>
<ul>
<li><a href="http://docs.jboss.org/weld/reference/latest/en-US/html_single/">Weld &#8211; JSR-299 Reference Implementation</a></li>
<li><a href="http://blogs.oracle.com/arungupta/entry/totd_144_cdi_produces_for">TOTD #144: CDI @Produces for container-managed @Resource</a></li>
<li><a href="http://javaboutique.internet.com/tutorials/cdi-producer-fields-and-methods/" target="_blank">CDI Producer Fields and Methods Enhance Java EE 6 DI</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1139/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1139&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/09/25/injection-with-cdi-part-iii/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">Download the code</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/07/producer01.gif" medium="image">
			<media:title type="html">Injecting beans</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/07/producer02.gif" medium="image">
			<media:title type="html">Producing primitives and data types</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">Download the code</media:title>
		</media:content>
	</item>
		<item>
		<title>Walking through the Java EE 6 implementation maze</title>
		<link>http://agoncal.wordpress.com/2011/06/24/walking-through-the-java-ee-6-implementation-maze/</link>
		<comments>http://agoncal.wordpress.com/2011/06/24/walking-through-the-java-ee-6-implementation-maze/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 19:31:01 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java ee 6]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1114</guid>
		<description><![CDATA[I&#8217;ve been asked so many times &#8220;what are the implementations of such or such specification in Java EE 6 ?&#8221; or &#8220;what is the reference implementation of such a spec ?&#8220;. Because I always forget some (and to be honest, sometimes I don&#8217;t even know if a spec has several implementations of not), I&#8217;m writing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1114&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been asked so many times &#8220;<strong>what are the implementations of such or such specification in Java EE 6 ?</strong>&#8221; or &#8220;<strong>what is the reference implementation of such a spec ?</strong>&#8220;. Because I always forget some (and to be honest, sometimes I don&#8217;t even know if a spec has several implementations of not), I&#8217;m writing this post to help me (and you) to remember.</p>
<p>So here is a non-exhaustive list of the several <strong>Java EE 6 implementations</strong> (please leave a comment to add anything to this list) :</p>
<table border="1">
<tbody>
<tr>
<td>Specification</td>
<td>Version</td>
<td>JSR</td>
<td>Prunned</td>
<td>Reference implementation</td>
<td>Other implementations</td>
</tr>
<tr>
<td>Java EE</td>
<td>6.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=316">316</a></td>
<td></td>
<td><a href="http://glassfish.java.net/">GlassFish V3</a></td>
<td><a href="http://us.tmaxsoft.com/jsp/product/detailcontents.jsp?psCd=00PD04&amp;menuCd=00PDMSJE">JEUS 7</a>, <a href="http://www-01.ibm.com/software/webservers/appserv/was/features/">Websphere 8</a>, <a href="http://geronimo.apache.org/">Geronimo 3</a>*, Weblogic 12g</td>
</tr>
<tr>
<td>Web Profile</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=316">316</a></td>
<td></td>
<td><a href="http://glassfish.java.net/">GlassFish V3</a></td>
<td><a href="http://www.jboss.org/jbossas/">JBoss 6</a>, <a href="http://www.jboss.org/jbossas/">JBoss 7</a>*, <a href="http://www.caucho.com/resin/">Resin 4</a>, <a href="http://geronimo.apache.org/">Geronimo 3</a>*, <a href="http://siwpas.mechsoft.com.tr/">Siwpass 1</a>, Weblogic 12g, <a href="http://openejb.apache.org/3.0/apache-tomee.html">TomEE</a>*</td>
</tr>
<tr>
<td>Managed Beans</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=316">316</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>JAX-RPC</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=101">101</a></td>
<td>Yes</td>
<td></td>
<td></td>
</tr>
<tr>
<td>JAX-WS</td>
<td>2.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=224">224</a></td>
<td></td>
<td><a href="http://metro.java.net/">Metro</a></td>
<td><a href="http://axis.apache.org/">Axis 2</a>, <a href="http://cxf.apache.org/">CXF 2</a>,</td>
</tr>
<tr>
<td>JAXB 2.2</td>
<td>2.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=222">222</a></td>
<td></td>
<td><a href="http://jaxb.java.net/">Glassfish JAXB 2.2</a></td>
<td></td>
</tr>
<tr>
<td>JAXM</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=67">67</a></td>
<td></td>
<td><a href="http://java.net/projects/saaj/">Glassfish SAAJ 1.3</a></td>
<td></td>
</tr>
<tr>
<td>StaX</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=173">173</a></td>
<td></td>
<td><a href="http://sjsxp.java.net/">Sjsxp 1</a></td>
<td><a href="http://woodstox.codehaus.org/">Woodstox 3</a>, <a href="http://stax.codehaus.org/Home">Codehaus</a>+</td>
</tr>
<tr>
<td>Web Services</td>
<td>1.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=109">109</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Web Services Metadata</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=181">181</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>JAX-RS</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=311">311</a></td>
<td></td>
<td><a href="http://jersey.java.net/">Jersey 1.x</a></td>
<td><a href="http://incubator.apache.org/wink/">Wink</a>*, <a href="http://cxf.apache.org/">CXF 2</a>, <a href="http://www.jboss.org/resteasy/">Resteasy 2</a>, <a href="http://www.restlet.org/">Restlet 2</a>,</td>
</tr>
<tr>
<td>JAXR</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=93">93</a></td>
<td> Yes</td>
<td></td>
<td><a href="http://juddi.apache.org/scout/">Scout 1</a>,</td>
</tr>
<tr>
<td>JSF</td>
<td>2.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=314">314</a></td>
<td></td>
<td><a href="http://javaserverfaces.java.net/">Mojara 2</a></td>
<td><a href="http://myfaces.apache.org/">MyFaces 2</a>,</td>
</tr>
<tr>
<td>JSP</td>
<td>2.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=245">245</a></td>
<td></td>
<td><a href="http://jsp.java.net/">GlassFish JSP 2.2</a></td>
<td><a href="http://tomcat.apache.org/">Tomcat 7</a>,</td>
</tr>
<tr>
<td>Debugging Support</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=45">45</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>JSTL</td>
<td>1.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=52">52</a></td>
<td></td>
<td><a href="http://jstl.java.net/">Glassfish JSTL 1.2</a></td>
<td></td>
</tr>
<tr>
<td>Servlet</td>
<td>3.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=315">315</a></td>
<td></td>
<td><a href="http://glassfish.java.net/">GlassFish 3</a></td>
<td><a href="http://tomcat.apache.org/">Tomcat 7</a>, <a href="http://www.eclipse.org/jetty/">Jetty 8</a>,</td>
</tr>
<tr>
<td>Expression Language</td>
<td>2.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=245">245</a></td>
<td></td>
<td><a href="http://uel.java.net/">GlassFish EL 2.2</a></td>
<td><a href="http://juel.sourceforge.net/">JUEL 2</a>,</td>
</tr>
<tr>
<td>EJB</td>
<td>3.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=318">318</a></td>
<td>Entity Beans CMP</td>
<td><a href="http://glassfish.java.net/">GlassFish 3</a></td>
<td><a href="http://openejb.apache.org/">OpenEJB 3.1</a>,</td>
</tr>
<tr>
<td>Interceptors</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=318">318</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>JAF</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=925">925</a></td>
<td></td>
<td><a href="http://java.sun.com/products/archive/javabeans/jaf102.html">GlassFish JAF 1</a></td>
<td></td>
</tr>
<tr>
<td>JavaMail</td>
<td>1.4</td>
<td><a href="http://jcp.org/en/jsr/detail?id=919">919</a></td>
<td></td>
<td><a href="http://kenai.com/projects/javamail">Kenai Project</a>+</td>
<td><a href="http://www.gnu.org/software/classpathx/javamail/javamail.html">GNU Java Mail</a>, <a href="http://geronimo.apache.org/maven/javamail/1.7/index.html">Geronimo JavaMail</a>,</td>
</tr>
<tr>
<td>JCA</td>
<td>1.6</td>
<td><a href="http://jcp.org/en/jsr/detail?id=322">322</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>JMS</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=914">914</a></td>
<td></td>
<td><a href="http://mq.java.net/">Open MQ 4</a></td>
<td><a href="http://activemq.apache.org/">ActiveMQ 5</a>, <a href="http://web.progress.com/fr-fr/sonic/sonicmq.html">SonicMQ</a>, <a href="http://www.jboss.org/hornetq/">HornetQ 2</a>, <a href="http://www-01.ibm.com/software/integration/wmq/">Websphere MQ</a>, <a href="http://joram.ow2.org/">Joram</a>,</td>
</tr>
<tr>
<td>JPA</td>
<td>2.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=317">317</a></td>
<td></td>
<td><a href="http://www.eclipse.org/eclipselink/">EclipseLink 2</a></td>
<td><a href="http://openjpa.apache.org/">OpenJPA 2</a>, <a href="http://www.hibernate.org/">Hibernate 3.5</a>,</td>
</tr>
<tr>
<td>JTA</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=907">907</a></td>
<td></td>
<td></td>
<td><a href="http://www.atomikos.com/Main/TransactionsEssentials">Atomikos</a>, <a href="http://docs.codehaus.org/display/BTM/Home">BTM</a>, <a href="http://www.jboss.org/jbosstm">JBoss Transaction</a>, <a href="http://simplejta.sourceforge.net/">SimpleJTA</a>, <a href="http://jotm.ow2.org/xwiki/bin/view/Main/WebHome">JOTM</a>,</td>
</tr>
<tr>
<td>JACC</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=115">115</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Bean Validation</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=303">303</a></td>
<td></td>
<td><a href="http://www.hibernate.org/subprojects/validator">Hibernate Validator 4</a></td>
<td><a href="http://incubator.apache.org/bval/cwiki/index.html">Apache Bean Validation</a>*</td>
</tr>
<tr>
<td>CDI</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=299">299</a></td>
<td></td>
<td><a href="http://seamframework.org/Weld">Weld 1</a></td>
<td><a href="http://openwebbeans.apache.org/owb/index.html">OpenWebBeans 1</a>, <a href="http://www.caucho.com/resin/candi/">CanDI</a>,</td>
</tr>
<tr>
<td>Dependency Injection</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=330">330</a></td>
<td></td>
<td><a href="http://code.google.com/p/google-guice/">Guice 3</a>+</td>
<td><a href="http://openwebbeans.apache.org/owb/index.html">OpenWebBeans 1</a>, <a href="http://seamframework.org/Weld">Weld 1</a>, <a href="http://www.caucho.com/resin/candi/">CanDI</a>, <a href="http://www.springsource.org/">Spring 3</a>,</td>
</tr>
<tr>
<td>Common Annotations</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=250">250</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Application Deployment</td>
<td>1.2</td>
<td><a href="http://jcp.org/en/jsr/detail?id=88">88</a></td>
<td>Yes</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Management</td>
<td>1.1</td>
<td><a href="http://jcp.org/en/jsr/detail?id=77">77</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>JASPIC</td>
<td>1.0</td>
<td><a href="http://jcp.org/en/jsr/detail?id=196">196</a></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<p><em>(*) not final yet at the time of writing this article  (+) not sure about that</em></p>
<p>Yes, it&#8217;s a maze and sometimes it&#8217;s difficult to walk through it&#8230; but hey, that&#8217;s also the strengh of being standard, portable and avoiding vendor locking. I will never say that an application is 100% portable through implementations (if you hear someone telling you this, don&#8217;t trust him/her), but it can get close to 100% in many cases. That&#8217;s also the difference between <em>standard</em> and <em>defacto-standard</em> (check the definition of <a href="http://en.wikipedia.org/wiki/De_facto">De Facto</a>).</p>
<p>And because I get lost in this maze, please help me in finding my way out. <strong>If I&#8217;ve missed something and I&#8217;m mistaken, please use the comments to improve this maze and give me your suggestions</strong>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1114/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1114&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/06/24/walking-through-the-java-ee-6-implementation-maze/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>
	</item>
		<item>
		<title>[Debate] – And what about configuration in Java EE 7 ?</title>
		<link>http://agoncal.wordpress.com/2011/06/10/debate-and-what-about-configuration-in-java-ee-7/</link>
		<comments>http://agoncal.wordpress.com/2011/06/10/debate-and-what-about-configuration-in-java-ee-7/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 12:13:11 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java ee 7]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1079</guid>
		<description><![CDATA[How do you configure your enterprise application ? Or to be more precise &#8220;what is configuration,  what can you configure in Java EE and how can you configure it ?&#8220; What is configuration ? Sometimes your application needs to change parts of its behavior at deployment time. You then need to provide some external configuration for some [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1079&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>How do you configure your enterprise application ? Or to be more precise &#8220;<strong>what is configuration,  what can you configure in Java EE and how can you configure it ?</strong>&#8220;</p>
<h2>What is configuration ?</h2>
<p>Sometimes your application needs to <strong>change parts of its behavior at deployment time</strong>. You then need to provide some <strong>external configuration</strong> for some components. For example, in your development environment you don&#8217;t want to use a datasource and instead hit the database with a user &amp; password, in your test environment you lookup for the datasource and use it. If you deploy your application in Europe you need to use the Euro as the current currency and if you deploy it in the US you need dollars. You&#8217;ve deployed your 2.3 version of your application and you want this &#8220;<em>2.3</em>&#8221; to appear at the bottom of your webpage as well as in your Swing <em>Help-&gt;About</em> menu. In a test environment everybody can access all the methods, in production security roles add certain restrictions. And so on and so forth&#8230;</p>
<p>In the Java EE specification there are several <strong>roles</strong> that deal with configuration (chapter 2.11) :</p>
<ul>
<li><strong>Deployer</strong> : &#8220;<em>During Configuration, external dependencies declared by the Application Component Provider are resolved and application assembly instructions defined by the Application Assembler are followed</em>.&#8221;</li>
<li><strong>System Administrator</strong> : &#8220;<em>The System Administrator is responsible for the configuration and administration of the enterprise’s computing and networking infrastructure</em>.&#8221;</li>
</ul>
<p>If you want to read more about configuration of the EE platform I suggest you read chapter 5 of the <a href="http://jcp.org/en/jsr/summary?id=316">Java EE 6 spec</a>.</p>
<h2>How do we configure today ?</h2>
<p>I first need to say that, thanks to Configuration by exception (or Convention over Configuration), you don&#8217;t need to add default configuration to your EE 6 application.  Default behavior and default configuration allows most applications to get the behavior they want most of the time, without the use of either annotations or deployment descriptors. But when we need to configure our application, how do we do it today ? The EE platform has some (optional) <strong>deployment descriptors</strong> you can use such as :</p>
<ul>
<li><tt>web.xml</tt> : you can configure parameters in your servlets with <tt>&lt;context-param&gt;</tt> or filters with  <tt>&lt;init-param&gt;</tt></li>
<li><tt>ejb-jar.xml</tt> : with the <tt>&lt;env-entry&gt;</tt> you can configure your EJBs</li>
<li><tt>application.xml</tt> : here you can configure some application specific information such as the context-root of the web application</li>
<li><tt>persistence.xml</tt> : it&#8217;s typically where you will configure the datasource or database access parameters</li>
<li><tt>application-client.xml</tt>, <tt>ra.xml</tt>, <tt>webservices.xml</tt>&#8230;</li>
</ul>
<p>Usually these files are located under your <tt>WEB-INF</tt> or <tt>META-INF</tt> directory. You can then also use <strong>JNDI</strong> to access this configuration or create your own environment entries in the JNDI tree. Your methods can then access the environment using the JNDI interfaces and lookup methods on component-specific context objects (or with the <tt>@Resource</tt> annotation and the new <tt>lookup</tt> attribute <tt>@Resource(lookup="java:app/env/TheOrderQueue")</tt>). Since Java EE 6 there are several environment namespaces (<tt>java:comp</tt>, <tt>java:module</tt>, <tt>java:app</tt>, <tt>java:global</tt>). So the EE prefered approach are <strong>environement entries</strong> such as this <tt>ejb-jar.xml</tt> file :</p>
<p><pre class="brush: xml;">
&lt;ejb-jar xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; version=&quot;3.2&quot;&gt;
    &lt;enterprise-beans&gt;
        &lt;session&gt;
            &lt;ejb-name&gt;MyEJB&lt;/ejb-name&gt;
            &lt;ejb-class&gt;org.agoncal.MyEJB&lt;/ejb-class&gt;
            &lt;remote&gt;org.agoncal.MyEJBRemote&lt;/remote&gt;
            &lt;session-type&gt;Stateless&lt;/session-type&gt;
            &lt;transaction-type&gt;Container&lt;/transaction-type&gt;
            &lt;resource-ref&gt;
                &lt;res-ref-name&gt;jdbc/employee&lt;/res-ref-name&gt;
                &lt;jndi-name&gt;jdbc/__default&lt;/jndi-name&gt;
            &lt;/resource-ref&gt;
            &lt;env-entry&gt;
                &lt;env-entry-name&gt;aMessage&lt;/env-entry-name&gt;
                &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
                &lt;env-entry-value&gt;Hello World&lt;/env-entry-value&gt;
            &lt;/env-entry&gt;
        &lt;/session&gt;
    &lt;/enterprise-beans&gt;
&lt;/ejb-jar&gt;
</pre></p>
<p><strong>Environment entries are seen as resources</strong> (you can inject them with <tt>@Resource</tt>) and they can be of any type : String, Object, JMS factories &amp; destinations, datasources&#8230; In the code below I inject the datasource called <tt>jdbc/employee</tt> as well as a String called <tt>aMessage</tt> :</p>
<p><pre class="brush: java;">
@Stateless
public class MyEJB {
    @Resource(name=&quot;jdbc/employee&quot;)
    private DataSource employeeDataSource;

    @Resource(name=&quot;aMessage&quot;)
    private String welcomeMessage;
    ...
}
</pre></p>
<p>With CDI, <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">Qualifiers</a> and Producers you could have the following code which makes use of the CDI typesafety :</p>
<p><pre class="brush: java;">
@Stateless
public class MyEJB {
    @Inject @EmployeeDS
    private DataSource employeeDataSource;

    @Inject @AHelloWorldMsg
    private String welcomeMessage;
    ...
}
</pre></p>
<p>With CDI and Alternatives you can then inject an alternative value for <tt>welcomeMessage</tt> or a different datasource for the <tt>employeeDataSource</tt>. Alternatives can then be used to configure your application.</p>
<h2>What&#8217;s missing ?</h2>
<p>JNDI is cool&#8230; but can be of a drag when you use servlet containers such as Tomcat or when you do simple batch processing (you don&#8217;t want to access a remote JNDI tree) or simple Java class. And EE relies a lot on JNDI. If we look at EJBs, the world is changing : it went from a complex component model to a POJO that can run in an embedded container. So let&#8217;s treat it as a POJO.</p>
<p>In the code above, <strong>why do I have to treat the <tt>welcomeMessage</tt> as an environment entry</strong> I should lookup ? Why can&#8217;t I just treat it as a simple String in a POJO which value changes at deployment time? <strong>Datasources, JMS factories&#8230; are container resources, but not a welcome message</strong>. Going futher, if an EJB is a POJO as well as a Servlet a RESTful Web Service or a Managed Bean, why not just configure these component using the same configuration model ?</p>
<p>CDI brings alternatives and the possibility to inject alternative values. But again, why do I have to use <tt>@Produces</tt> (to produce a String for the welcome message), <tt>@Inject</tt>, <tt>@Alternative</tt> and a seperate class that gives me the value of the alternative welcome message, when I just want to configure externally the value of the String ?</p>
<p>What&#8217;s missing in Java EE is a simple way to configure your beans (and by bean I mean EJBs and so on).</p>
<h2>What do we do next ?</h2>
<p><strong>Java EE 7 has started</strong> and we have 18 months to talk about it and make it happen. So why not having a more flexible configuration model in the platform. And because we don&#8217;t want to reinvent the wheel, let&#8217;s get some inspiration from Spring Config, or even better <a href="http://seamframework.org/Seam3/ConfigModule">Seam Config</a> (which makes even XML a bit more type-safe ;o) Taking my previous code example, I would not inject the <tt>welcomeMessage</tt> but just treat it as a simple String :</p>
<p><pre class="brush: java;">
@Stateless
public class MyEJB {
    @Inject @EmployeeDS
    private DataSource employeeDataSource;

    private String welcomeMessage;
    ...
}
</pre></p>
<p>Then, if I want to configure the welcome message the Seam Config way I&#8217;ll have an external XML file (let&#8217;s reuse the <tt>ejb-jar.xml</tt>) and use new namespaces : here the namespace <tt>r</tt> refers to the package <tt>org.agoncal</tt>. So <tt>r:MyEJB</tt> referes to the class <tt>org.agoncal.MyEJB</tt>. So, as you can see  <tt>r:welcomeMessage</tt> refers to the property <tt>org.agoncal.MyEJB.welcomeMessage</tt> in which we set the String <em>Hello World</em> :</p>
<p><pre class="brush: xml; highlight: [20];">
&lt;ejb-jar xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
         xmlns:s=&quot;urn:java:ee:ejb&quot;
         xmlns:r=&quot;urn:java:org.agoncal&quot; version=&quot;3.2&quot;&gt;

    &lt;s:enterprise-beans&gt;
        &lt;s:session&gt;
            &lt;r:MyEJB&gt;
                &lt;s:ejb-name&gt;MyEJB&lt;/s:ejb-name&gt;
                &lt;s:ejb-class&gt;
                    &lt;r:MyEJB/&gt;
                &lt;/s:ejb-class&gt;
                &lt;s:remote&gt;
                    &lt;r:MyEJBRemote/&gt;
                &lt;/s:remote&gt;
                &lt;s:session-type-stateless/&gt;
                &lt;s:transaction-type-container/&gt;
                &lt;r:employeeDataSource&gt;
                    &lt;r:ADifferentEmployeeDSQualifier/&gt;
                &lt;/r:employeeDataSource&gt;
                &lt;r:welcomeMessage&gt;Hello World&lt;/r:welcomeMessage&gt;
            &lt;/r:MyEJB&gt;
        &lt;/s:session&gt;
    &lt;/s:enterprise-beans&gt;
&lt;/ejb-jar&gt;
</pre></p>
<p>The namespace <tt>urn:java:ee:ejb</tt> is EJB Config&#8217;s root namespace (inspired from Seam Config). This is where the built-in elements live. Here I just give a simple (mayby non accurate) example of what configuration could look like, but if you look at <a href="http://docs.jboss.org/seam/3/config/latest/reference/en-US/html_single/">Seam Config</a>, you can configure nearly everything (lists, maps, references&#8230;).</p>
<h2>And going further ?</h2>
<p>Well, if an EJB is a POJO with specific services (transactional, thread safe, secure&#8230;) let&#8217;s consider it like a bean : a Managed Bean with sepecific services. So let&#8217;s declare it in the <tt>beans.xml</tt> (CDI file). Same for all the managed beans. At the moment there are several deployment descriptors. What about having the possibility to have a single one (as well as multiple like today) to configure the entire plaform ? Something like application.xml could be extended, or <tt>beans.xml</tt>.</p>
<p>Java EE 7 is going cloud, so why not use the same way to configure your nodes, instances, platform&#8230; ?</p>
<h2>Let&#8217;s continue this debate</h2>
<p>I&#8217;ve written this blog because I started a <a href="http://java.net/projects/javaee-spec/lists/jsr342-experts/archive/2011-06/message/0">thread</a> on the Java EE 7 <a href="http://java.net/projects/javaee-spec/lists/jsr342-experts/archive">mailing list</a> on configuration. I&#8217;m not an expert on configuration but I can see the benefit of having something similar to <a href="http://docs.jboss.org/seam/3/config/latest/reference/en-US/html_single/">Seam Config</a> in the EE platform. Changing (or upgrading) the way we&#8217;ve been doing configuration throught environment entries is a huge work (look at all the deployment descriptors that we should have to extend). Is it worth it ? Do you care ?</p>
<p>Use this blog to post your comments or the <a href="http://java.net/projects/javaee-spec/lists/jsr342-experts/archive">Java EE 7 mailing list</a>.</p>
<h2>References</h2>
<ul>
<li><a href="http://docs.jboss.org/seam/3/config/latest/reference/en-US/html_single/">Seam Config</a></li>
<li>Former <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java">Spring Java Config</a></li>
<li><a href="http://weblogs.java.net/blog/jjviana/archive/2010/05/18/applicaction-configuration-java-ee-6-using-cdi-simple-example">Applicaction configuration in Java EE 6 using CDI &#8211; a simple example</a></li>
<li><a href="http://download.oracle.com/docs/cd/B31017_01/web.1013/b28221/servjndi008.htm">Configuring an Environment Reference to an Environment Variable</a></li>
<li><a title="Configure your EJB 3 with envirnoment entries using ENC" href="http://agoncal.wordpress.com/2007/09/18/configure-your-ejb-3-with-envirnoment-entries-using-enc/">Configure your EJB 3 with envirnoment entries using ENC</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1079/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1079/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1079/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1079/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1079/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1079/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1079/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1079/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1079&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/06/10/debate-and-what-about-configuration-in-java-ee-7/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>
	</item>
		<item>
		<title>To inject or not to inject: CDI is the question</title>
		<link>http://agoncal.wordpress.com/2011/05/23/to-inject-or-not-to-inject-cdi-is-the-question/</link>
		<comments>http://agoncal.wordpress.com/2011/05/23/to-inject-or-not-to-inject-cdi-is-the-question/#comments</comments>
		<pubDate>Mon, 23 May 2011 14:45:34 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cdi]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1058</guid>
		<description><![CDATA[Two weeks ago I did a little tour around several JUGs and conferences to talk about dependency injections with CDI. The final goal of this road movie was to end up at GeeCon in Krakow. It was my second time at GeeCon and I have to say that this conference is like good wine : [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1058&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Two weeks ago I did a <a title="A week in central Europe… with CDI" href="http://agoncal.wordpress.com/2011/05/02/a-week-in-central-europe-with-cdi/">little tour around several JUGs and conferences</a> to talk about dependency inject<a href="http://www.geecon.org"><img class="alignright size-full wp-image-1075" title="GeeCon" src="http://agoncal.files.wordpress.com/2011/05/geecon.jpg?w=468" alt=""   /></a>ions with CDI. The final goal of this road movie was to end up at <a href="http://www.geecon.org">GeeCon</a> in <a href="http://www.krakow.pl/english/">Krakow</a>. It was my <a title="GeeCon is over, long live GeeCon" href="http://agoncal.wordpress.com/2009/05/13/geecon-is-over-long-live-geecon/">second time at GeeCon</a> and I have to say that this conference is like good wine : <strong>getting better with age</strong>. This community based conference is on its third edition and attracts people through out central and eastern Europe. Plenty of <a href="http://2011.geecon.org/main/speakers">good speakers</a>, nice location, skilled attendees&#8230; and a lot of fun (GeeCon organizers are party addicts). So make sure you mark this conference into your agenda for next year.</p>
<p>In the meantime, I have made my slides available. Enjoy and do not hesitate to send me some feedback.</p>
<iframe src='http://www.slideshare.net/slideshow/embed_code/8060552' width='490' height='402'></iframe>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1058/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1058/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1058/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1058/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1058/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1058/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1058/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1058/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1058&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/05/23/to-inject-or-not-to-inject-cdi-is-the-question/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/05/geecon.jpg" medium="image">
			<media:title type="html">GeeCon</media:title>
		</media:content>
	</item>
		<item>
		<title>Injection with CDI (Part II)</title>
		<link>http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/</link>
		<comments>http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/#comments</comments>
		<pubDate>Tue, 03 May 2011 11:54:08 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cdi]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=1015</guid>
		<description><![CDATA[This is the second post based on pure CDI Injection (see Part I) after having talked about how to bootstrap CDI in several environments and how to add CDI to an existing Java EE 6 application. In this post I quickly want to show the different injection points in CDI : field, constructor and setter. To [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1015&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionII.zip"><img class="size-full wp-image-652 alignleft" title="Download the code" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a>This is the second post based on pure CDI Injection (see <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">Part I</a>) after having talked about how to <a title="Bootstrapping CDI in several environments" href="http://agoncal.wordpress.com/2011/01/12/bootstrapping-cdi-in-several-environments/">bootstrap CDI in several environments</a> and how to <a title="Adding CDI to an existing Java EE 6 application" href="http://agoncal.wordpress.com/2011/02/07/adding-cdi-to-an-existing-java-ee-6-application/">add CDI to an existing Java EE 6 application</a>. In this post I quickly want to show the different injection points in CDI : <strong>field, constructor and setter</strong>. To illustrate these different injection points I&#8217;ll use a subset of the <a title="Injection with CDI (Part I)" href="http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/">previous example</a> : <strong>a servlet injecting an ISBN generator POJO</strong> :</p>
<p><a href="http://agoncal.files.wordpress.com/2011/05/cdiinjectionii.png"><img class="aligncenter size-full wp-image-1036" title="cdiinjectionII" src="http://agoncal.files.wordpress.com/2011/05/cdiinjectionii.png?w=468" alt=""   /></a></p>
<h1>Field injection</h1>
<p>Until now, in all the previous posts, you&#8217;ve seen the <tt>@Inject</tt> annotation put on fields (attributes).</p>
<p><pre class="brush: java; highlight: [4,8];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    @Inject
    @ThirteenDigits
    private NumberGenerator numberGenerator;

    @Inject
    private ItemEJB itemEJB;
    ...
}
</pre></p>
<p>As you can see in the code above, the <tt>@Inject</tt> and the qualifiers (here <tt>@ThirteenDigits</tt>) annotate an attribute. But like many other injection frameworks, in CDI you can also have constructor and setter injection.</p>
<h1>Constructor injection</h1>
<p>Instead of annotating the attributes, you can add the <tt>@Inject</tt> annotation on a constructor. If you then need to use qualifiers, you can add them to the attributes of the constructor as follow :</p>
<p><pre class="brush: java; highlight: [7,8];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    private NumberGenerator numberGenerator;
    private ItemEJB itemEJB;

    @Inject
    public ItemServlet(@ThirteenDigits NumberGenerator numberGenerator, ItemEJB itemEJB) {
        this.numberGenerator = numberGenerator;
        this.itemEJB = itemEJB;
    }
    ...
}
</pre></p>
<p>As you can see, the <tt>@Inject</tt> is not on the field but on the constructor. On the other hand, <tt>@ThirteenDigits</tt> doesn&#8217;t qualify the constructor but the <tt>numberGenerator</tt> parameter itself (which is logical). You can also mix field and constructor injection if you want (below I use constructor injection and attribute injection on the EJB) :</p>
<p><pre class="brush: java; highlight: [6,9];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    private NumberGenerator numberGenerator;

    @Inject
    private ItemEJB itemEJB;

    @Inject
    public ItemServlet(@ThirteenDigits NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }
    ...
}
</pre></p>
<p>But the rule is : <strong>you can only have one constructor injection point</strong>. The container is the one doing injection, not you (you can&#8217;t invoke a constructor in a managed environment, well, you can, but it will not work as you expect). There is only one bean constructor allowed so the container can do its job of injecting the right references. <strong>The following is invalid</strong> :</p>
<p><pre class="brush: java; highlight: [7,13];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    private NumberGenerator numberGenerator;
    private ItemEJB itemEJB;

    @Inject
    public ItemServlet(@ThirteenDigits NumberGenerator numberGenerator, ItemEJB itemEJB) {
        this.numberGenerator = numberGenerator;
        this.itemEJB = itemEJB;
    }

    @Inject
    public ItemServlet(@ThirteenDigits NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }
	...
}
</pre></p>
<p>If you have more than one bean constuctor, this is what you get (the error code and message is <a href="http://seamframework.org/Weld">Weld</a> specific of course) :</p>
<p><pre class="brush: plain; gutter: false;">
WELD-000812 Cannot determine constructor to use for public@WebServlet class ItemServlet. Possible constructors [[constructor] @Inject public ItemServlet(NumberGenerator, ItemEJB), [constructor] @Inject public ItemServlet(NumberGenerator)]
</pre></p>
<p>On the other hand, it is syntactically legal to have field and constructor injection at the same time (but useless) :</p>
<p><pre class="brush: java; highlight: [4,6,9];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    @Inject @ThirteenDigits
    private NumberGenerator numberGenerator;
    @Inject
    private ItemEJB itemEJB;

    @Inject
    public ItemServlet(@ThirteenDigits NumberGenerator numberGenerator, ItemEJB itemEJB) {
        this.numberGenerator = numberGenerator;
        this.itemEJB = itemEJB;
    }
    ...
}
</pre></p>
<h1>Setter injection</h1>
<p>The other choice is to use setter injection which looks like constructor injection. You annotate the setter with <tt>@Inject</tt> and you qualify the parameters :</p>
<p><pre class="brush: java; highlight: [7,8,12];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    private NumberGenerator numberGenerator;
    private ItemEJB itemEJB;

    @Inject
    public void setNumberGenerator(@ThirteenDigits NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Inject
    public void setItemEJB(ItemEJB itemEJB) {
        this.itemEJB = itemEJB;
    }
    ...
}
</pre></p>
<p>When you use constructor or setter injection you need to apply your qualifiers to a parameter. So make sure you have the right <tt>@Targets</tt> (<tt>java.lang.annotation.ElementType.PARAMETER</tt>) definition :</p>
<p><pre class="brush: java; highlight: [3];">
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD, PARAMETER})
public @interface ThirteenDigits {
}
</pre></p>
<h1>Conclusion</h1>
<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionII.zip"><img class="alignright size-full wp-image-652" title="Download the code" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a>One question you could ask (and that&#8217;s the one <a href="http://twitter.com/#!/agoncal/status/65166255216279553">I asked</a> to <a href="http://twitter.com/#!/plmuir/status/65196933928595456">Pete Muir</a>) is : &#8220;when do you use field over constructor or setter injection ?&#8221;. There is no real technical answer except that it&#8217;s your personal taste. In a managed environment, the container is the one doing all the injection work, it just needs the right injection points. However, with constructor or setter injection you can add some logic if needed (not with field injection). But it looks like setter injection was added for <a href="http://twitter.com/#!/plmuir/statuses/65497453637550080">backward compatibility with existing Java Beans</a>.</p>
<p>The next article will cover <strong>producers</strong>, so stay tuned.</p>
<h1>Download</h1>
<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionII.zip">Download the code</a>, give it a try, and give me some feedback.</p>
<h1>References</h1>
<ul>
<li><a href="http://docs.jboss.org/weld/reference/latest/en-US/html_single/">Weld &#8211; JSR-299 Reference Implementation</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/1015/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/1015/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/1015/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/1015/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/1015/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/1015/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/1015/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/1015/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=1015&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">Download the code</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/05/cdiinjectionii.png" medium="image">
			<media:title type="html">cdiinjectionII</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">Download the code</media:title>
		</media:content>
	</item>
		<item>
		<title>A week in central Europe… with CDI</title>
		<link>http://agoncal.wordpress.com/2011/05/02/a-week-in-central-europe-with-cdi/</link>
		<comments>http://agoncal.wordpress.com/2011/05/02/a-week-in-central-europe-with-cdi/#comments</comments>
		<pubDate>Mon, 02 May 2011 12:24:02 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[conference]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=926</guid>
		<description><![CDATA[I haven&#8217;t talked much lately at conferences or JUGs. The last one was Devoxx in November 2010 and I have been quite ever since (working on some other plans ;o) But it&#8217;s time to do a bit of touring again. This time it will be Central Europe and the topic with injection in CDI. The presentation of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=926&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>I haven&#8217;t talked much lately at conferences</strong> or JUGs. The last one was <a href="http://www.devoxx.com/display/Devoxx2K10/Home">Devoxx</a> in November 2010 and I have been quite ever since (working on some other plans ;o) But it&#8217;s time to do a bit of <strong>touring again</strong>. This time it will be Central Europe and <strong>the topic with injection in <a href="http://jcp.org/en/jsr/summary?id=299">CDI</a></strong>. The presentation of the talk is <strong><em>To inject or not to inject: CDI is the question</em></strong> and the description roughly is :</p>
<blockquote><p>After a quick introduction of CDI (Contexts and Dependency Injection) I will concentrate on dependency injection and the type-safe approach on injection in CDI. If you are fed up of using String based configuration, come to this talk and have a type-safe journey on CDI.</p></blockquote>
<p>How come I am touring again ? Everything started with an invitation from my friends at <a href="http://2011.geecon.org/main/home">GeeCon</a>. I discovered <a href="http://2009.geecon.org/">GeeCon in 2009</a>. It was the first edition of this conference in Cracow (Poland) created by the local user group. As I mentioned <a title="GeeCon is over, long live GeeCon" href="http://agoncal.wordpress.com/2009/05/13/geecon-is-over-long-live-geecon/">in my post</a>, I really liked the conference as it felt very professional with good speakers and nice atmosphere. So this year I&#8217;ve accepted the invitation and I&#8217;m going back to the 2011 edition to talk about injection in CDI&#8230;. and on my way, I&#8217;ve decided to have some stop-overs :</p>
<ul>
<li>Monday 9th of May &#8211; come on listen to my talk at the <a href="http://java.net/projects/jugc/pages/Home">JUG Cologne</a> in <strong>Germany</strong> (<a href="http://maps.google.fr/maps?ie=UTF8&amp;q=google+maps+PROKODA+GmbH,+Stolberger+Str.+309,+50933+K%C3%B6ln,+Deutschland&amp;fb=1&amp;gl=fr&amp;hq=PROKODA+GmbH,&amp;hnear=Stolberger+Stra%C3%9Fe+309,+D-50933+K%C3%B6ln,+Germany&amp;cid=0,0,15735733614697997414&amp;z=16">Map</a>)</li>
<li>Tuesday 10th of May &#8211; <a href="http://www.java.cz/article/czjug">CZJUG</a> (Prague &#8211; <strong>Czech Republic</strong>) : it&#8217;s going to be a busy day. I&#8217;ll spend the day at the EMEA Oracle User Group (<a href="http://maps.google.fr/maps?ie=UTF8&amp;q=Radisson+Blu,+Stepanska+40,+110+00+Prague&amp;fb=1&amp;gl=fr&amp;hq=Radisson+Blu,&amp;hnear=%C5%A0t%C4%9Bp%C3%A1nsk%C3%A1+624%2F40,+110+00+Praha-Nov%C3%A9+M%C4%9Bsto,+R%C3%A9publique+Tch%C3%A8que&amp;cid=0,0,478559369422589852&amp;z=16&amp;iwloc=A">Map</a>) and then go to the JUG to do my talk at 7pm (<a href="http://maps.google.fr/maps?f=q&amp;source=s_q&amp;hl=fr&amp;geocode=&amp;q=Malostransk%C3%A9m+n%C3%A1m.+25+Prague&amp;aq=&amp;sll=50.079908,14.426446&amp;sspn=0.021784,0.038581&amp;gl=fr&amp;ie=UTF8&amp;hq=&amp;hnear=Malostransk%C3%A9+n%C3%A1m%C4%9Bst%C3%AD+2%2F25,+118+00+Praha-Mal%C3%A1+Strana,+R%C3%A9publique+Tch%C3%A8que&amp;ll=50.088181,14.403205&amp;spn=0.011234,0.01929&amp;z=16">Map</a>).</li>
<li>Wednesday 11th of May &#8211; <a href="http://2011.geecon.org/site/schedule">GeeCon</a> (Cracow &#8211; <strong>Poland</strong>) : I&#8217;ll be doing a Java EE 6 university talk with my friend <a href="http://blogs.sun.com/alexismp/">Alexis Moussine-Pouchkine</a>. It will be the same talk we did at Devoxx last year, but updated of course</li>
<li>Thursday 12th of May - <a href="http://2011.geecon.org/site/conf_day_1">GeeCon</a> (<a href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;q=Dobrego+Pasterza+128,+dzielnica+XV+Mistrzejowice+31-358+Krak%C3%B3w,+Ma%C5%82opolskie,+Poland&amp;aq=&amp;sll=37.0625,-95.677068&amp;sspn=47.215051,83.056641&amp;ie=UTF8&amp;geocode=FahM_AIdE_IwAQ&amp;split=0&amp;hq=&amp;hnear=Dobrego+Pasterza+128,+Krak%C3%B3w,+Ma%C5%82opolskie,+Poland&amp;ll=50.089117,19.984903&amp;spn=0.018806,0.040555&amp;z=15">Map</a>) I&#8217;ll do my CDI talk</li>
<li>On Friday I will have fun and a relaxing time in Cracow (it is such a nice city)</li>
<li>Then I&#8217;ll visit some friends in Venice (<strong>Italy</strong>) and stay during the week-end (not talking about Java at all, drinking wine and eating pasta)</li>
<li>&#8230; and then back home</li>
</ul>
<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps/ms?ie=UTF8&amp;hl=en&amp;msa=0&amp;msid=206814731761431156908.0004a1fe5be88d22930e7&amp;ll=48.189814,11.125974&amp;spn=5.501755,17.632199&amp;output=embed"></iframe><br /><small><a href="http://maps.google.com/maps/ms?ie=UTF8&amp;hl=en&amp;msa=0&amp;msid=206814731761431156908.0004a1fe5be88d22930e7&amp;ll=48.189814,11.125974&amp;spn=5.501755,17.632199&amp;source=embed" style="text-align:left">View Larger Map</a></small>
<p>I&#8217;ll be doing all these trips using my favorite transport : night trains. So if you are anywhere near and want to attend one of my talks&#8230; of just have a beer, fill free to come.</p>
<p>See you</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/926/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/926/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/926/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/926/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/926/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/926/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/926/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/926/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=926&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/05/02/a-week-in-central-europe-with-cdi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>
	</item>
		<item>
		<title>Formation Java EE 6 en juin à Paris</title>
		<link>http://agoncal.wordpress.com/2011/04/26/formation-java-ee-6-en-juin-a-paris/</link>
		<comments>http://agoncal.wordpress.com/2011/04/26/formation-java-ee-6-en-juin-a-paris/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 12:48:49 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=975</guid>
		<description><![CDATA[Vos avez un nouveau projet dans les tuyaux ? Vous vous questionnez sur les frameworks à choisir ? Vous hésitez à utiliser votre framework printanier à base d&#8217;XML et de complexité ? Vous voulez migrer votre application vers un standard ? Vous détestez les EJBs ? J&#8217;ai ce qu&#8217;il vous faut : une formation de 3 jours autour de [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=975&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://training.xebia.fr/formations-java-jee/formation-architectures-aujourdhui-java-ee-antonio-goncalves/"><img class="size-full wp-image-986 alignright" title="Formation Java EE 6 chez Xebia" src="http://agoncal.files.wordpress.com/2011/04/logo-xebia2.jpg?w=468" alt="Xebia" /></a>Vos avez un nouveau projet dans les tuyaux ? Vous vous questionnez sur les frameworks à choisir ? Vous hésitez à utiliser votre framework printanier à base d&#8217;XML et de complexité ? Vous voulez migrer votre application vers un standard ? Vous détestez les EJBs ? J&#8217;ai ce qu&#8217;il vous faut : <strong>une formation de 3 jours</strong> autour de <strong>Java EE 6</strong> intitulée <a href="http://training.xebia.fr/formations-java-jee/formation-architectures-aujourdhui-java-ee-antonio-goncalves/">Architectures d’aujourd’hui avec Java EE 6</a>.</p>
<p><a href="http://www.jetbrains.com/idea/"><img class="size-full wp-image-988 alignleft" title="Intellij Idea" src="http://agoncal.files.wordpress.com/2011/04/intellijidea-logo.png?w=468" alt=""   /></a>Cette formation a été créé par mes soins, s&#8217;inspire de <a href="http://www.antoniogoncalves.org/xwiki/bin/view/Book/JavaEE6">mon livre</a> et a pour objectif de démystifier la nouvelle plate-forme Java EE. Elle allie présentations et séances de développement (<a href="http://maven.apache.org">Maven</a>, <a href="http://glassfish.java.net/">GlassFish</a>, <a href="http://www.jetbrains.com/idea/">Intellij Idea</a>, <a href="http://www.zeroturnaround.com/jrebel/">JRebel</a>) en mettant l’accent sur les bonnes pratiques d’architectures. Patterns d’hier devenus anti-patterns aujourd’hui, course au découplage, sur-découpage en couches… vous apprendrez à utiliser les briques techniques de Java EE 6 (<strong>JPA 2.0, EJB 3.1, JSF 2.0, Bean Validation 1.0, CDI 1.0 et JAX-RS 1.0</strong>) pour répondre au mieux aux besoins de vos utilisateurs.</p>
<p><img class="size-full wp-image-987 alignright" title="JRebel" src="http://agoncal.files.wordpress.com/2011/04/logo_jrebel.png?w=468" alt=""   /><br />
Et comme goodies vous aurez <strong>un exemplaire de mon livre</strong>, <strong>une licence d&#8217;Intellij Idea</strong> ainsi qu&#8217;une <strong>licence <strong>JRebel </strong>de 6 semaines</strong>, c&#8217;est pas beau ça ?!?!</p>
<p>La prochaine formation aura lieu chez <strong><a href="http://training.xebia.fr/formations-java-jee/formation-architectures-aujourdhui-java-ee-antonio-goncalves/">Xebia du 6 au 8 juin</a></strong>, alors n&#8217;hésitez pas à vous <a href="http://training.xebia.fr/wp-content/uploads/bon-de-commande.pdf">inscrire</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/975/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/975/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/975/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=975&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/04/26/formation-java-ee-6-en-juin-a-paris/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/04/logo-xebia2.jpg" medium="image">
			<media:title type="html">Formation Java EE 6 chez Xebia</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/04/intellijidea-logo.png" medium="image">
			<media:title type="html">Intellij Idea</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/04/logo_jrebel.png" medium="image">
			<media:title type="html">JRebel</media:title>
		</media:content>
	</item>
		<item>
		<title>Injection with CDI (Part I)</title>
		<link>http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/</link>
		<comments>http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 15:34:14 +0000</pubDate>
		<dc:creator>agoncal</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cdi]]></category>

		<guid isPermaLink="false">http://agoncal.wordpress.com/?p=846</guid>
		<description><![CDATA[After writing a post about how to bootstrap CDI in your environment and giving you some tips about how to incorporate CDI in an existing Java EE 6 application, I want to talk about injection. Yes, pure injection or how to inject a bean into another one. As you&#8217;ll see in this series of three articles (Part II), [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=846&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionI.zip"><img class="alignleft size-full wp-image-652" title="download" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a> After writing a post about how to <a title="Bootstrapping CDI in several environments" href="http://agoncal.wordpress.com/2011/01/12/bootstrapping-cdi-in-several-environments/">bootstrap CDI</a> in your environment and giving you some tips about <a title="Adding CDI to an existing Java EE 6 application" href="http://agoncal.wordpress.com/2011/02/07/adding-cdi-to-an-existing-java-ee-6-application/">how to incorporate CDI in an existing Java EE 6 application</a>, I want to talk about injection. Yes, pure injection or <strong>how to inject a bean into another one</strong>. As you&#8217;ll see in this series of <strong>three articles </strong>(<a title="Injection with CDI (Part II)" href="http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/">Part II</a>), many different cases can happen. Let&#8217;s start with a simple one : a straight forward injection.</p>
<h1>Default injection</h1>
<p>The simplest possible injection case is&#8230; simple. You have <em>something</em>, and you inject <em>something</em> into it. Why am I using the word <em>something </em>? Because until Java EE 5 we could only inject resources (EntityManager, Datasource, JMS destinations and factories&#8230;) into certain components (EJBs and Servlets). With CDI, you can <strong>inject nearly anything into anything else</strong>.</p>
<blockquote><p><span style="text-decoration:underline;">Versions of software used for this arcticle</span><br />
Java SE 1.6.0_23<br />
GlassFish 3.1<br />
Maven 3.0.2</p></blockquote>
<p>To illustrate injection I&#8217;ll be using the same use case I&#8217;ve used in <a title="Adding CDI to an existing Java EE 6 application" href="http://agoncal.wordpress.com/2011/02/07/adding-cdi-to-an-existing-java-ee-6-application/">previous articles</a> or in my <a href="http://www.antoniogoncalves.org/xwiki/bin/view/Book/JavaEE6">Java EE 6 book</a> : a CD-Book store.</p>
<p style="text-align:center;"><a href="http://agoncal.files.wordpress.com/2011/04/cdiinjection01.gif"><img class="aligncenter size-full wp-image-901" title="Default injection" src="http://agoncal.files.wordpress.com/2011/04/cdiinjection01.gif?w=468" alt=""   /></a></p>
<p>The class diagram above shows the following components :</p>
<ul>
<li><tt>Book</tt> is just an Entity with some attributes and named queries</li>
<li><tt>ItemEJB</tt> is a stateless EJB (with no interface) doing CRUD operations on the <tt>Book</tt> thanks to the <tt>EntityManager</tt></li>
<li><tt>IsbnGenerator</tt> is just a POJO that generates a random ISBN number (used for the <tt>Book</tt>)</li>
<li><tt>ItemRestService</tt> is annotated with <tt>@Path</tt> (which designates a REST web service in JAX-RS) and delegates the CRUD operation to the <tt>ItemEJB</tt></li>
<li><tt>ItemServlet</tt> is a Servlet that uses the <tt>ItemEJB</tt> to display all the books from the database</li>
</ul>
<p>As you can see, except for the <tt>EntityManager</tt> that is injected with <tt>@PersistenceContext</tt>, all the other components use <tt>@Inject</tt>. Here is a few lines of code of the <tt>ItemEJB</tt> getting a reference of the <tt>EntityManager</tt> :</p>
<p><pre class="brush: java; highlight: [4];">
@Stateless
public class ItemEJB {

    @PersistenceContext(unitName = &quot;cdiPU&quot;)
    private EntityManager em;
    ...
}
</pre></p>
<p>The <tt>ItemServlet</tt> and the <tt>ItemRestService</tt> are very similar as they both inject a reference of the <tt>ItemEJB</tt> and the <tt>IsbnGenerator</tt> :</p>
<p><pre class="brush: java; highlight: [4,7];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    @Inject
    private IsbnGenerator numberGenerator;

    @Inject
    private ItemEJB itemEJB;
    ...
}
</pre></p>
<p>And the <tt>IsbnGenertor</tt> has absolutely nothing special to it as it doesn&#8217;t extends from anything nor it is annotated, it&#8217;s just a POJO :</p>
<p><pre class="brush: java;">
public class IsbnGenerator {

    public String generateNumber () {
        return &quot;13-84356-&quot; + Math.abs(new Random().nextInt());
    }
}
</pre></p>
<p>In all these cases there is only one implementation to choose from (there is only <tt>ItemEJB</tt>, only one <tt>IsbnGenerator</tt>). If you only have one implementation, CDI will be able to inject it. We then talk about <strong>default injection</strong>. In fact, the code :</p>
<p><pre class="brush: java; gutter: false;">
@Inject IsbnGenerator numberGenerator
</pre></p>
<p>could have been written</p>
<p><pre class="brush: java; gutter: false;">
@Inject @Default IsbnGenerator numberGenerator
</pre></p>
<p><tt>@Default</tt> is a built in <strong>qualifier</strong> that informs CDI to inject the default bean implementation. If you define a bean with no qualifier, the bean automatically has the qualifier <tt>@Default</tt>. The following code is identical to the previous one.</p>
<p><pre class="brush: java; highlight: [4,9];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    @Inject @Default
    private IsbnGenerator numberGenerator;
    ...
}

@Default
public class IsbnGenerator {

    public String generateNumber () {
        return &quot;13-84356-&quot; + Math.abs(new Random().nextInt());
    }
}
</pre></p>
<p>If you only have one implementation of the <tt>IsbnGenerator</tt> to inject, the default behaviour applies and a straight forward <tt>@Inject</tt> does the job. But sometimes you have to choose between several implementations, that&#8217;s where <strong>qualifiers </strong>come into play.</p>
<blockquote><p>In this article I use the term <em>bean</em>, but to be more precise I should say <em>managed bean</em> (ie <em>beans that are managed by CDI</em>). <a href="/aboutJava/communityprocess/final/jsr316/index.html">ManagedBeans</a> have been introduced in Java EE 6.</p></blockquote>
<h1>Ambiguous injection &amp; Qualifiers</h1>
<p>For a given bean type, there may be <strong>multiple beans which implement the type</strong>. For example, our application can have two implementations of the <tt>NumberGenerator</tt> interface : <tt>IsbnGenerator</tt> generates a 13 digits number and <tt>IssnGenerator</tt> a 8 digits number. A component that needs to generate a 13 digits number needs some way to distinguish between the two implementations. One approach would be to explicitly specify the class (<tt>IsbnGenerator</tt>) but that creates a hard dependence between the component and the implementation. Another approach would be to rely on external XML configuration to declare and inject the appropriate bean. CDI uses qualifiers, which are annotations, to get <strong>strong typing and loose coupling</strong>.</p>
<blockquote><p>In this article I&#8217;m using injection on the attribute, meaning that the <tt>@Inject</tt> annotation is on the attribute. But with CDI you can also use setter injection or constructor injection.</p></blockquote>
<p>Let&#8217;s say, for some reason, that the <tt>ItemServlet</tt> creates books with a 13 digits ISBN number, and the <tt>ItemRestService</tt> creates books with a 8 digits ISSN number. Both (the <tt>ItemServlet</tt> and the <tt>ItemRestService</tt>) inject a reference of the same <tt>NumberGenerator</tt> interface, which implementation will there use ? You don&#8217;t know ? CDI doesn&#8217;t know either, and this is the kind of error message you will get :</p>
<p><pre class="brush: plain; gutter: false;">
Ambiguous dependencies for type [NumberGenerator] with qualifiers [@Default] at injection point [[field] @Inject private ItemRestService.numberGenerator]. Possible dependencies [[Managed Bean [class IsbnGenerator] with qualifiers [@Any @Default], Managed Bean [class IssnGenerator] with qualifiers [@Any @Default]]].
</pre></p>
<p>That means we need to be less ambiguous and tell CDI which bean to inject where. If you come from Spring the first thing that comes to your mind is &#8220;<em>let&#8217;s use the beans.xml file</em>&#8220;. But as <a href="http://seamframework.org/Documentation/WhatIsBeansxmlAndWhyDoINeedIt">this post says</a>, &#8220;<em>beans.xml is not there to define beans in XML</em>&#8220;. With CDI you use qualifiers (annotations).</p>
<blockquote><p>There are <a href="http://docs.jboss.org/cdi/spec/1.0/html_single/#builtinqualifiers">three built-in qualifiers</a> in CDI :</p>
<ul>
<li><tt>@Default</tt> : If a bean does not explicitly declare a qualifier, the bean has a <tt>@Default</tt> qualifier</li>
<li><tt>@Any</tt> : allows the application to specify qualifiers dynamically</li>
<li><tt>@New</tt> : allows the application to obtain a new qualified bean</li>
</ul>
</blockquote>
<p>A qualifier represents some semantic associated with a type that is satisfied by some implementations of the type. For example, you could introduce qualifiers to represent <em>thirteen digits number generator</em> or <em>eight digits number generator</em>. In Java qualifiers are represented by annotations defined as <tt>@Target({FIELD, TYPE, METHOD})</tt> and <tt>@Retention(RUNTIME)</tt>. It is declared by specifying the <tt>@javax.inject.Qualifier</tt> meta-annotation as follow :</p>
<p><pre class="brush: java; highlight: [1,4,7,10];">
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface EightDigits {
}

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface ThirteenDigits {
}
</pre></p>
<p>As you can see, I&#8217;ve just defined two qualifiers, very easily. Right, so how do I use them now ? Better than words, a class diagram will make it clear.</p>
<p style="text-align:center;"><a href="http://agoncal.files.wordpress.com/2011/04/cdiinjection02.gif"><img class="aligncenter size-full wp-image-902" title="Injection wih qualifiers" src="http://agoncal.files.wordpress.com/2011/04/cdiinjection02.gif?w=468" alt=""   /></a></p>
<p>First of all, the qualifiers need to be applied on the appropriate implementation. As you can see, <tt>@ThirteenDigits</tt> is applied to <tt>IsbnGenerator</tt> and <tt>@EightDigits</tt> to <tt>@IssnGenerator</tt> :</p>
<p><pre class="brush: java; highlight: [1,9];">
@EightDigits
public class IssnGenerator implements NumberGenerator {

    public String generateNumber() {
        return &quot;8-&quot; + Math.abs(new Random().nextInt());
    }
}

@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {

    public String generateNumber() {
        return &quot;13-84356-&quot; + Math.abs(new Random().nextInt());
    }
}
</pre></p>
<p>Then, the components that inject a reference to the <tt>NumberGenerator</tt> interface also need to use it as follow :</p>
<p><pre class="brush: java; highlight: [4,13];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    @Inject @ThirteenDigits
    private NumberGenerator numberGenerator;
    ...
}

@Path(&quot;/items&quot;)
@ManagedBean
public class ItemRestService {

    @Inject @EightDigits
    private NumberGenerator numberGenerator;
    ...
}
</pre></p>
<p>You don&#8217;t need external configuration, that&#8217;s why CDI is said to use strong typing. You can rename your implementations to whatever you want, the injection point will not change (that&#8217;s loose coupling). Note that a bean may declare multiple qualifiers. As you can see, CDI is an elegant way to have typesafe injection. But if you start creating annotations each time you need to inject something, your application will end up being very verbose. That&#8217;s when enumerations can help you.</p>
<h1>Qualifiers with enumerations</h1>
<p>Each time you need to choose between implementation you create an annotation. So if you need an extra <em>two digits number generator</em> or a <em>ten digits number generator</em> you create more and more annotations. Looks like we are moving from XML Hell to Annotation Hell ! One way to avoid the multiplication of annotations is to use enumeration as follow :</p>
<p><pre class="brush: java; highlight: [4,13,18,26];">
@WebServlet(urlPatterns = &quot;/itemServlet&quot;)
public class ItemServlet extends HttpServlet {

    @Inject @NumberOfDigits(Digits.THIRTEEN)
    private NumberGenerator numberGenerator;
    ...
}

@Path(&quot;/items&quot;)
@ManagedBean
public class ItemRestService {

    @Inject @NumberOfDigits(Digits.EIGHT)
    private NumberGenerator numberGenerator;
    ...
}

@NumberOfDigits(Digits.THIRTEEN)
public class IsbnGenerator implements NumberGenerator {

    public String generateNumber() {
        return &quot;13-84356-&quot; + Math.abs(new Random().nextInt());
    }
}

@NumberOfDigits(Digits.EIGHT)
public class IssnGenerator implements NumberGenerator {

    public String generateNumber() {
        return &quot;8-&quot; + Math.abs(new Random().nextInt());
    }
}</pre></p>
<p>As you can see I got rid of the <tt>@ThirteenDigits</tt> and <tt>@EightDigits</tt> qualifiers and I&#8217;m using the single qualifier <tt>@NumberOfDigits</tt> which as an enumerations as a value (in my example <tt>@EightDigits</tt>). This is the code you need to write :</p>
<p><pre class="brush: java; highlight: [4,8];">
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface NumberOfDigits {
    Digits value();
}

public enum Digits {
    TWO,
    EIGHT,
    TEN,
    THIRTEEN
}
</pre></p>
<h1>Conclusion</h1>
<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionI.zip"><img class="alignright size-full wp-image-652" title="download" src="http://agoncal.files.wordpress.com/2010/05/download.gif?w=468" alt=""   /></a> I don&#8217;t know about you, but I love it. I really like the way CDI wires beans together <strong>without XML</strong>, just with pure Java in a <strong>type-safe way</strong>. Ok, ok, I admit, not everything is beautiful. The first thing I see is the <strong>multiplication of annotations</strong> in your code. Thanks to enumerations, this can be limited. The other point I can see is the <strong>IDE support</strong>. Your IDE needs to be cleaver to know that :</p>
<p><pre class="brush: java; gutter: false;">
@Inject @NumberOfDigits(Digits.EIGHT) NumberGenerator numberGenerator
</pre></p>
<p>refers to <tt>IssnGenerator</tt>. But here I&#8217;m talking without really knowing much about the topic. I use <a href="http://www.jetbrains.com/idea/">Intellij IDEA</a> and the CDI support is just amazing. I can navigate from bean to bean without worrying about knowing the implementation. I suppose NetBeans might have some kind of support&#8230; but I wonder if Eclipse does ;o)</p>
<p>The next article will cover <strong><a title="Injection with CDI (Part II)" href="http://agoncal.wordpress.com/2011/05/03/injection-with-cdi-part-ii/">the different available injection points</a></strong>, so stay tuned.</p>
<h1>Download</h1>
<p><a href="http://www.antoniogoncalves.org/xwiki/bin/download/Main/Attach/CDIInjectionI.zip">Download the code</a>, give it a try, and give me some feedback.</p>
<h1>References</h1>
<ul>
<li><a href="http://www.warski.org/blog/?p=151">Dependency Injection and replacing dependencies in CDI/Weld</a></li>
<li><a href="http://blogs.sun.com/arungupta/entry/totd_144_cdi_produces_for">TOTD #144: CDI @Produces for container-managed @Resource</a></li>
<li><a href="http://docs.jboss.org/weld/reference/latest/en-US/html_single/">Weld &#8211; JSR-299 Reference Implementation</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/agoncal.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/agoncal.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/agoncal.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/agoncal.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/agoncal.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/agoncal.wordpress.com/846/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/agoncal.wordpress.com/846/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/agoncal.wordpress.com/846/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=agoncal.wordpress.com&amp;blog=7143934&amp;post=846&amp;subd=agoncal&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://agoncal.wordpress.com/2011/04/07/injection-with-cdi-part-i/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1fc6aa04011b2f0f9721df913b0fd415?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">agoncal</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">download</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/04/cdiinjection01.gif" medium="image">
			<media:title type="html">Default injection</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2011/04/cdiinjection02.gif" medium="image">
			<media:title type="html">Injection wih qualifiers</media:title>
		</media:content>

		<media:content url="http://agoncal.files.wordpress.com/2010/05/download.gif" medium="image">
			<media:title type="html">download</media:title>
		</media:content>
	</item>
	</channel>
</rss>

