上篇简单介绍了一下bean配置文件注入简单的属性和复杂一点的类注入,今天说一下其余类型的注入。html
spring中提供配置Bean有三种实例化的方式java
类构造器实例化就是昨天说的那种spring
< bean id ="engine" class ="com.demo.spring.car.QiyouEngine" ></ bean >
使用这个实例化QiyouEngine类,调用的是类默认的构造函数api
若是想要在构造器里加入参数就得在替换掉上篇写在bean标签里的property标签,改为<constructor-arg></constructor-arg>数组
好比把上篇中使用set方法注入的属性name和engine,改为用构造器注入就的这么写:ide
< bean id ="car" class ="com.demo.spring.car.Car" > < constructor-arg index ="0" type ="java.lang.String" value ="宝马" ></ constructor-arg > < constructor-arg index ="1" type ="com.demo.spring.car.IEngine" ref ="engine" ></ constructor-arg > </ bean >
<constructor-arg>标签中index指的是该属性在构造器中参数的顺序,从0开始。而type是写注入属性的类型和构造器的顺序是同样的函数
public Car(String name,IEngine engine){ this .name = name; this .engine = engine; }
接下来说如何注入集合类型,如List,Set,Map等this
List的注入和数组的注入是采起相同的标签spa
< bean id ="hobby" class ="com.demo.spring.Hobby" > < property name ="hobbys" > < list > < value > 篮球 </ value > < value > 足球 </ value > </ list > </ property > </ bean >
hobby类的结构.net
public class Hobby { private List < String > hobbys; public List < String > getHobbys() { return hobbys; } public void setHobbys(List < String > hobbys) { this .hobbys = hobbys; } @Override public String toString() { return " Hobby [hobbys= " + hobbys + " ] " ; } }
以上执行的结果
因为原有的方式List是写在bean标签内,得不到复用,咱们能够借助spring提供的ListFactoryBean来实现
< bean id ="hobby" class ="com.demo.spring.Hobby" > < property name ="hobbys" ref ="hobbys" ></ property > </ bean > < bean id ="hobbys" class ="org.springframework.beans.factory.config.ListFactoryBean" > < property name ="sourceList" > < list > < value > 篮球 </ value > < value > 足球 </ value > </ list > </ property > </ bean >
须要说明的是虽然上面使用<list>能够实现这样的效果,不过这是旧的标签了,咱们照样能够在spring 3.2中使用,可是官方提供了新的方式
首先须要在xml顶部添加一些信息,加粗的就是须要添加的命名空间
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
使用spring新标签<util:list>,大大简化了编写的复杂度
< util:list id ="hobbys" list-class ="java.util.ArrayList" > < value > 篮球 </ value > < value > 足球 </ value > </ util:list >
其余的Map和Set标签能够查看官网的api文件