上一篇博文中介紹了Spring中配置bean的方法。那麼問題來了,如果bean中有一些參數是依賴了另外一些bean或者是另外一些參數該怎麼配置呢?這篇博文就說說如何解決這個問題
1.set方法注入
例如:如果UserServiceImpl的實現類中有一個屬性,那麼使用Spring框架的IOC功能時,可以通過依賴注入把該屬性的值傳入進來!!
具體的配置如下
<bean id="us" class="com.demo1.UserServiceImpl">
<property name="uname" value="小風"/>
</bean>
類如下
public class UserServiceImpl implements UserService {
private String name;
public void setName(String name) {
this.name = name;
}
...
}
<!-- 演示的依賴注入,依賴的是類,不是字符串,用ref屬性 -->
<bean id="customerDao" class="com.demo3.CustomerDaoImpl"/>
<bean id="customerService" class="com.demo3.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
public class CustomerServiceImpl {
// 提供成員屬性,提供set方法
private CustomerDaoImpl customerDao;
public void setCustomerDao(CustomerDaoImpl customerDao) {
this.customerDao = customerDao;
}
public void save(){
System.out.println("我是業務層service....");
customerDao.save();
}
}
2.構造方法的注入方式
編寫Java的類,提供構造方法
public class Car {
private String name;
private double money;
public Car(String name, double money) {
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "Car [name=" + name + ", money=" + money + "]";
}
}
編寫配置文件,如果構造中有引用,用ref=""代替value
<bean id="car" class="com.demo4.Car">
<constructor-arg name="name" value="大奔"/>
<constructor-arg name="money" value="100"/>
</bean>
3.集合(List,Set,Map)的注入
1. 如果是數組或者List集合,注入配置文件的方式是一樣的
<bean id="collectionBean" class="com.itheima.demo5.CollectionBean">
<property name="arrs">
<list>
<value>美美</value> // 如果是對象類型<ref bean="引用"/>,set集合均相同
<value>小風</value>
</list>
</property>
</bean>
2. 如果是Set集合,注入的配置文件方式如下:
<property name="sets">
<set>
<value>哈哈</value>
<value>呵呵</value>
</set>
</property>
3. 如果是Map集合,注入的配置方式如下:
<property name="map">
<map>
<entry key="老王2" value="38"/> // 對象是<entry key-ref="老王2" value-ref="38"/>
<entry key="鳳姐" value="38"/>
<entry key="如花" value="29"/>
</map>
</property>
4.Spring框架的配置文件分開管理
例如:在配置文件夾下多創建了一個配置文件,現在是兩個核心的配置文件,那麼加載這兩個配置文件的方式有兩種!
* 主配置文件中包含其他的配置文件:
<import resource="applicationContext2.xml"/>
* 工廠創建的時候直接加載多個配置文件:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml","applicationContext2.xml");