请举例解释@Autowired注解?

SpingAutowired浏览:296收藏:0
答案:
@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 id="textEditor" class="com.howtodoinjava.TextEditor">
</bean>

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.howtodoinjava.SpellChecker">
</bean>

</beans>