一
.
请举例解释@Autowired注解?
1 ) . 简述 : @Autowired注解对自动装配何时何处被实现提供了更多细粒度的控制
2 ) . 功能 : @Autowired注解可以像@Required注解,构造器一样被用于bean的设值方法上自动装配bean的属性,一个参数或者带有任意名称或带有多个参数的方法
3 ) . 例子 :
[1] 可在设值方法上使用@Autowired注解来替代配置文件中的<property>元素,当spring容器在setter方法上找到@Autowired注解时,会尝试用byType自动装配
[2]也可在构造方法上使用@Autowired注解,带有@Autowired注解的构造方法意味着在创建一个bean时将会被自动装配,即便在配置文件中使用<constructor-arg>元素
4 ) . 代码演示 :
public class TextEditor{
private SpellChecker spellChecker;
@Autowiredpublic 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/>
二.
请举例说明@Qualifier注解?
1 ) . 功能 : @Qualifie注解意味着可以在被标注bean的字段上可以自动装配,Qualifier注解可以用来取消Spring不能取消的bean应用
2 ) . 以下示例将会在Customer的person属性中自动装配person的值
public class Customer{
@Autowiredprivat Person person;
}
3 ) . 以下我们要在配置文件中来配置Person类
<bean id="customer" class="com.howtodoinjava.common.Customer"/>
<bean id="personA" class="com.howtodoinjava.common.Person" >
<property name="name" value="lokesh"/>
<bean/>
<bean id="personB" calss="com.howtodoinjava.common.Person">
<property name="name" value="alex">
<bean/>
4 ) . 问题 : Spring知道要自动装配哪个person bean么?不会的,但是运行上面的示例时,会抛出以下异常
Caused by : org,springframework.beans.factory.NoSuchBeanDefinitionException :
No unique bean of type[com.howtodoinjava.common.Person] is defined :
expected single matching bean but found 2 :[personA,personB]
5 ) .解决 : 使用@Quanlifier注解来告诉spring容器要装配哪个Bean
public class Customer{
@Autowired
@Qualifier("personA")
private Person person;
}