Injection:CDI中的 I

Injection: the 'I' in CDI 

http://code.google.com/p/google-guice/

想快快喝下Google果汁——Guice吗?


怎么样理解依赖注入

CDI 是一個針對注入上下文與依賴的 API.
CDI is an API for injecting contexts and dependencies. In Seam and Spring, dependencies work mostly by naming beans and binding them to their injection points by their names. If you are following this tutorial after having completed Getting Started with Contexts and Dependency Injection and JSF 2.0, you have so far only referenced a managed bean by name from the JSF page when we defined the name for the bean using the @Named annotation. The primary role of the @Named annotation is to define the bean for the purpose of resolving EL statements within the application, usually through the JSF EL resolvers. Injection could be performed by using names, but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.

In the following example, you create an ItemProcessor that takes a list of items from a class that implements the ItemDao interface. You take advantage of CDI's @Inject annotation to demonstrate how it is possible to inject a bean into another class. The following diagram depicts the scenario you construct in this exercise.

CDI diagram showing objects created in this exercise

DAO stands for data access object.



Example



// Google Guava in Weld-OSGI.jar for GlassFish.
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

/**
 *
 * @author WisdomFish, Kuo
 */
public class DefaultItemDao2 implements ItemDao2 {

    @Override
    public List<ItemKuo> fetchItem() {
//        List<ItemKuo> results = Lists.newArrayList();
        List<ItemKuo> results = new ArrayList();
        results.add(new ItemKuo(2, 4));
        results.add(new ItemKuo(2, 4));
        results.add(new ItemKuo(2, 4));
        results.add(new ItemKuo(2, 4));
        return results;

    }
}



Working with Qualifiers


A CDI qualifier is an annotation that can be applied at the class level to indicate the kind of bean the class is, and also at the field level (among other places) to indicate what kind of bean needs to be injected at that point.

To demonstrate the need for a qualifier in the application we are building, let's add another DAO class to our application which also implements the ItemDao interface. The following diagram depicts the scenario you are constructing in this exercise. CDI must be able to determine which bean implementation should be used at an injection point. Because there are two implementations of ItemDao, we can resolve this by creating a qualifier named Demo. Then, we "tag" both the bean we want to use, as well as the injection point in ItemProcessor, with a @Demo annotation.



http://tech.it168.com/zt/guice/index.html

Comments