博士TL;
@Autowired注释使您不必自己在XML文件(或任何其他方式)中进行连接,它只是为您找到需要在哪里注入的内容并为您完成该工作。
完整的解释
@Autowired注释允许您跳过要注入内容的其他配置,并为您自行完成。假设你的包是com.mycompany.movies,你必须把这个标签放在你的XML(应用程序上下文文件)中:
<context:component-scan base-package="com.mycompany.movies" />
This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component (for simple bean) or @Controller (for a servlet control) or @Repository (for DAO classes) and these classes are somewhere under the package com.mycompany.movies, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration class (or any combination of the three).
The @Autowired annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder it understands (by the prefix set + the @Autowired annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception. To avoid the Exception, you can use the @Qualifier annotation and tell it which of the two beans to inject in the following manner:
@Qualifier("redBean")
class Red implements Color {
// Class code here
}
@Qualifier("blueBean")
class Blue implements Color {
// Class code here
}
或者如果你更喜欢在XML中声明bean,它看起来像这样:
<bean id="redBean" class="com.mycompany.movies.Red"/>
<bean id="blueBean" class="com.mycompany.movies.Blue"/>
在@Autowired声明中,你还需要添加@Qualifier来告诉你要注入哪一个颜色bean:
@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
this.color = color;
}
如果你不想使用两个注释(@Autowired和@Qualifier),你可以使用@Resource来组合这两个:
@Resource(name="redBean")
public void setColor(Color color) {
this.color = color;
}
@Resource(您可以在这个答案的第一个注释中阅读有关它的一些额外数据)使您不必使用两个注释,而是只使用一个注释。
我再加两点评论:
好的做法是使用@Inject而不是@Autowired,因为它不是spring特定的,而是JSR-330标准的一部分。
另一个好的实践是将@Inject / @Autowired放在构造函数上而不是方法上。如果将其放在构造函数上,则可以验证注入的bean不是空的,并且在尝试启动应用程序时快速失败,并在需要实际使用bean时避免出现NullPointerException。
更新:为了完成图片,我创建了一个关于@Configuration类的新问题。