Small Spring系列一:BeanFactory(一)
人生如逆旅,我亦是行人。

前言
Spring是一个开放源代码的设计层面框架,它解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用。
准备
bean-v1.xml配置bean的信息BeanDefinition用于存放bean的定义BeanFactory获取bean的信息,实例化bean`BeanFactoryTest测试BeanFactory是否可用
bean-v1.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id = "nioCoder"
class = "com.niocoder.service.v1.NioCoderService">
</bean>
<bean id ="invalidBean"
class="xxx.xxx">
</bean>
</beans>
BeanDefinition
bean-v1.xml中定义了每个bean,但这些信息我们该如何存储呢?
spring是通过BeanDefinition接口来描述bean的定义
BeanDefinition
package com.niocoder.beans;
/**
* bean.xml bean的定义
* @author zhenglongfei
*/
public interface BeanDefinition {
/**
* 获取bean.xml中 bean的全名 如 "com.niocoder.service.v1.NioCoderService"
* @return
*/
String getBeanClassName();
}
GenericBeanDefinition
GenericBeanDefinition实现了BeanDefinition接口
package com.niocoder.beans.factory.support;
import com.niocoder.beans.BeanDefinition;
/**
* BeanDefinition 实现类
*
* @author zhenglongfei
*/
public class GenericBeanDefinition implements BeanDefinition {
private String id;
private String beanClassName;
public GenericBeanDefinition(String id, String beanClassName) {
this.id = id;
this.beanClassName = beanClassName;
}
public String getBeanClassName() {
return this.beanClassName;
}
}
BeanFactory
我们已经使用BeanDefinition来描述bean-v1.xml的bean的定义,下面我们使用BeanFactory来获取bean的实例
BeanFactory
package com.niocoder.beans.factory;
import com.niocoder.beans.BeanDefinition;
/**
* 创建bean的实例
* @author zhenglongfei
*/
public interface BeanFactory {
/**
* 获取bean的定义
* @param beanId
* @return
*/
BeanDefinition getBeanDefinition(String beanId);
/**
* 获取bean的实例
* @param beanId
* @return
*/
Object getBean(String beanId);
}
DefaultBeanFactory
DefaultBeanFactory实现了BeanFactory接口
package com.niocoder.beans.factory.support;
import com.niocoder.beans.BeanDefinition;
import com.niocoder.beans.factory.BeanCreationException;
import com.niocoder.beans.factory.BeanDefinitionStoreException;
import com.niocoder.beans.factory.BeanFactory;
import com.niocoder.util.ClassUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* BeanFactory的默认实现类
*
* @author zhenglongfei
*/
public class DefaultBeanFactory implements BeanFactory {
private static final String ID_ATTRIBUTE = "id";
private static final String CLASS_ATTRIBUTE = "class";
/**
* 存放BeanDefinition
*/
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
/**
* 根据文件名称加载,解析bean.xml
*
* @param configFile
*/
public DefaultBeanFactory(String configFile) {
loadBeanDefinition(configFile);
}
/**
* 具体解析bean.xml的方法 使用dom4j
*
* @param configFile
*/
private void loadBeanDefinition(String configFile) {
ClassLoader cl = ClassUtils.getDefaultClassLoader();
try (InputStream is = cl.getResourceAsStream(configFile)) {
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
Element root = doc.getRootElement();
Iterator<Element> elementIterator = root.elementIterator();
while (elementIterator.hasNext()) {
Element ele = elementIterator.next();
String id = ele.attributeValue(ID_ATTRIBUTE);
String beanClassName = ele.attributeValue(CLASS_ATTRIBUTE);
BeanDefinition bd = new GenericBeanDefinition(id, beanClassName);
this.beanDefinitionMap.put(id, bd);
}
} catch (Exception e) {
throw new BeanDefinitionStoreException("IOException parsing XML document", e);
}
}
@Override
public BeanDefinition getBeanDefinition(String beanId) {
return this.beanDefinitionMap.get(beanId);
}
@Override
public Object getBean(String beanId) {
BeanDefinition bd = this.getBeanDefinition(beanId);
if (bd == null) {
throw new BeanCreationException("BeanDefinition does not exist");
}
ClassLoader cl = ClassUtils.getDefaultClassLoader();
String beanClassName = bd.getBeanClassName();
try {
// 使用反射创建bean的实例,需要对象存在默认的无参构造方法
Class<?> clz = cl.loadClass(beanClassName);
return clz.newInstance();
} catch (Exception e) {
throw new BeanCreationException("Bean Definition does not exist");
}
}
}
BeanFactoryTest
以上,我们已经创建了bean.xml,BeanDefinition来描述bean的定义,并且使用BeanFactory来获取bean的实例。下面我们来测试一下BeanFactory是否可用。
package com.niocoder.test.v1;
import com.niocoder.beans.BeanDefinition;
import com.niocoder.beans.factory.BeanCreationException;
import com.niocoder.beans.factory.BeanDefinitionStoreException;
import com.niocoder.beans.factory.BeanFactory;
import com.niocoder.beans.factory.support.DefaultBeanFactory;
import com.niocoder.service.v1.NioCoderService;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* BeanFactory 测试类
*/
public class BeanFactoryTest {
/**
* 测试获取bean
*/
@Test
public void testGetBean() {
BeanFactory factory = new DefaultBeanFactory("bean-v1.xml");
BeanDefinition bd = factory.getBeanDefinition("nioCoder");
assertEquals("com.niocoder.service.v1.NioCoderService", bd.getBeanClassName());
NioCoderService nioCoderService = (NioCoderService) factory.getBean("nioCoder");
assertNotNull(nioCoderService);
}
/**
* 测试无效的bean
*/
@Test
public void testInvalidBean() {
BeanFactory factory = new DefaultBeanFactory("bean-v1.xml");
try {
factory.getBean("invalidBean");
} catch (BeanCreationException e) {
return;
}
Assert.fail("expect BeanCreationException ");
}
/**
* 测试无效的xml
*/
@Test
public void testInvalidXML() {
try {
new DefaultBeanFactory("xxx.xml");
} catch (BeanDefinitionStoreException e) {
return;
}
Assert.fail("expect BeanDefinitionStoreException ");
}
}
代码下载
类图

Small Spring系列一:BeanFactory(一)的更多相关文章
- 转:Spring系列之beanFactory与ApplicationContext
原文地址:Spring系列之beanFactory与ApplicationContext 一.BeanFactoryBeanFactory 是 Spring 的“心脏”.它就是 Spring IoC ...
- Spring系列之beanFactory与ApplicationContext
一.BeanFactoryBeanFactory 是 Spring 的“心脏”.它就是 Spring IoC 容器的真面目.Spring 使用 BeanFactory 来实例化.配置和管理 Bean. ...
- 深入理解Spring系列之三:BeanFactory解析
转载 https://mp.weixin.qq.com/s?__biz=MzI0NjUxNTY5Nw==&mid=2247483824&idx=1&sn=9b7c2603093 ...
- Spring 系列: Spring 框架简介 -7个部分
Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...
- Spring 系列: Spring 框架简介(转载)
Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...
- 通俗化理解Spring3 IoC的原理和主要组件(spring系列知识二总结)
♣什么是IoC? ♣通俗化理解IoC原理 ♣IoC好处 ♣工厂模式 ♣IoC的主要组件 ♣IoC的应用实例 ♣附:实例代码 1.什么是IoC(控制反转)? Spring3框架的核心是实现控制反转(Io ...
- 狗鱼IT教程:推介最强最全的Spring系列教程
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建. 简单来说,Spring是一个分层的JavaSE/EEfull-stack( ...
- Spring系列之IOC的原理及手动实现
目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 导语 Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架.也是几乎所有J ...
- Spring系列之DI的原理及手动实现
目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 前言 在上一章中,我们介绍和简单实现了容器的部分功能,但是这里还留下了很多的问题.比如我们在构造bean实例的时 ...
- Spring系列之AOP的原理及手动实现
目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 引入 到目前为止,我们已经完成了简易的IOC和DI的功能,虽然相比如Spring来说肯定是非常简陋的,但是毕竟我 ...
随机推荐
- 【0802 | Day 7】Python进阶(一)
目 录 数字类型的内置方法 一.整型内置方法(int) 二.浮点型内置方法(float) 字符串类型内置方法 一.字符串类型内置方法(str) 二.常用操作和内置方法 优先掌握: 1.索引取值 2. ...
- 阿里P8架构师浅析——MySQL的高并发优化
一.数据库结构的设计 1.数据行的长度不要超过8020字节,如果超过这个长度的话在物理页中这条数据会占用两行从而造成存储碎片,降低查询效率. 2.能够用数字类型的字段尽量选择数字类型而不用字符串类型的 ...
- DRF (Django REST framework) 中的路由Routers
路由Routers 注意是:对于视图集ViewSet!!!我们除了可以自己手动指明请求方式与动作action之间的对应关系外,还可以使用Routers来帮助我们快速实现路由信息. REST frame ...
- Mybatis批处理(批量查询,更新,插入)
mybatis批量查询 注意这里的 in 和 <trim prefix="(" suffix=")"> 以及 in ( )的三种方式的(例1(推 ...
- Eclipse配置初始化(自用)
以上都是性能调优的配置,下面是其他常用的配置和优化 设置utf-8编码 window -> preferences -> General -> workplace中text file ...
- 计算机基础+python初阶
今日内容: 1.计算机基础知识 2.python简介 3.快速入门 今日内容: 一.计算机基础 1. 计算机什么组成的 输入输出设备 cpu 硬盘 内存 中央处理器 处理各种数据 相当于人的大脑 内存 ...
- 05_指针之New()函数的使用
1.new函数是一个内置函数,表达式new(T)创建一个未命名的T类型变量,初始化为T类型的零值,并返回其地址(地址类型为*T)2.p:=new(int),q:=new(int)==>p!=q ...
- 《GO Home Trash!》UML类图,ER图以及数据库设计
<Go Home Trash!>UML类图 ER图以及数据库中数据表 分析: 这款软件经过我们前期的讨论以及需求分析,确定了用户,客服以及管理员三个实体.在设计UML类图时,对各个实体之间 ...
- Python从入门到精通之环境搭建
本章内容: Windows系统环境搭建 Linux系统环境搭建 Mac OS系统环境搭建 一.下载python安装包 下载地址:https://www.python.org/downloads/ 二. ...
- 在Azure云上实现postgres主备切换
以下是工作上实现postgres主备切换功能所用到的代码和步骤,中间走了不少弯路,在此记录下.所用到的操作系统为centos 7.5,安装了两台服务器,hostname为VM7的为Master,VM8 ...