版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37606901/article/details/82258624
使用工厂模式中的静态工厂来创建实例 Bean。
此时需要注意,静态工厂无需工厂实例,所以不再需要定义静态工厂。
而对于工厂所要创建的 Bean,其不是由自己的类创建的,所以无需指定自己的类。但其是由工厂类创建的,所以需要指定所用工厂类。故 class 属性指定的是工厂类而非自己的类。当然,还需要通过 factory-method 属性指定工厂方法。
下面是代码:
applicationContext.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">
<!-- 注册Service:静态工厂Bean -->
<bean id="myService" class="com.myproject.ba03.ServiceFactory" factory-method="getSomeService"/>
</beans>
这个是ISomeService接口
package com.myproject.ba03;
public interface ISomeService {
void doSome();
}
工厂:
package com.myproject.ba03;
public class ServiceFactory {
public static ISomeService getSomeService() {
return new SomeServiceImpl();
}
}
SomeServiceImpl实现类:
package com.myproject.ba03;
public class SomeServiceImpl implements ISomeService {
private int a;
public SomeServiceImpl() {
System.out.println("执行无参构造器");
}
/*
public SomeServiceImpl(int a) {
this.a = a;
}
*/
@Override
public void doSome() {
System.out.println("执行doSome()方法");
}
}
测试类:
package com.myproject.ba03;
/*因为是静态的工厂bean---所以在applicationContext.xml里面不需要再注册工厂了。删去如下内容:
* <bean id="factory" class="com.myproject.ba3.ServiceFactory"/>
<!-- 注册Service:动态工厂Bean -->
<bean id="myService" factory-bean="factory" factory-method="getSomeService"/>
* 修改成:
* <!-- 注册Service:静态工厂Bean -->
<bean id="myService" class="com.myproject.ba03.ServiceFactory" factory-method="getSomeService"/>
* 注意:如果是 <bean id="myService" class="com.myproject.ba03.ServiceFactory">因为有class,所以会new 出一个工厂,但是如果是下面这个,而且后面还多了一些属性的话:
* <bean id="myService" class="com.myproject.ba03.ServiceFactory" factory-method="getSomeService"/>---意思是:类名.getSomeService就会这直接创建了myService对象
* 从而使得我的class不是new出来的了。---------静态工厂是不需要进行创建对象的,直接是 类名. 的引用
*
* **/
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01() {
// 创建容器对象,加载Spring配置文件
String resource = "com/myproject/ba03/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
}