Spring Autowiring by Name
2015-08-22 11:38
639 查看
In Spring, “Autowiring by Name” means, if the name of a bean is same as the name of other bean property, auto wire it.
For example, if a “
You can enable this feature via
See a full example of Spring auto wiring by name.
With autowire by name enabled, you do not need to declares the
See another example, this time, the wiring will failed, caused the bean “
For example, if a “
customer” bean exposes an “
address” property, Spring will find the “
address” bean in current container and wire it automatically. And if no matching found, just do nothing.
You can enable this feature via
autowire="byName"like below :
<!-- customer has a property name "address" --> <bean id="customer" class="com.mkyong.common.Customer" autowire="byName" /> <bean id="address" class="com.mkyong.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean>
See a full example of Spring auto wiring by name.
1. Beans
Two beans,customerand
address.
package com.mkyong.common; public class Customer { private Address address; //... }
package com.mkyong.common; public class Address { private String fulladdress; //... }
2. Spring Wiring
Normally, you wire the bean explicitly, viarefattribute like this :
<bean id="customer" class="com.mkyong.common.Customer" > <property name="address" ref="address" /> </bean> <bean id="address" class="com.mkyong.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean>
Output
Customer [address=Address [fulladdress=Block A 888, CA]]
With autowire by name enabled, you do not need to declares the
propertytag anymore. As long as the “
address” bean is same name as the property of “
customer” bean, which is “
address”, Spring will wire it automatically.
<bean id="customer" class="com.mkyong.common.Customer" autowire="byName" /> <bean id="address" class="com.mkyong.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean>
Output
Customer [address=Address [fulladdress=Block A 888, CA]]
See another example, this time, the wiring will failed, caused the bean “
addressABC” is not match the property name of bean “
customer”.
<bean id="customer" class="com.mkyong.common.Customer" autowire="byName" /> <bean id="addressABC" class="com.mkyong.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean>
Output
Customer [address=null]
相关文章推荐
- 针对Eclipse的maven Missing artifact com.microsoft.sqlserver:slqjdbc4:jar:4.0
- Spring Autowiring by Type
- Java GC 日志详解
- java readLine
- 启动Java Web项目时提示错误:A child container failed during start
- Ehcache 整合Spring 使用页面、对象缓存
- Spring Auto-Wiring Beans
- Java--排序与查找
- 叶存菜鸟URL和URLConnection java笔记
- struts接收参数方式
- java多线程学习
- JAVA内存分配-通俗讲解
- JAVA基础概念
- Java多线程通信
- Struts(19)Struts集成
- Struts(18)标签
- Java Servlet的配置文件web.xml配置内容和具体含义
- Spring Filter components in auto scanning
- java 金额转大写
- Struts(17)注释