一、构造器实例化(默认方式):要求Bean对象中要提供无参构造
TypeDao:bean对象
public class TypeDao {
private String str;
//无参构造
public TypeDao() {
}
public TypeDao(String str) {
this.str = str;
}
public void test(){
System.out.println("TypeDao Test...");
}
}
配置文件:
<?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.xxxx.dao.TypeDao"></bean>
</beans>
实例化测试:
BeanFactory factory = new ClassPathXmlApplicationContext("spring02.xml");
TypeDao typeDao = (TypeDao) factory.getBean("typeDao");
typeDao.test();
如果没有提供无参构造则会报错:
二、静态工厂实例化:
Bean对象:
public class TypeService {
public void test(){
System.out.println("TypeService Test...");
}
}
静态工厂类:
/**
* Created by Jack on 2020.12.18.
* 定义静态工厂类
*/
public class StaticFactory {
/**
* 定义对应的静态方法
* @return
*/
public static TypeService createService(){
return new TypeService();
}
}
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">
<!--
静态工厂实例化
1、定义工厂类及对应的静态方法
2、配置bean对象对应的工厂类及静态方法
id:需要被实例化的bean对象的id
class:静态工厂类的路径
factory-method:静态工厂类中实例化bean对象的方法
-->
<bean id="typeService" class="com.xxxx.factory.StaticFactory" factory-method="createService"></bean>
</beans>
实例化测试:
//静态工厂实例化
TypeService typeService = (TypeService) factory.getBean("typeService");
typeService.test();
三、实例化工厂实例化
Bean对象:
public class TypeController {
public void test(){
System.out.println("TypeController Test...");
}
}
实例化工厂:
/**
* Created by Jack on 2020.12.18.
* 定义实例化工厂
*/
public class InstanceFactory {
/**
* 定义方法
* @return
*/
public TypeController createController(){
return new TypeController();
}
}
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">
<!--
实例化工厂
1、定义工厂类及对应的方法
2、配置工厂对象
3、配置bean对象对应的工厂对象及工程方法
factory-bean:工厂对象对应的id属性值
factory-method:工厂类中的方法
-->
<!--工厂对象-->
<bean id="instanceFactory" class="com.xxxx.factory.InstanceFactory"></bean>
<!--bean对象-->
<bean id="typeController" factory-bean="instanceFactory" factory-method="createController"></bean>
</beans>
实例化测试:
//实例化工厂实例化
TypeController typeController = (TypeController) factory.getBean("typeController");
typeController.test();