spring提供三种实例化方式:默认构造、静态工厂、实例工厂
一、默认(无参)构造:就是经常使用的方式,xml-><bean id="" class=""></bean>
二、静态工厂:工厂工具类,提供的方法都是static静态的
1、沿用上一个工程,基本结构如下:
2、新建CategoryService类
package hjp.spring.staticinstance; public class CategoryService { public void addCategory() { System.out.println("add category"); } }
3、新建工厂类MyFactory
package hjp.spring.staticinstance; public class MyFactory { public static CategoryService createService() { return new CategoryService(); } }
4、新建beans.xml配置文件
<?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"> <!-- 将工厂交予spring,自定义工厂创建对象由spring管理 class 指定工厂实现类 factory-method 确定静态方法 --> <bean id="categoryServiceId" class="hjp.spring.staticinstance.MyFactory" factory-method="createService"></bean> </beans>
5、新建测试类
package hjp.spring.staticinstance; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp { @Test public void demo1() { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("hjp/spring/staticinstance/beans.xml"); CategoryService categoryService=applicationContext.getBean("categoryServiceId",CategoryService.class); categoryService.addCategory(); } }
三、实例工厂:
1、沿用上一个工程,基本结构如下:
2、新建OrderService类
package hjp.spring.commeninstance; public class OrderService { public void addOrder() { System.out.println("add Order"); } }
3、新建工厂类MyFactory
package hjp.spring.commeninstance; public class MyFactory { public OrderService createService() { return new OrderService(); } }
4、新建beans.xml配置文件
<?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"> <!-- 1、创建工厂 --> <bean id="myFactoryId" class="hjp.spring.commeninstance.MyFactory"></bean> <!-- 2、实例工厂创建对象,交予spring管理 factory-bean 确定实例工厂 factory-method 确定方法 --> <bean id="orderServiceId" factory-bean="myFactoryId" factory-method="createService"></bean> </beans>
5、新建测试类
package hjp.spring.commeninstance; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp { @Test public void demo1() { //获得容器 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("hjp/spring/commeninstance/beans.xml"); //获得对象 OrderService orderService = applicationContext.getBean("orderServiceId", OrderService.class); orderService.addOrder(); } }
时间: 2024-11-07 03:58:53