spring配置文件头设置default-autowire
来源:互联网 发布:搭建个人云软件 编辑:程序博客网 时间:2024/05/21 17:59
default-autowire与autowire主要用于spring的IOC的注解注入,明白两者的区别和用法将使你的开发事半功倍。
Spring 提供了Resource、Autowired这两个注解用于注入,另外在xml配置文件中,beans标签下有一个参数default-autowire用来设置默认的注入类型。
default-autowire和autowire的可选值
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.csdn.net/otengyue/article/details/51509000- spring配置文件头设置default-autowire
- Spring中default-autowire与autowire区别
- Spring中的注入注解Resource/Autowired以及配置文件中default-autowire参数详解
- spring配置文件中autowire详解
- 学习笔记:Spring中default-autowire与autowire区别
- spring中的default-autowire="byName"
- 【Spring】spring的自动装配(default-autowire="byName")
- spring的自动装配(default-autowire="byName")
- spring 自动装配 default-autowire="byName/byType"
- spring的自动装配(default-autowire="byName")
- Spring中的自动装配(default-autowire="byName")
- spring的自动装配(default-autowire="byName")
- spring的自动装配(default-autowire="byName")
- Spring的自动装配 default-autowire="byName"
- spring的自动装配(default-autowire="byName")
- spring的自动装配(default-autowire="byName")
- spring的自动装配(default-autowire="byName")
- spring 自动装配 default-autowire="byName/byType"
- jsp中几种包含页面的方式区别
- 仿京东移动端手指拨动切换轮播图效果
- (笔记)MVC模式
- rman如何在nomount模式下恢复丢失的所有控制文件
- try catch 中带返回值执行顺序
- spring配置文件头设置default-autowire
- Visual Studio 2015 中关于运行时库的设置 /MD[d]、/MT[d]、/LD[d]
- 阅读小结:The Unreasonable Effectiveness of Noisy Data for Fine-Grained Recognition
- android中重要的几个组件
- 数组
- HTTP header location 重定向 URL
- jedi-vim安装
- Flume日志收集分层架构应用实践
- expect转义符及远程主机执行命令