注解实现自动装配
- 支持:
jdk1.5版本后支持注解开发,Spring2.5就支持注解了!
- 要使用需要知道以下几点
1.导入约束:context约束
2.配置注解的支持:context:annotation-config/
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解支持-->
<context:annotation-config/>
</beans>
@Autowired
- 直接在属性上使用即可!也可以在set方式上使用!
- 使用 @Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname!
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null;
punliac class Pelople{
//如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required=flase)
private Cat cat
@Autowired
private Dog dog;
private String name;
}
如果 @Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【 @Autowired】完成时,我们可以使用 @Qualifier(value = “xxx”)去配置 @Autowired的使用,指定一个唯一的bean对象注入!因为在一些情况下因为类型和名字无法注入的时候我们就可以去用上面的两个标签配合着去使用
- 实体类People
package com.cloud.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class People {
@Autowired
@Qualifier(value = "dog")
private Dog dog;
@Autowired
@Qualifier(value = "cat")
private Cat cat;
private String name;
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"dog=" + dog +
", cat=" + cat +
", name='" + name + '\'' +
'}';
}
}
- @Resource注解
package com.cloud.pojo;
import javax.annotation.Resource;
public class People {
@Resource(name = "dog")
private Dog dog;
@Resource
private Cat cat;
private String name;
}
小结:
@Resource和Autowired的区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就会报错!【常用】
- 执行顺序不同:@Autowired通过byType的方式实现。@Resource默认通过byname的方式实现