I know that there are many articles that explain how to use CDI in Java EE, but it's hard for me to understand what benefits this brings. For example, suppose I have a class that currently uses an instance of Foo. I could do
Foo myFoo = new Foo();
or
// Better, FooFactory might return a mock object for testing Foo myFoo = FooFactory.getFoo();
I keep reading what with CDI I can do:
@Inject Foo myFoo;
but why is it better than the previous factory based approach? I assume there is another use case that I don’t know about, but I could not identify it.
If I understood the answers below, the concept is that the DI structure acts as the main factory object, which is centrally configured. Is this a reasonable interpretation?
Update
Since then, I started learning Spring, and now it makes a lot more sense. The following paragraph is taken from Spring in Practice using the AccountService class as an AccountService , which in turn uses an instance of AccountDao . I apologize for the long quote, but I think it really depends on why the resources invested offer something along standard initialization.
You could create an AccountService using a new keyword, but creating service-level objects is rarely that simple. They often depend on DAOs, senders, SOAP proxies, and more. You could programmatically create each of these dependencies in the AccountService constructor (or through static initialization), but this leads to hard dependencies and cascading changes as they are replaced.
In addition, you can create dependencies from the outside and install them in the AccountService using setter methods or constructor arguments. This will eliminate the hard internal dependencies (if they were declared in the AccountService interface by interface), but you duplicate the initialization code anyway. Here's how you create a DAO and hook it up to your AccountService Spring way:
<bean id="accountDao" class="com.springinpractice.ch01.dao.jdbc.JdbcAccountDao"/> <bean id="accountService" class="com.springinpractice.ch01.service.AccountService"> <property name="accountDao" ref="accountDao"/> </bean>
AccountService beans as described above, your program can now request an instance of AccountService from the ApplicationContext Spring, and the Spring DI environment will make sure to instantiate everything that is required to create the instance.