spring学习笔记13(注解@Autowired方式注入)

出自:http://wang09si.blog.163.com/blog/static/17017180420139261016713/


@Autowired与@Resource用法基本相同,区别在于@Autowired是默认以类型去查找,而@Resource默认以字段名去查找。

@Autowired是spring提供的,而 @Resource是j2ee提供的。
看例子:

public class AnimalServiceImpl implements AnimalService {
@Autowired private PersonDao per;
public AnimalServiceImpl(){}
public AnimalServiceImpl(PersonDao per){
this.per = per;
}
public void jump(){
per.add();
}
}
 <bean id="personDaoB" class="com.dao.person.PersonDaoImpl" ></bean>
  <bean id='animalService' class="com.service.person.AnimalServiceImpl" >
AnimalService animal = (AnimalService)cxt.getBean("animalService");
animal.jump();


那么,能不能让 @Autowired以名称查找呢?
@Autowired @Qualifier("personDaoB") private PersonDao per;
这样就可以了!


@Autowired(required=false)当根据类型去找,找不到时,注入一个空。
@Autowired(required=true)当根据类型去找,找不到时,抛出异常信息。
例如
<bean id="personDaoB" class="com.dao.person.PersonDaoImpl" ></bean>
 <bean id='animalService' class="com.service.person.AnimalServiceImpl" >
 </bean>
@Autowired(required=false) private PersonService ps;
public AnimalServiceImpl(PersonDao per,PersonService ps){
this.per = per;
this.ps = ps;
}
测试
AnimalService animal = (AnimalService)cxt.getBean("animalService");
animal.jump();
一切正常!
如果改为
@Autowired(required=true) private PersonService ps;
由于找不到 PersonService  类型对应的bean,而 required=true,
所以抛出异常信息!


注意,注解注入时一定要同时写带参和不带参的构造方法!
如果你不用构造方法行不行呢?就像第一种方式一样:
@Autowired private PersonDao pd;
public void setPd(PersonDao pd) {
this.pd = pd;
}
public void save(String str){
pd.add(str);
}
 <context:annotation-config/>
 <bean id="personDao" class="com.dao.spring.PersonDaoImpl"></bean>
   <bean id='personService' class="com.service.spring.PersonServiceImpl">
同样是可以的!与第一种方式的区别在于,在bean里面,除了配置了两个bean以外,什么也没配,而是在声明属性的时候,写 @Autowired之类的注解。而第一种是,在bean的实现类里面,基本什么也没配置,而是在配置文件中写了 <property name="personDaoA" ref="personSetDao"></property>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值