title: Why use CDI in Java EE
body: <p>I know there are a lot of articles out there that explain how to use CDI in Java EE but I'm having trouble figuring out what advantage this actually brings. For example, suppose I have a class that currently uses an instance of Foo. I might either do</p>
  
  <pre><code>Foo myFoo = new Foo();
  </code></pre>
  
  <p>or </p>
  
  <pre><code>// Better, FooFactory might return a mock object for testing    
  Foo myFoo = FooFactory.getFoo();
  </code></pre>
  
  <p>I keep reading that with CDI I can do:</p>
  
  <pre><code>@Inject
  Foo myFoo;
  </code></pre>
  
  <p>but why is this better than the previous factory based approach? I assume there is some other use case that I'm not aware of but I haven't been able to identify this. </p>
  
  <p>If I've understood the responses below, the concept is that the DI framework acts as a master object factory that is configured centrally. Is this a reasonable interpretation?</p>
  
  <p><strong>Update</strong></p>
  
  <p>I've since started learning Spring and this now makes a lot more sense. The paragraph below is taken from <em>Spring in Practice</em> taking an example of an <code>AccountService</code> class which in turn, uses an instance of <code>AccountDao</code>. I apologise for the long quote but I think it really gets to the heart of why injected resources offer something over standard initialisation. </p>
  
  <p><em>You could have constructed the AccountService using the new keyword, but the creation of service layer objects is rarely so straightforward. They often depend on DAOs, mail senders, SOAP proxies, and whatnot. You could instantiate each of those dependencies programmatically in the AccountService constructor (or through static initialization), but that leads to hard dependencies and cascading changes as they’re swapped out.</em></p>
  
  <p><em>Additionally, you could create dependencies externally and set them on the AccountService via setter methods or constructor arguments. Doing so would eliminate the hard internal dependencies (as long as they were declared in the AccountService by interface), but you’d have duplicated initialization code everywhere. Here’s how you create a DAO and wire it
  up to your AccountService the Spring way:</em></p>
  
  <pre><code>&lt;bean id="accountDao" class="com.springinpractice.ch01.dao.jdbc.JdbcAccountDao"/&gt;
  
  &lt;bean id="accountService"
      class="com.springinpractice.ch01.service.AccountService"&gt;
      &lt;property name="accountDao" ref="accountDao"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>Having configured the beans as above, your program can now request an instance of <code>AccountService</code> from the Spring ApplicationContext and the Spring DI framework will look after instantiated everything that needs instantiating. </p>