构造器注入,那不就是使用构造方法来注入信息吗! 所以我们先来写一个带参的构造方法,看看spring的xml是如何进行配置的。
此构造方法共有三个参数 name age 和time 分别是String类型 Integer类型 和 类对象。
package org.com.qst.service.impl;
import org.com.qst.service.IAccountService;
import java.util.Date;
public class AccountServiceImpl implements IAccountService {
private String name;
private Integer age;
private Date time;
public AccountServiceImpl(String name, Integer age, Date time) {
this.name = name;
this.age = age;
this.time = time;
}
public void saveAccount() {
System.out.println("service"+name+age+time);
}
}
配置XML
从此配置文件中我们可以看出 spring能够注入的类型( 1 基本类型和String型 2 其他bean类型 (ref=...容器中出现过得bean对象 3 复杂类型和集合类型) 就明确了。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="org.com.qst.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="mys"></constructor-arg>
<constructor-arg name="age" value="21"></constructor-arg>
<constructor-arg name="time" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>
</beans>
除了使用到的 name 标签外 还有两个标签 index ,type 也可以指定构造方法的参数, index有用指定位置来进行注入参数,type根据参数的类型来注入参数,这两个并不常有。