[转载]Spring Beans Auto-Wiring
Autowiring Modes
You have learnt how to declare beans using the <bean> element and inject <bean> with
using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application.
There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition. |
|
Mode |
Description |
This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter. |
|
no |
|
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. |
|
byName |
|
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if |
|
byType |
|
Similar to byType, but type applies to constructor arguments. If there is |
|
constructor |
not exactly one bean of the constructor argument type in the container, a |
Spring first tries to wire using autowire by constructor, if it does not work, |
|
autodetect |
|
You can use byType or constructor autowiring mode to wire arrays and other typed-collections. |
Limitations with autowiring
Autowiring works best when it is used consistently across a project. If autowiring is not used in
general, it might be confusing to developers to use it to wire only one or two bean definitions.
Though, autowiring can significantly reduce the need to specify properties or constructor
arguments but you should consider the limitations and disadvantages of autowiring before using
them.
Limitations |
Description |
You can still specify dependencies using <constructor-arg> and |
|
Overriding possibility |
|
You cannot autowire so-called simple properties such as primitives, |
|
Primitive data types |
|
Strings, and Classes. |
|
Autowiring is less exact than explicit wiring, so if possible prefer using |
|
Confusing nature |
|
Spring Autowiring 'byName'
This mode specifies autowiring by property name. Spring container looks at the beans on
which auto-wire attribute is set to byName in the XML configuration file. It then tries to match and
wire its properties with the beans defined by the same names in the configuration file. If matches
are found, it will inject those beans otherwise, it will throw exceptions.
For example, if a bean definition is set to autowire byName in configuration file, and it contains
aspellChecker property (that is, it has a setSpellChecker(...) method), Spring looks for a bean
definition named spellChecker, and uses it to set the property. Still you can wire remaining
properties using <property> tags. Following example will illustrate the concept.
Let us have working Eclipse IDE in place and follow the following steps to create a Spring
application:
Step |
Description |
Create a project with a name SpringExample and create a |
|
1 |
|
Add required Spring libraries using Add External JARs option as explained in the Spring |
|
2 |
|
Create Java classes TextEditor, SpellChecker and MainApp under |
|
3 |
|
4 |
Create Beans configuration file Beans.xml under the src folder. |
The final step is to create the content of all the Java files and Bean Configuration file and |
|
5 |
|
Here is the content of TextEditor.java file: |
|
package com.tutorialspoint; public class TextEditor { |
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
} }
Following is the content of another dependent class file SpellChecker.java: package com.tutorialspoint;
public class SpellChecker {
public SpellChecker() {
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
} }
Following is the content of the MainApp.java file: package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
} }
Following is the configuration file Beans.xml in normal condition: <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<property name="spellChecker" ref="spellChecker" />
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
But if you are going to use autowiring 'byName', then your XML configuration file will become as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor"
autowire="byName">
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:
Inside SpellChecker constructor.
Inside checkSpelling.
Spring Autowiring 'byType'
This mode specifies autowiring by property type. Spring container looks at the beans on which autowireattribute is set to byType in the XML configuration file. It then tries to match and wire a property if its typematches with exactly one of the beans name in configuration file. If matches are found, it will inject those beans otherwise, it will throw exceptions.
For example, if a bean definition is set to autowire byType in configuration file, and it contains aspellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire remaining properties using <property> tags. Following example will illustrate the concept where you will find no difference with above example except XML configuration file has been changed.
Here is the content of TextEditor.java file:
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public void setSpellChecker( SpellChecker spellChecker ) {
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
} }
Following is the content of another dependent class file SpellChecker.java: package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file: package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
} }
Following is the configuration file Beans.xml in normal condition: <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<property name="spellChecker" ref="spellChecker" />
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
But if you are going to use autowiring 'byType', then your XML configuration file will become as follows:
<?xml version="1.0" encoding="UTF-8"?> |
<beans xmlns="http://www.springframework.org/schema/beans" <!-- Definition for textEditor bean --> <bean id="textEditor" class="com.tutorialspoint.TextEditor" </bean> |
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:
Inside SpellChecker constructor.
Inside checkSpelling.
Spring Autowiring by Constructor
This mode is very similar to byType, but it applies to constructor arguments. Spring container looks at the beans on which autowire attribute is set to constructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in configuration file. If matches are found, it will inject those beans otherwise, it will throw exceptions.
For example, if a bean definition is set to autowire by constructor in configuration file, and it has a constructor with one of the arguments of SpellChecker type, Spring looks for a bean definition namedSpellChecker, and uses it to set the constructor's argument. Still you can wire remaining arguments using <constructor-arg> tags. Following example will illustrate the concept.
Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:
Step |
Description |
|
Create a project with a name SpringExample and create a |
||
1 |
||
Add required Spring libraries using Add External JARs option as explained in the Spring |
||
2 |
||
Create Java classes TextEditor, SpellChecker and MainApp under |
||
3 |
||
4 |
Create Beans configuration file Beans.xml under the src folder. |
|
The final step is to create the content of all the Java files and Bean Configuration file and |
||
5 |
||
Here is the content of TextEditor.java file: |
||
package com.tutorialspoint; public class TextEditor { public TextEditor( SpellChecker spellChecker, String name ) { } return spellChecker; |
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
} }
Following is the content of another dependent class file SpellChecker.java: package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling()
{
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file: package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
} }
Following is the configuration file Beans.xml in normal condition: <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<!-- Definition for textEditor bean -->
TUTORIALS POINT
Simply Easy Learning Page 64
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<constructor-arg ref="spellChecker" />
<constructor-arg value="Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
But if you are going to use autowiring 'by constructor', then your XML configuration file will become as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor" autowire="constructor">
<constructor-arg value="Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:
Inside SpellChecker constructor.
Inside checkSpelling.
[转载]Spring Beans Auto-Wiring的更多相关文章
- spring beans源码解读
spring beans下面有如下源文件包: org.springframework.beans, 包含了操作java bean的接口和类.org.springframework.beans.anno ...
- spring beans源码解读之--总结篇
spring beans下面有如下源文件包: org.springframework.beans, 包含了操作java bean的接口和类.org.springframework.beans.anno ...
- 如何在servlet取得spring beans (autowired)(转)
在应用中一般普通的JavaPojo都是由Spring来管理的,所以使用autowire注解来进行注入不会产生问题,但是有两个东西是例外的,一个是 Filter,一个是Servlet,这两样东西都是由S ...
- spring beans源码解读之--Bean的注解(annotation)
随着spring注解的引入,越来越多的开发者开始使用注解,这篇文章将对注解的机制进行串联式的讲解,不求深入透彻,但求串起spring beans注解的珍珠,展示给大家. 1. spring beans ...
- spring beans的写入工具——spring-beans-writer
spring-beans-writer是我曾经为动态生成spring beans配置文件做的一个写入工具,托管地址: https://github.com/bluejoe2008/spring-bea ...
- spring beans 源码解读
从把spring下下来,导入到eclipse,花了几个小时的时间. 本来壮志雄心的说要,满满深入学习研读spring源码,现在看来还是不太现实,太难懂了,各种依赖,说明都是英文,整个串起来理解,深入研 ...
- Spring Boot学习一之Spring Beans和依赖注入
你可以自由地使用任何标准的Spring框架技术去定义beans和它们注入的依赖.简单起见,我们经常使用 @ComponentScan 注解搜索beans,并结合 @Autowired 构造器注入. 如 ...
- Spring Boot2(007):关于Spring beans、依赖注入 和 @SpringBootApplication 注解
一.关于Spring beans 和 依赖注入(Dependency Injection) spring boot 和 Spring 全家桶无缝衔接,开发过程中可以很轻松地使用 Spring 全家桶的 ...
- 什么是Spring beans?
Spring beans 是那些形成Spring应用的主干的java对象.它们被Spring IOC容器初始化,装配,和管理.这些beans通过容器中配置的元数据创建.比如,以XML文件中 的形式定义 ...
随机推荐
- SNRO:Number Range
业务对象是在一定的编号范围内分配编号的,编号既可以是内部分配也可以是外部分配.对于外部分配,用户输入编号,系统检查这个编号是否被占用.对于内部分配,系统会自动的把编号分配给业务对象.所以内部分配和外部 ...
- 游戏对象的变换-Transform
问题: 在给GameObject设置位置的时候,怎么保证设置的位置在摄像机的范围内? 主要看摄像机的深度轴和你的GameObject的深度轴,比如如果现在的平面是: Z–> Y, ...
- Linux 我的第一个makefile(Linux指令学习笔记)
我的第一个makefile 最近学到了makefile的文件的编写.makefile是一个能达到方便编译链接生成目标程序的文件, make确实很方便,在写makefile的过程也能更好的理解gcc编译 ...
- yum最常用的命令
yum是一个用于管理rpm包的后台程序,用python写成,可以非常方便的解决rpm的依赖关系.在建立好yum服务器后,yum客户端可以通过 http.ftp方式获得软件包,并使用方便的命令直接管理. ...
- VS2015编译错误:调用的目标发生了异常--->此实现不是Windows平台FLPS验证的加密算法的一部分。
在Win10下安装好几次VS2015(企业版)了,这次发生了一个奇怪的问题,错误截图如下: 控制台.WPF等项目均有此错误!但是ASP.NET项目却可以编译运行!一开始还以为VS2015安装错误,修复 ...
- 基础学习总结(四)--SQLite
1. SQLiteDatabase 操作SQLite数据库的类.可以执行SQL语句,对数据库进行增.删.查.改的操作.也可以进行transaction的控制.很多类对数据库的操作最终都是通过SQL ...
- c# WinForm 编程总结
1.清空DataGridView /// <summary> /// 清空DataGridView /// </summary> /// <param name=&quo ...
- CAD格式DWF嵌入到自己的网页中展示--Autodesk Design Review
网页上嵌入CAD图纸,用的 Autodesk Design Review控件嵌入IE, 网上的 dwf viewer方式没成功. Head之间 <script type="text/j ...
- mongodb持久化
先上一张图(根据此处重画),看完下面的内容应该可以理解. mongodb使用内存映射的方式来访问和修改数据库文件,内存由操作系统来管理.开启journal的情况,数据文件映射到内存2个view:pri ...
- php 获取数组第一个值的方法分享
以下是对使用php实现获取数组第一个值的方法进行了详细的分析介绍,需要的朋友可以过来参考下 reset (PHP 3, PHP 4, PHP 5)reset -- 将数组的内部指针指向第一个单元 说明 ...