Dependency injection

Dependency injection is a technique for supplying external dependencies to a Java class. Java EE 5 introduced dependency injection via the @Resource annotation, however, this annotation is limited to injecting resources such as database connections, JMS resources, and so on. CDI includes the @Inject annotation, which can be used to inject instances of Java classes into any dependent objects.

JSF applications typically follow the Model-View-Controller (MVC) design pattern. As such, often some JSF managed beans take the role of controllers in the pattern, while others take the role of the model. This approach typically requires the controller managed bean to have access to one or more of the model-managed beans. CDI's dependency injection capabilities make injecting beans into one another very simple, as illustrated in the following example:

package net.ensode.javaee8book.cdidependencyinjection.ejb; 
 
import java.util.logging.Logger; 
import javax.inject.Inject; 
import javax.inject.Named; 
 
@Named 
@RequestScoped 
public class CustomerController { 
 
  private static final Logger logger = Logger.getLogger( 
      CustomerController.class.getName()); 
  @Inject 
  private Customer customer; 
 
  public String saveCustomer() { 
 
    logger.info("Saving the following information 
" + customer. 
        toString()); 
 
    //If this was a real application, we would have code to save 
    //customer data to the database here. 
 
    return "confirmation"; 
  } 
} 

Notice that all we had to do to initialize our Customer instance was to decorate it with the @Inject annotation. When the bean is constructed by the application server, an instance of the Customer bean is automatically injected into this field. Notice that the injected bean is used in the saveCustomer() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.71.115