spring有三种依赖注入的方式,第一种是构造方法注入
<bean id="bean" class="Test1.Per">
<constructor-arg name="username" value="xx"></constructor-arg>
<constructor-arg name="arr">
<array>
<value>1</value>
<value>2</value>
</array>
</constructor-arg>
<constructor-arg name="list">
<list>
<value>"xx"</value>
<value>"cc"</value>
</list>
</constructor-arg>
<constructor-arg name="set">
<set>
<value>"ss"</value>
</set>
</constructor-arg>
<constructor-arg name="prop">
<props>
<prop key="mmm">"ppp"</prop>
</props>
</constructor-arg>
<constructor-arg name="date" ref="date"></constructor-arg>
</bean>
<bean id="date" class="java.util.Date" >
</bean>
//bean类
public class Per {
private String username;
private int[] arr;
private List list;
private Set set;
private Properties prop;
private Date date;
public Per(String username, int[]arr, List list, Set set, Properties prop
, Date date){
this.username=username;
this.arr=arr;
this.list=list;
this.set=set;
this.prop=prop;
this.date=date;
}
public void get(){
System.out.println(this.list);
System.out.println(this.arr[0]);
System.out.println(this.username);
System.out.println(this.set);
System.out.println(this.prop);
System.out.println(this.date);
}
}
这种方式缺点是在获取bean对象时,注入数据是必须的操作,否则无法创建,即使是无用的数据也要注入。如果有多个构造方法,每个构造方法只有参数的顺序不同,那通过构造方法注入多个参数会注入到第一个出现的构造方法中
第二种方法是setter注入
public class Per {
private String username;
public void setUsername(String username){
this.username=username;
}
public void get(){
System.out.println(this.username);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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">
<beans>
<bean id="bean" class="Test1.Per">
<property name="username" value="pp">
</property>
</beans>
</beans>
最后一种是注解注入,@Resource、@Service、@Controller等