spring中autowire的用法
2016-06-28 11:47
531 查看
Autowire模式就是在spring的声明文件里用作进行对象间的关联关系自动绑定的,就是在spring beanfactory内的一个bean对其bean的引用可以自动进行,而不一定用ref=的方式显式声明。在reference的3.3.6节有详细的介绍,autowire主要有5种模式:
1 no
不使用Autowire,引用关系显示声明,spring的reference也建议不用autoware,因为这会破坏模块关系的可读性,原文如下:
2 byName
用名称关联,如果指定了这种模式,如
这样对于bean userManagerTarget的属性baseDAO,spring就会自动去引用同名的bean,也就是上面的声明和下面是等价的:
3 byType
和前面的byName类似的,就是这个属性会在整个beanFactory定义里找和这个属性一样的bean自动关联上,如果有2个或更多这个类型的bean在beanFactory的定义里,就直接抛异常了,如果没有,就什么都不发生,这个属性就是null,所以这个只适用与这个属性的类型有且只有一个同类的bean在spring里定义
4 constructor
这个的意思我没有确定的把握,不过感觉用途也不会大,好像是用构造函数新建一个属性类型的bean并关联上,reference原文是:
5 autodetect
这个的意思好像是说自动决定用byType还是constructor方式,原文如下:
综上所述,感觉上只有byName比较实用一些,但是spring的reference还是不推荐在定义中用这个功能
1 no
不使用Autowire,引用关系显示声明,spring的reference也建议不用autoware,因为这会破坏模块关系的可读性,原文如下:
Note: as has already been mentioned, for larger applications, it is discouraged to use autowiring because it removes the transparency and the structure from your collaborating classes.
2 byName
用名称关联,如果指定了这种模式,如
<bean id="userManagerTarget" class="com.mdcchina.jianghu.logic.UserManager" autowire="byName"> <property name="baseDAO"/> </bean>
这样对于bean userManagerTarget的属性baseDAO,spring就会自动去引用同名的bean,也就是上面的声明和下面是等价的:
<bean id="userManagerTarget" class="com.mdcchina.jianghu.logic.UserManager" autowire="no"> <property name="baseDAO"> <ref local="baseDAO"/> </property> </bean>
3 byType
和前面的byName类似的,就是这个属性会在整个beanFactory定义里找和这个属性一样的bean自动关联上,如果有2个或更多这个类型的bean在beanFactory的定义里,就直接抛异常了,如果没有,就什么都不发生,这个属性就是null,所以这个只适用与这个属性的类型有且只有一个同类的bean在spring里定义
4 constructor
这个的意思我没有确定的把握,不过感觉用途也不会大,好像是用构造函数新建一个属性类型的bean并关联上,reference原文是:
This is analogous to byType, but applies to constructor arguments. If there isn't exactly one bean of the constructor argument type in the bean factory, a fatal error is raised.
5 autodetect
这个的意思好像是说自动决定用byType还是constructor方式,原文如下:
Chooses constructor or byType through introspection of the bean class. If a default constructor is found, byType gets applied.
综上所述,感觉上只有byName比较实用一些,但是spring的reference还是不推荐在定义中用这个功能
相关文章推荐
- java1对属性的理解
- spring boot 学习笔记(001) 新建Eclipse工程
- 使用Maven配置Struts2 集成Spring
- eclipse下载
- Java 探针:Java SE 6 提供的 Attach API
- MyBatis入门第2天--MyBatis基础知识(二)
- java.text.Format及相关类详解
- java中的类修饰符、成员变量修饰符、方法修饰符
- Spring Data JPA 快速入门
- 64位win7环境eclipse集成svn后出现Failed to load JavaHL Library的解决办法
- eclipse *.vm 文件,语法高亮
- html传到后台的中文乱码(后台为java)
- java虚拟机收集器之老年代收集器
- leetcode-java-137. Single Number II
- 取消eclipse js验证
- 项目从eclipse迁移到as
- eclipse birt报表
- java的4中对象引用方式
- Java程序打包成exe
- Spring4.x官方参考文档中文版——第21章 Web MVC框架(16)