(五)java深入java虚拟机及大数据笔记库(61)

  一 .   请举例解释@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;

@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/>
 
 
 



       二.  请举例说明@Qualifier注解?


1 ) . 功能 : @Qualifie注解意味着可以在被标注bean的字段上可以自动装配,Qualifier注解可以用来取消Spring不能取消的bean应用

2 ) . 以下示例将会在Customer的person属性中自动装配person的值

public class Customer{

@Autowired
privat 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;

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值