1、构造方法注入
类中提供构造方法
bean.xml中通过constructor-arg为构造方法的参数赋值
2、setter方法注入
类中提供setter方法
bean.xml中通过property标签配置注入
3、集合的注入方式
类中提供setter方法
package com.alphajuns.webstudy.pojo; import java.util.*; public class CollectionDI { private String[] strArray; private List<String> list; private Set<String> set; private Map<String, String> map; private Properties properties; public void setStrArray(String[] strArray) { this.strArray = strArray; } public void setList(List<String> list) { this.list = list; } public void setSet(Set<String> set) { this.set = set; } public void setMap(Map<String, String> map) { this.map = map; } public void setProperties(Properties properties) { this.properties = properties; } @Override public String toString() { return "CollectionDI{" + "strArray=" + Arrays.toString(strArray) + ", list=" + list + ", set=" + set + ", map=" + map + ", properties=" + properties + '}'; } }
bean.xml中配置
<!-- 集合注入 --> <bean id="CollectionDI" class="com.alphajuns.webstudy.pojo.CollectionDI"> <!-- 数组 --> <property name="strArray"> <set> <value>AAA</value> <value>BBB</value> <value>CCC</value> </set> </property> <!-- list --> <property name="list"> <array> <value>DDD</value> <value>EEE</value> <value>FFF</value> </array> </property> <property name="set"> <list> <value>111</value> <value>222</value> <value>111</value> </list> </property> <property name="map"> <props> <prop key="a">AAA</prop> <prop key="b">BBB</prop> </props> </property> <property name="properties"> <map> <entry key="d" value="DDD"></entry> <entry key="e"> <value>EEE</value> </entry> </map> </property> </bean>
p名称空间方式也能注入,也是采用了setter方法的方式。