spring Ioc spring Ioc 容器的实例化有三种方式
- 构造器实例化
- 静态工厂实例化
- 实例化工厂实例化
构造器实例化
javaBean对象必须提供一个空参数的构造方法,才可以
typeDao
public class TypeDao {
public void test(){
System.out.println("TypeDao Test...");
}
}
spring 配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
构造器实例化
对应Bean对象需要提供空构造
-->
<bean id="typeDao" class="com.xxx.dao.TypeDao"></bean>
</beans>
静态工厂实例化
创建一个工厂对象
StaticFactory
package com.xxx.factory;
import com.xxx.service.TypeService;
/**
* 定义静态工厂类
*/
public class StaticFactory {
public static TypeService createService() {
// 这里可以操作自己想做的东西
return new TypeService();
}
}
配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
静态工厂实例化
1.定义工厂类以及对应的静态方法
2.配置bean队形对应的工厂类及静态方法
id: 需要被实例化的bean对象的id
clas: 静态工厂类的路径
factory-method: 静态工厂类中实例化bean对象的静态方法
-->
<bean id="typeService" class="com.xxx.factory.StaticFactory" factory-method="createService"></bean>
</beans>
实例化工厂实例化
创建一个实例化的工厂
package com.xxx.factory;
import com.xxx.controller.TypeController;
/**
* 定义实例化工厂
*/
public class InstanceFactory {
public TypeController createTypeController(){
return new TypeController();
}
}
配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
实例化工厂实例化
1.定义工厂类以及对应的方法
2.配置工程对象
3.配置bean对象对应的工厂对象及工厂方法
factory-bean 工厂对象对应的id
factory-method 工厂类中的方法
-->
<bean id="instanceFactory" class="com.xxx.factory.InstanceFactory"></bean>
<bean id="typeController" factory-bean="instanceFactory" factory-method="createTypeController"></bean>
</beans>
区别
静态工厂实例化和实例化工厂实例化区别
静态工厂是在静态方法中返回的
实例化工厂实例化是在非静态方法中返回的