Spring Autowiring by Constructor
2015-08-22 11:41
441 查看
In Spring, “Autowiring by Constructor” is actually autowiring by Type in constructor argument. It means, if data type of a bean is same as the data type of other bean constructor argument, auto wire it.
See a full example of Spring auto wiring by constructor.
With autowire by constructor enabled, you can leave the
See a full example of Spring auto wiring by constructor.
1. Beans
Two beans,developerand
language.
package com.mkyong.common; public class Developer { private Language language; //autowire by constructor public Developer(Language language) { this.language = language; } //... }
package com.mkyong.common; public class Language { private String name; //... }
2. Spring Wiring
Normally, you wire the bean via constructor like this :<bean id="developer" class="com.mkyong.common.Developer"> <constructor-arg> <ref bean="language" /> </constructor-arg> </bean> <bean id="language" class="com.mkyong.common.Language" > <property name="name" value="Java" /> </bean>
Output
Developer [language=Language [name=Java]]
With autowire by constructor enabled, you can leave the
constructorproperty unset. Spring will find the compatible data type and wire it automatcailly.
<bean id="developer" class="com.mkyong.common.Developer" autowire="constructor" /> <bean id="language" class="com.mkyong.common.Language" > <property name="name" value="Java" /> </bean>
Output
Developer [language=Language [name=Java]]
相关文章推荐
- java内部类和匿名类
- Spring Autowiring by Name
- 针对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