Spring中通过工厂获取bean简单实现

Spring中通过工厂获取bean简单实现

欢迎访问我的博客shammgodyoung

项目背景

主要是为了学习Spring的使用,同时也能了解下工厂模式

创建一个web项目

使用idea创建一个web项目,具体过程就不赘述了

导入jar包

所需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();
    }
}
  • 测试通过
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值