您的位置:首页 > 编程语言 > Java开发

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

2015-03-14 20:46 387 查看
出自: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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: