版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37606901/article/details/82532049
有些时候,项目中需要通过工厂类来创建 Bean 实例,而不能像前面例子中似的,直接由 Spring 容器来装配 Bean 实例。使用工厂模式创建 Bean 实例,就会使工厂类与要创建的
Bean 类耦合到一起。
(1)将动态工厂 Bean 作为普通 Bean 使用
将动态工厂 Bean 作为普通 Bean 来使用是指,在配置文件中注册过动态工厂 Bean 后, 测试类直接通过 getBean()获取到工厂对象,再由工厂对象调用其相应方法创建相应的目标对象。配置文件中无需注册目标对象的 Bean。因为目标对象的创建不由 Spring 容器来管理。
那么下面直接上代码:
接口:
package com.bjpowernode.ba02;
public interface ISomeService {
void doSome();
}
实现类:
package com.bjpowernode.ba02;
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.bjpowernode.ba02;
public class ServiceFactory {
public ISomeService getSomeService() {
return new SomeServiceImpl();
}
}
测试类:
package com.bjpowernode.ba02;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01() {
ISomeService service = new ServiceFactory().getSomeService();
service.doSome();
}
}
这个代码肯定是正确的,而且运行出来结果。但是呢,这个代码还是有很大的耦合的。这段代码不仅有工厂和测试类的耦合还有实现类和工厂的耦合。所以我们需要进行改进:
所以我们通过配置文件解耦:
增加 applicationCondex.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">
<!-- 注册动态工厂 -->
<bean id="factory" class="com.bjpowernode.ba02.ServiceFactory"/>
<!-- 注册Service:动态工厂Bean -->
<bean id="myService" factory-bean="factory" factory-method="getSomeService"/>
</beans>
所以我们进行的修改测试类为:
package com.bjpowernode.ba02;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01() {
ISomeService service = new ServiceFactory().getSomeService();
service.doSome();
}
@Test
public void test02() {
// 创建容器对象,加载Spring配置文件
String resource = "com/bjpowernode/ba02/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
通过这样的设置就会解决了第一个程序会出现的耦合。