【Spring】(七)注解实现自动装配
使用注解实现自动装配
-
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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>
1.@Autowired自动装配【常用】
-
直接在属性上使用即可,也可以在set方法上使用。
-
使用Autowired后可以不用编写set方法,前提是这个自动装配的属性在IOC(Spring)容器中存在,且属性名和bean的id相同。
-
People
public class People { @Autowired private Cat cat; @Autowired private Dog dog; private String name; .. } -
applicationContext.xml中
<context:annotation-config /> <bean id="cat" class="pojo.Cat"/> <bean id="dog" class="pojo.Dog"/> <bean id="people" class="pojo.People"/>
2.@Autowired的required属性
//如果显示定义了Autowired的required属性为false,说明该对象可以为null,否则不为空
@Autowired(required = false)
private Cat cat;
3.@Nullable
-
字段标注这个注解,说明该字段可为null
public void setName(@Nullable String name) { this.name = name; }
4.@Qualifier(value="xxx")
-
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解@Autowired完成时,可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入。
-
applicationContext.xml
<bean id="cat1" class="pojo.Cat"/> <bean id="cat2" class="pojo.Cat"/> -
People中
@Autowired(required = false) @Qualifier(value = "cat2") private Cat cat;
5.@Resource自动装配【常用】
-
非spring注解,javax自带的注解
导包:
import javax.annotation.Resource; -
先根据属性名去注册容器找有相同id的bean,没有则找是否有相同且唯一的类型。
-
1.配置文件中
<bean id="cat1" class="pojo.Cat"/> <bean id="cat" class="pojo.Cat"/> <!--找到这个--> -
2.People中
@Resource private Cat cat; @Resource private Dog dog;
-
-
可以指定其属性name的值:解决出现属性名与id不同,且类型不唯一的情况
-
1.配置文件
<bean id="cat1" class="pojo.Cat"/> <!--找到这个--> <bean id="cat2" class="pojo.Cat"/> -
2.People
@Resource(name = "cat1") private Cat cat;
-
6.小结:
@Resource和@Autowired的区别
-
都是用来自动装配的,都可以放在属性字段上
-
@Autowired先通过byType的方式实现,再通过byName实现,并且必须要求这个对象存在。
-
@Resource默认通过byname方式实现,如果找不到名字,则通过byType实现。如果两个都找不到,就报错。
-
执行顺序不同:
@Autowired默认通过byType方式实现。
@Resource默认通过byname方式实现。

浙公网安备 33010602011771号