0. 前言:
视频教程:黑马程序员Java设计模式详解,全网最全23种Java设计模式
23种设计模式学的差不多了,得找个具体的框架案例上手体验一把。
在Java开发实际工作当中用的最多的开源框架便是Spring家族,于是就从Spring的Ioc特性入手,运用一定的设计模式,从Spring源码入手回顾并自定义实现Spring的Ioc 🚀 🚀
大概学习了分析了实现SpringIoc相关的类,接下来就要自己自定义SpringIOC:
现要对下面的配置文件进行解析,并自定义Spring框架的IOC对涉及到的对象进行管理。
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name = "username" value="zhangsan"></property>
<property name = "password" value="123456"></property>
</bean>
</beans>
-
先看下整体的类图:
-
项目结构:
瞬间有Spring内味了😄接下来就一个个详细学习
1. bean相关的pojo类
ApplicationContext.xml
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name = "username" value="zhangsan"></property>
<property name = "password" value="123456"></property>
</bean>
</beans>
需要将配置文件中的bean封装成对应的bean对象,得充分封装至每个标签:
- property标签:
PropertyValue
- bean标签:
BeanDefinition
- 一个bean标签中又可以有多个property标签,因此需要
MutablePropertyValues
封装
1.1 PropertyValue类
/**
* 用来封装bean标签下的property标签的属性
* name、ref、
* value等属性:给基本数据类型及String类型数据赋的值
*/
public class PropertyValue {
private String name;
private String ref;
private String value;
//省略有参无参、setter/getter方法
}
1.2 MutablePropertyValues类
一个bean标签可以有多个property子标签,所以再定义一个MutablePropertyValues类,用来存储并管理多个PropertyValue对象:
/**
* 用户存储和管理多个PropertyValue对象
*/
public class MutablePropertyValues implements Iterable<PropertyValue> {
//定义list集合对象,用来存储PropertyValue对象
private final List<PropertyValue> propertyValueList;
public MutablePropertyValues() {
this.propertyValueList = new ArrayList<PropertyValue>();
}
public MutablePropertyValues(List<PropertyValue> propertyValues) {
if (propertyValues == null) {
this.propertyValueList = new ArrayList<PropertyValue>();
} else {
this.propertyValueList = propertyValues;
}
}
//获取所有的propertyValue对象,返回以数组的形式
public PropertyValue[] getPropertyValues() {
return propertyValueList.toArray(new PropertyValue[0]);
}
//根据name属性值获取PropertyValue对象
public PropertyValue getPropertyValues(String propertyName) {
//遍历集合对象
for (PropertyValue propertyValue : propertyValueList) {
if (propertyValue.getName().equals(propertyName)) {
return propertyValue;
}
}
return null;
}
//判断集合是否为空
public boolean isEmpty() {
return propertyValueList.isEmpty();
}
//添加PropertyValue对象
//为了实现链式编程,需要在return时返回this即可
public MutablePropertyValues addPropertyValue(PropertyValue propertyValue) {
//判断集合中存储的PropertyValue对象是否和传递的重复了,如果重复了,则需要进行覆盖
for (int i = 0; i < propertyValueList.size(); i++) {
//获取集合钟每一个PropertyValue对象
PropertyValue currentPv = propertyValueList.get(i);
if (currentPv.getName().equals(propertyValue.getName())) {
propertyValueList.set(i, propertyValue);
return this;
}
}
this.propertyValueList.add(propertyValue);
return this;
}
//判断集合中是否有指定name属性的对象
public boolean contains(String propertyName) {
return getPropertyValues(propertyName) != null;
}
//获取迭代器对象
@Override
public Iterator<PropertyValue> iterator() {
return propertyValueList.iterator();
}
}
-
此类中的知识点:
final修饰的变量表示赋值之后不能再进行更改,系统赋默认值也算赋值,因此系统也不会赋默认值。
如果不在定义的时候或者构造函数中对final变量进行赋值的话,则生成的对象中final变量的值是未知的(编译器也会直接报错),因此必须进行初始化。
如果用static final同时修饰变量的话,则变量必须在定义的时候进行初始化。因为static变量属于类,在调用构造函数之前就已经被系统赋予默认值了。
如果不在定义的时候初始化,那么既无法在构造函数中初始化,系统也不会赋默认值。则该变量被定义出来是毫无意义的。
1.3 BeanDefinition类
BeanDefinition类用来封装bean信息(也就是bean标签的数据),主要包含:
- id(即bean对象的名称)
- class(需要交由spring管理的类的全类名)
- 子标签property数据(需要用到MutablePropertyValues类进行储存)
/**
* 用来封装bean标签数据
* id属性
* class 属性
* property子标签的数据
*/
public class BeanDefinition {
private String id;
private String className;
private MutablePropertyValues propertyValues;
public BeanDefinition() {
//由于在MutablePropertyValues()的构造器中已经初始化
propertyValues = new MutablePropertyValues();
}
//忽略对属性的setter/getter方法
}
2. 注册表相关类
2.1 BeanDefinitionRegistry接口
BeanDefinitionRegistry接口定义了注册表的相关操作,定义如下功能:
- 注册BeanDefinition对象到注册表中
- 从注册表中删除指定名称的BeanDefinition对象
- 根据名称从注册表中获取BeanDefinition对象
- 判断注册表中是否包含指定名称的BeanDefinition对象
- 获取注册表中BeanDefinition对象的个数
- 获取注册表中所有的BeanDefinition的名称
public interface BeanDefinitionRegistry {
//注册BeanDefinition对象到注册表中
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
//从注册表中删除指定名称的BeanDefinition对象
void removeBeanDefinition(String beanName) throws Exception;
//根据名称从注册表中获取BeanDefinition对象
BeanDefinition getBeanDefinition(String beanName) throws Exception;
boolean containsBeanDefinition(String beanName);
int getBeanDefinitionCount();
String[] getBeanDefinitionNames();
}
2.2 SimpleBeanDefinitionRegistry类
该类实现了BeanDefinitionRegistry接口,定义了Map集合作为注册表容器。
public class SimpleBeanDefinitionRegistry implements BeanDefinitionRegistry {
//定义一个容器,用来存储BeanDDefintion对象,用双列集合,储存<name,对象>
private Map<String,BeanDefinition> beanDefinitionMap = new HashMap<>();
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName,beanDefinition);
}
@Override
public void removeBeanDefinition(String beanName) throws Exception {
beanDefinitionMap.remove(beanName);
}
@Override
public BeanDefinition getBeanDefinition(String beanName) throws Exception {
return beanDefinitionMap.get(beanName);
}
@Override
public boolean containsBeanDefinition(String beanName) {
return beanDefinitionMap.containsKey(beanName);
}
@Override
public int getBeanDefinitionCount() {
return beanDefinitionMap.size();
}
@Override
public String[] getBeanDefinitionNames() {
return beanDefinitionMap.keySet().toArray(new String[0]);
}
}
3. 解析器相关类
3.1 BeanDefinitionReader接口
BeanDefinitionReader是用来解析配置文件并在注册表中注册bean的信息。定义了两个规范,其具体由子类实现
- 获取注册表的功能,让外界可以通过该对象获取注册表对象。
- 加载配置文件,并注册bean数据
public interface BeanDefinitionReader {
//获取注册表对象
BeanDefinitionRegistry getRegistry();
//加载配置文件并在注册表中进行注册
void loadBeanDefinitions(String configLocation) throws Exception;
}
3.2 XmlBeanDefinitionReader类
XmlBeanDefinitionReader类是专门用来解析xml配置文件的;该类实现BeanDefinitionReader接口并实现接口中的两个功能。
而在真正的Spring中,BeanDefinition中有针对不同配置文件的解析类:
/*
针对xml文件进行解析的类
*/
public class XmlBeanDefinitionReader implements BeanDefinitionReader {
//声明注册表对象
//需要遵循迪米特法则,提前定义,将解析为beanDefintion对象进行注册
private BeanDefinitionRegistry registry;
public XmlBeanDefinitionReader() {
registry = new SimpleBeanDefinitionRegistry();
}
@Override
public BeanDefinitionRegistry getRegistry() {
return registry;
}
@Override
public void loadBeanDefinitions(String configLocation) throws Exception {
//使用dom4进行xml配置文件的解析,具体见pom.xml文件
SAXReader reader = new SAXReader();
//获取类路径下的配置文件
InputStream is = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
Document document = reader.read(is);
//根据Document对象获取对应标签(即xml中的<beans><beans/>)
Element rootElement = document.getRootElement();//这里的根标签就是<beans><beans/>
//获取根标签下所有的beans标签对象:在<beans><beans/>中有多个bean对象
List<Element> beanElements = rootElement.elements("bean");
//遍历集合,获取每个bean对象中的属性
for (Element beanElement : beanElements) {
//获取id属性
String id = beanElement.attributeValue("id");
//获取class属性
String className = beanElement.attributeValue("class");
//获取property属性,由于一个bean可能有多个property属性,用MutablePropertyValues存储
MutablePropertyValues propertyValues = new MutablePropertyValues();
//需要再次遍历获得每一个propertyValue对象
List<Element> propertyList = beanElement.elements("property");
for (Element element : propertyList) {
String name = element.attributeValue("name");
String ref = element.attributeValue("ref");
String value = element.attributeValue("value");
PropertyValue propertyValue = new PropertyValue(name, ref, value);
propertyValues.addPropertyValue(propertyValue);
}
//将id、classname以及property属性都封装至BeanDefinition中
BeanDefinition beanDefinition = new BeanDefinition();
beanDefinition.setId(id);
beanDefinition.setClassName(className);
beanDefinition.setPropertyValues(propertyValues);
//并将封装好的BeanDefinition注册至表中
registry.registerBeanDefinition(id,beanDefinition);
}
}
}
<!--dom4j 的坐标-->
<dependencies>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
4. IOC容器相关类
4.1 BeanFactory接口
public interface BeanFactory {
//根据bean对象名称获取bean对象
Object getBean(String name) throws Exception;
//根据bean对象的名称获取bean对象,并进行类型转换(泛型方法)
<T> T getBean(String name,Class<? extends T> clazz) throws Exception;
}
<T> T
表示返回值是一个泛型,传递啥,就返回啥类型的数据,而单独的T
就是表示限制你传递的参数类型,这个案例中,通过一个泛型的返回方式,获取每一个集合中的第一个数据, 通过返回值<T> T
和T
的两种方法实现
方法返回值前的的左右是告诉编译器,当前的方法的值传入类型可以和类初始化的泛型类不同,也就是该方法的泛型类可以自定义,不需要跟类初始化的泛型类相同
4.2 ApplicationContext接口
该接口的所以的子实现类对bean对象的创建都是非延时的,所以在该接口中定义 refresh()
方法,该方法主要完成以下两个功能:
- 加载配置文件。
- 根据注册表中的BeanDefinition对象封装的数据进行bean对象的创建。
//定义非延迟性加载
public interface ApplicationContext extends BeanFactory {
//进行配置文件加载并进行对象创建
void refresh() throws IllegalStateException, Exception;
}
4.3 AbstractApplicationContext类
-
作为ApplicationContext接口的子类,所以该类也是非延时加载,所以需要在该类中定义一个Map集合,作为bean对象存储的容器。
-
声明BeanDefinitionReader类型的变量,用来进行xml配置文件的解析,符合单一职责原则。
BeanDefinitionReader类型的对象创建交由子类实现,因为只有子类明确到底创建BeanDefinitionReader哪儿个子实现类对象。
/*
ApplicationContext接口的子实现类,用于立即加载
*/
public abstract class AbstractApplicationContext implements ApplicationContext {
//声明解析器变量
protected BeanDefinitionReader beanDefinitionReader;
//定义用于储存bean对象的map容器,在此不考虑线程安全 直接用hashmap
protected Map<String,Object> singletonObjects = new HashMap<>();
//声明配置文件路径的变量
protected String configLocation ;
@Override
public void refresh() throws Exception {
//加载beanDefinition对象
beanDefinitionReader.loadBeanDefinitions(configLocation);
//初始化bean
finishBeanInitialization();
}
//bean的初始化:
private void finishBeanInitialization() throws Exception{
//获取注册表对象
BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
//获取BeanDefinition对象
String[] beanDefinitionNames = registry.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
//对bean进行初始化
getBean(beanDefinitionName);
}
}
}
注意:该类finishBeanInitialization()方法中调用getBean()方法使用到了模板方法模式。
4.4 ClassPathXmlApplicationContext类
该类主要是加载类路径下的配置文件,并进行bean对象的创建,主要完成以下功能:
- 在构造方法中,创建BeanDefinitionReader对象。
- 在构造方法中,调用refresh()方法,用于进行配置文件加载、创建bean对象并存储到容器中。
- 重写父接口中的getBean()方法,并实现依赖注入操作。
/*
IOC容器具体的子实现类,用于加载类路径下的xml格式的配置文件
*/
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {
public ClassPathXmlApplicationContext(String configLoaction) {
this.configLocation = configLoaction;
//构建解析器对象
beanDefinitionReader = new XmlBeanDefinitionReader();
try {
this.refresh();
} catch (Exception ignored) {
}
}
//根据bean对象的名称获取bean对象
@Override
public Object getBean(String name) throws Exception {
//判断容器中是否包含指定名称的bean对象,即注册表中是否有对应的beanDefinition对象
//如果包含,直接返回即可,如果不包含,则需要自行创建
Object obj = singletonObjects.get(name);
if (obj != null) {
return obj;
}
//获取BeanDefinition对象
BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
BeanDefinition beanDefinition = registry.getBeanDefinition(name);
if (beanDefinition == null) {
return null;
}
//获取bean信息中的classname
String className = beanDefinition.getClassName();
//并通过反射创建对象
Class<?> clazz = Class.forName(className);
Object beanObj = clazz.newInstance();
//重点:进行依赖注入操作
MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
//1.获取对应的property对象
for (PropertyValue propertyValue : propertyValues) {
//2.获取property对象及其内部的属性
String propertyName = propertyValue.getName();
String value = propertyValue.getValue();
String ref = propertyValue.getRef();
//3.对value和ref属性判断赋值(只做setter注入)
// 3.1对ref执行对象的注入
if (ref != null && !"".equals(ref)) {
Object bean = getBean(ref);
String methodName = StringUtils.getStterMethoByFieldName(propertyName);
Method[] methods = clazz.getMethods();
// 3.1.1用反射获取对应方法,创建对象
for (Method method : methods) {
if (method.getName().equals(methodName)) {
method.invoke(beanObj, bean);
}
}
}
// 3.2 value判断只做String处理
if (value != null && !"".equals(value)) {
String methodName = StringUtils.getStterMethoByFieldName(propertyName);
Method method = clazz.getMethod(methodName, String.class);
method.invoke(beanObj, value);
}
}
//在返回beanObj对象之前,需要将对象存储至map容器中
singletonObjects.put(name,beanObj);
return beanObj;
}
@Override
public <T> T getBean(String name, Class<? extends T> clazz) throws Exception {
Object bean = getBean(name);
if(bean != null) {
return clazz.cast(bean);
}
return null;
}
}
5. 自定义Spring IOC总结
5.1 使用过程
-
将my_spring项目通过maven直接安装到本地仓库
-
新建名为my_spring_demo的maven项目并引入my_spring 坐标
<artifactId>my_spring_demo</artifactId> <dependencies> <dependency> <groupId>org.itstack</groupId> <artifactId>my_spring</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans> <!--文件头为模板自带,下面的bean属自己配置--> <bean id="userDao" class="com.wayne.dao.impl.UserDaoImpl"> <property name="username" value="Bruce Wayne"/> <property name="nickname" value="Batman"/> </bean> <bean id="userService" class="com.wayne.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"/> </bean> </beans>
-
调用<自定义Spring IOC>(上)的例子,执行情况如下:
public class UserController { public static void main(String[] args) throws Exception { //1.创建Spring的容器对象 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.从容器对象中获取UserService对象 System.out.println("是否调用对象的分割线=======上面创建对象========下面调用对象====================="); UserService userService = applicationContext.getBean("userService", UserService.class); //3.调用UserService对象的add方法 userService.add(); } }
运行结果:
成功注入了UserDao和UserService对象,并执行了对应方法
5.2 设计模式总结
-
工厂模式:
- 这个使用简单工厂模式 + xml配置文件的方式(
这个应该不用说明了)
- 这个使用简单工厂模式 + xml配置文件的方式(
-
单例模式:
-
Spring IOC管理的bean对象都是单例的,此处的单例不是通过构造器进行单例的控制的,而是Spring框架对每一个bean只创建了一个对象,
-
具体体现在对bean的初始化上:
-
-
-
模板方法模式:
-
AbstractApplicationContext类中的finishBeanInitialization()方法调用了子类的getBean()方法,因为getBean()的实现和环境息息相关:
-
在Spring中:
-
在my_spring中
-
-
-
迭代器模式:
- 对于MutablePropertyValues类定义使用到了迭代器模式,因为此类存储并管理PropertyValue对象,也属于一个容器,所以给该容器提供一个遍历方式
-
另外:
spring框架其实使用到了很多设计模式:- 如AOP使用到了代理模式,
- 选择JDK代理或者CGLIB代理使用到了策略模式,
- 还有适配器模式,装饰者模式,观察者模式等(在之前的对应的设计模式中有所涉及)
5.2.1 与Spirng比较
spring框架底层是很复杂的,进行了很深入的封装,并对外提供了很好的扩展性。
而我们自定义SpringIOC有以下几个目的:
- 了解Spring底层对对象的大体管理机制。
- 了解设计模式在具体的开发中的使用。
- 以后学习spring源码,通过该案例的实现,可以降低spring学习的入门成本。