基于xml的ioc的配置分为以下四种情况:
1、基于无参数构造函数
2、基于有参构造函数实例化(这篇文章暂时不讲,因为这个更多是依赖注入的内容)
2、基于静态工厂方法实例化
3、基于实例工厂方法实例化
不同的实例化方式对象和组件ioc的配置方式也不同
基于无参数构造函数
package com.atguigu.ioc_01;
public class HappyComponent {
//默认包含无参数构造函数
public void doWork() {
System.out.println("HappyComponent.doWork");
}
}
基于静态工厂方法实例化
package com.atguigu.ioc_01;
public class ClientService {
private static ClientService clientService = new ClientService();
private ClientService() {}
public static ClientService createInstance() {
return clientService;
}
}
基于实例工厂方法实例化
package com.atguigu.ioc_01;
public class DefaultServiceLocator {
private static ClientServiceImpl clientService = new ClientServiceImpl();
public ClientServiceImpl createClientServiceInstance() {
return clientService;
}
}
package com.atguigu.ioc_01;
public class ClientServiceImpl {
}
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 可以使用无参构造函数实例化的组件,如何进行ioc配置呢?
<bean 一个组件信息代表一个组件对象
id 组件的标识(名字随便取就行) 唯一 方便后期读取
class 组件的类的权限定符
将一个组件类 - 声明两个组件信息 - [默认是单例模式] - 会实例化两个组件对象
-->
<bean id="happyComponent1" class="com.atguigu.ioc_01.HappyComponent"/>
<bean id="happyComponent2" class="com.atguigu.ioc_01.HappyComponent"/>
<!-- 静态工厂类如何声明工厂方法进行ioc配置
<bean
id="组件的标识"
class="工厂类的全限定符"
factory-method="工厂方法"
-->
<bean id="clientService" class="com.atguigu.ioc_01.ClientService" factory-method="createInstance"/>
<!--非静态工厂如何声明ioc配置-->
<!--首先配置工厂类的组件信息-->
<bean id="defaultServiceLocator" class="com.atguigu.ioc_01.DefaultServiceLocator"/>
<!--通过指定非静态工厂对象和方法名 来配置生成ioc信息-->
<bean id="clientService2" factory-bean="defaultServiceLocator" factory-method="createClientServiceInstance"/>
</beans>