请举例解释 @Autowired 注解?
@Autowired
注解对自动装配何时何处被实现提供了更多细粒度的控制。@Autowired
注解可以像@Required
注解、构造器一样被用于在bean的设值方法上自动装配bean的属性,一个参数或者带有任意名称或带有多个参数的方法。
比如,可以在设值方法上使用 @Autowired
注解来替代配置文件中的 <property>
元素。当 Spring 容器在 setter 方法上找到 @Autowired
注解时,会尝试用 byType 自动装配。
当然我们也可以在构造方法上使用 @Autowired
注解。带有 @Autowired
注解的构造方法意味着在创建一个 bean 时将会被自动装配,即便在配置文件中使用 <constructor-arg>
元素。
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
下面是没有构造参数的配置方式:
<beans>
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean class="com.howtodoinjava.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean class="com.howtodoinjava.SpellChecker">
</bean>
</beans>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论