default-autowire与autowire主要用于spring的IOC的注解注入,明白两者的区别和用法将使你的开发事半功倍。
Spring 提供了Resource、Autowired这两个注解用于注入,另外在xml配置文件中,beans标签下有一个参数default-autowire用来设置默认的注入类型。
default-autowire和autowire的可选值
可选值 | 功能说明 |
---|---|
no | 默认不使用autowiring。 必须显示的使用”“标签明确地指定bean。 |
byName | 根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。 |
byType | 如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的bean,则什么事都不发生,属性也不会被设置。如果你不希望这样,那么可以通过设置 dependency-check=”objects”让Spring抛出异常。 |
constructor | 与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。 |
autodetect | 通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式。 |
beans标签设置default-autowire参数
在spring的配置文件中可以参照如下设置default-autowire参数
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
在beans标签设置default-autowire=”byName”后,在spring容器实例化bean(包含xml配置bean和注解方式bean)时,该bean内部的字段会自动根据byName装载spring容器里的bean。如下:
Spring配置文件中
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
Student类
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
此时spring容器启动加载bean时候由于在beans标签设置default-autowire=”byName”,那么在加载Student的Bean时候,会把字符串”Tom”注入到Student类的stu_name字段,而由于配置了自动注入所有在注入teacher字段时候,会扫描容器里id为teacher的Bean注入到该字段中,而不用再在id为student的Bean配置了。
autowire参数的用法
autowire可用在两次:XML中配置Bean的参数和@Autowired注解注入。两者都是把对应的类实现自动注入。
(1)XML中配置Bean的参数
Autowire配置的可选值依然如上述表格中的说明,XML配置文件如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
同样,spring容器启动加载bean时候,在加载到Student的Bean时候,会把字符串”Tom”注入到Student类的stu_name字段,而同时由于对这个类配置了autowire=”byName”参数,所以会扫描spring容器中id为teacher的Bean然后注入到该类的teacher字段中。
(2)@Autowired注解注入
@Autowired往往用在类中注解注入,在配置xml需要配置才能使用@Autowired标识
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
在类中使用@Autowired标识注入字段
原文:http://blog.youkuaiyun.com/otengyue/article/details/51509000