一 . 常规Bean的依赖注入
很简单,不过多赘述了,注意ref: 是构造函数或set方法的参数,一般为对象, value:?是构造函数或set方法的参数,一般为值.? ?看下图
1.1.1这是List的注入(演示泛型为String和UserDao两种情况)
在UserServiceImpl.java里的代码
private List<String> stringList;
public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
private List<UserDao> userDaoList;
public void setUserDaoList(List<UserDao> userDaoList) {
this.userDaoList = userDaoList;
}
applicationContext.xml里的配置代码
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="stringList" >
<list>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<property name="userDaoList">
<list>
<ref bean="userDaoA"></ref>
<ref bean="userDaoB"></ref>
<ref bean="userDaoC"></ref>
</list>
</property>
</bean>
<bean id="userDaoA" class="com.itheima.dao.impl.UserDaoImpl"></bean>
<bean id="userDaoB" class="com.itheima.dao.impl.UserDaoImpl"></bean>
<bean id="userDaoC" class="com.itheima.dao.impl.UserDaoImpl"></bean>
1.1.2同理set与此类似,不在演示
1.1.3map也很简单,大致与上文类似,下面给出配置文件不太一样的地方
<property name="map">
<map>
<entry key="d1" value-ref="userDao1"></entry>
<entry key="d2" value-ref="userDao2"></entry>
</map>
</property>
Propertis:键值对,键与值都是字符串;
1.1.4定义与map有点区别
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
?这是配置文件代码
<property name="properties">
<props>
<prop key="p1">ppp1</prop>
<prop key="p2">ppp2</prop>
</props>
</property>
可用autowire自动装配,一般用ByName,注意set方法名称与注入的Bean ID一致,否则会报错