我正在阅读Spring 3.0.x参考文档,以了解Spring Autowired注释:
我不理解以下示例。我们需要在XML中做些什么才能使其工作?
示例1:
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
例子2
public class MovieRecommender {
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public void prepare(MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
如何在实现相同接口并使用相同类的情况下,进行两个类的自动装配?示例:
class Red implements Color
class Blue implements Color
class myMainClass{
@Autowired
private Color color;
draw(){
color.design();
}
}
哪种设计方法会被调用?我该如何确保调用红色类的设计方法而不是蓝色类的?
MovieFinder
是一个接口,而我们有一个名为MovieFinderImpl
(bean id = movieFinder)的bean,Spring会按类型还是按名称自动注入它? - JaskeyLam@Qualifier
。如果是,按名称;如果不是,则按类型。按类型仅在上下文中只有一个类型为MovieFinder
的bean时才有效。超过1个将导致异常。 - Avi@Autowired
注解如何作用于prepare
方法。它正在初始化MovieRecommender
,但从技术上讲,它并不是一个setter。 - Chesser@Autowired
也适用于构造函数。它会查找所需的依赖项并将它们注入到构造函数中。 - Avi