3.11.1 使用@Inject @Name依赖注入

@javax.inject.Inject可以使用下面的方式来替代@Autowired:

import javax.inject.Inject;

public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Inject
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

    public void listMovies() {
        this.movieFinder.findMovies(...);
        ...
    }
}

@Autowired一样,可以在字段级别,方法级别和构造函数参数级别使用@Inject。 此外,你可以将注入点声明为Provider,允许按需访问作用域较小的bean或通过Provider.get()调用对其他bean的延迟访问。 在上述示例基础上做如下改变:

import javax.inject.Inject;
import javax.inject.Provider;

public class SimpleMovieLister {

    private Provider<MovieFinder> movieFinder;

    @Inject
    public void setMovieFinder(Provider<MovieFinder> movieFinder) {
        this.movieFinder = movieFinder;
    }

    public void listMovies() {
        this.movieFinder.get().findMovies(...);
        ...
    }
}

如果你想要为注入的依赖项使用限定名称,则应该使用@Named,如下所示:

import javax.inject.Inject;
import javax.inject.Named;

public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Inject
    public void setMovieFinder(@Named("main") MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

    // ...
}

results matching ""

    No results matching ""