Spring DI-注解注入

Spring DI-注解注入

用注解实现属性注入

1、步骤:

1.1、创建Student类和Person类
1
2
3
4
5
6
7
8
public class Person {
@Resource
private Student student;

public void say(){
this.student.say();
}
}
1.2、把Person和Student放入到spring容器中
1
2
<bean id="student" class="..."></bean>
<bean id="person" class="..."></bean>
1.3、启动依赖注入的注解解析器
1
<context:annotation-config></context:annotation-config>

注意:基本类型不能用注解完成注入

2、原理:

2.1、当启动spring容器的时候创建了person和student两个对象
2.2、加载配置文件是否含有context:annotation-config

当spring容器解析到
context:annotation-config</context:annotation-config>
spring容器会在纳入spring管理范围的bean查找;

2.3、查找这些bean的方法或者属性上是否含有Resource注解
2.4、当存在Resource注解

则查看该注解的属性name的值:

  • 如果name的值为””,则会按照该注解所在的属性的名称和spring容器中的ID做匹配,如果匹配成功,则赋值;
    如果匹配不成功,则按照类型进行匹配,则赋值; 如果类型再匹配不成功,则报错;

  • 如果name的属性值不为””,则按照name的属性的值和spring容器中的ID匹配,成功,则赋值,不成功,则报错

3、xml与注解区别

  • xml效果比较高,写法比较复杂
  • 注解效率比较低,但是写法比较简单

    因为注解可能需要查找spring容器中定义的所有bean。

4、依赖注入的注解

  • @Resource(name=”student”) 见上面
  • @Autowired 按照类型进行匹配
  • @Qualifier(“student”) 按照”student”与spring中的ID进行匹配

@Resource = @Autowired + @Qualifier(“student”)

@Autowired + @Qualifier(“student”)组合使用