欢迎访问我的博客shammgodyoung
项目背景
主要是为了学习Spring的使用,同时也能了解下工厂模式
创建一个web项目
使用idea创建一个web项目,具体过程就不赘述了
导入jar包
编写相关测试代码
- Service接口及实现类
// Service接口
public interface UserService {
void sayHello();
}
// Service实现类(2个)
public class UserServiceImpl01 implements UserService {
@Override
public void sayHello() {
System.out.println("UserServiceImpl01 say hello!");
}
}
public class UserServiceImpl02 implements UserService {
@Override
public void sayHello() {
System.out.println("UserServiceImpl02 say hello!");
}
}
- 配置文件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">
<bean id="userService01" class="com.dy.demo.service.impl.UserServiceImpl01"/>
<bean id="userService02" class="com.dy.demo.service.impl.UserServiceImpl02"/>
</beans>
- 从工厂获取bean
public class ServiceFactory {
public static UserService getBean(String name) throws Exception {
UserService userService = null;
SAXReader reader = new SAXReader();
File file = new File("G:\\BaiduNetdiskDownload\\projects\\web-demo\\spring-test\\config\\applicationContext.xml");
Document read = reader.read(file); // 读取文件
Element rootElement = read.getRootElement(); // 获取根标签
Iterator iterator = rootElement.elementIterator(); // 创建Iterator对象,用于后面遍历子标签
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
String id = element.attributeValue("id"); // 获取子标签中id的值
// 如果与传入的name一致就通过反射获取该实例
if (!StringUtils.isEmpty(name) && name.equals(id)) {
String className = element.attributeValue("class");
userService = (UserService) Class.forName(className).newInstance();
}
}
return userService;
}
}
- 编写测试类
public class TestService {
public static void main(String[] args) throws Exception {
UserService userService = ServiceFactory.getBean("userService02");
userService.sayHello();
}
}
- 测试通过