一、简介
上篇文章写的有些混乱,可以略过,这篇文章开始对我们的简单spring进行改造,构建出一个BeanFactory的基本框架
二、正文
首先直接看图,我们先来学习低级容器BeanFactory。
DefaultListableBeanFactory的整个类继承关系中大概包含上面五块体系
1.BeanFactory体系
2.注册单例Bean
3.别名相关
4.FactoryBean相关
5.注册BeanDefinition
我们主要关注 1,2,5三块内容,别名不需要关注,FactoryBean的作用虽然比较重要的,但是更多的是在实例化对象,也先放在一边。
整个改造后的文件结构如图所示,其实也就是按照DefaultListableBeanFactory的结构体系去创建就可以了。
代码如下,有兴趣的同学可以一起创建,可以加深Spring的结构体系了解。
首先是BeanDefinition
package support;
public class BeanDefinition {
private Class beanClass;
public void setBeanClass(Class beanClass) {
this.beanClass = beanClass;
}
public Class getBeanClass() {
return beanClass;
}
}
然后是BeanFactory
package Factory.Interface;
/**
* 最顶层接口,提供getBean方法
*/
public interface BeanFactory {
Object getBean(String beanName) throws Exception;
}
package Factory.Interface;
/**
*扩展BeanFactory使其支持迭代Ioc容器持有的Bean对象 (先不关注)
*/
public interface ListableBeanFactory extends BeanFactory{
}
package Factory.Interface;
import Register.Interface.SingletonBeanRegistry;
/**
* 扩展BeanFactory,扩展了父类容器的方法(先不关注)
*/
public interface HierarchicalBeanFactory extends BeanFactory {
}
package Factory.Interface;
/**
* 扩展BeanFactory,能够被那些支持自动装配功能的Bean工厂实现(先不关注)
*/
public interface AutowireCapableBeanFactory extends BeanFactory{
}
创建SingletonBeanRegistry接口和他的实现类DefaultSingletonBeanRegistry
package Register.Interface;
/**
* 注册单例Bean接口
*/
public interface SingletonBeanRegistry {
/**
* 注册Bean
* @param beanName
* @param singletonObject
*/
void registerSingleton(String beanName, Object singletonObject);
/**
* 获取Bean
* @param beanName
* @return
*/
Object getSingleton(String beanName);
}
package Register.Impl;
import Register.Interface.SingletonBeanRegistry;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
@Override
public void registerSingleton(String beanName, Object singletonObject) {
addSingleton(beanName,singletonObject);
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName,singletonObject );
}
}
@Override
public Object getSingleton(String beanName) {
return this.singletonObjects.get(beanName);
}
}
package Register.Abstract;
import Register.Impl.DefaultSingletonBeanRegistry;
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
}
回到BeanFactory
package Factory.Interface;
import Register.Interface.SingletonBeanRegistry;
/**
* 继承HierarchicalBeanFactory的同时继承了 注册单例Bean的SingletonBeanRegistry
*/
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
}
package Factory.Interface;
/**
* BeanFactory集大成的接口,汇聚了所有接口的方法
*/
public interface ConfigurableListableBeanFactory extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory{
}
package Factory.Abstract;
import Factory.Interface.ConfigurableBeanFactory;
import Register.Abstract.FactoryBeanRegistrySupport;
import support.BeanDefinition;
/**
* 继承FactoryBeanRegistrySupport,实现ConfigurableBeanFactory
*/
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
@Override
public Object getBean(String beanName) throws Exception {
//调用doGetBean
return doGetBean(beanName);
}
protected Object doGetBean(String beanName) throws Exception {
//获取Bean,获取到直接返回,获取不到调用createBean抽象方法,实际会调用到子类AbstractAutowireCapableBeanFactory中createBean
Object singleton = getSingleton(beanName);
if(singleton!=null){
return singleton;
}
return createBean(beanName);
}
protected abstract Object createBean(String beanName) throws Exception;
protected abstract BeanDefinition getBeanDefinition(String beanName) throws Exception;
}
package Factory.Abstract;
import Factory.Interface.AutowireCapableBeanFactory;
import InstantiationStrategy.Impl.SimpleInstantiationStrategy;
import InstantiationStrategy.Interface.InstantiationStrategy;
import MyAnnotation.MyAutowired;
import cn.hutool.core.bean.BeanUtil;
import support.BeanDefinition;
import java.lang.reflect.Field;
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();
//createBean方法
@Override
protected Object createBean(String beanName) throws Exception {
//调用doCreateBean
Object beanInstance = doCreateBean(beanName);
return beanInstance;
}
protected Object doCreateBean(String beanName) throws Exception{
//调用createBeanInstance
Object beanInstance = createBeanInstance(beanName);
//注册Bean
registerSingleton(beanName,beanInstance);
//填充Bean属性
populateBean(beanInstance);
return beanInstance;
}
protected Object createBeanInstance(String beanName) throws Exception{
//实例化Bean
return instantiateBean(beanName);
}
protected Object instantiateBean(String beanName) throws Exception {
//调用getBeanDefinition抽象方法,实际调用子类DefaultListableBeanFactory的getBeanDefinition
BeanDefinition beanDefinition = getBeanDefinition(beanName);
//获取实例化策略创建对象
return getInstantiationStrategy().instantiate(beanName,beanDefinition);
}
protected void populateBean(Object bean) throws Exception {
//此段代码通过注解填充属性,和Spring真实处理有些不同
Class<?> aClass = bean.getClass();
//获取所有声明字段
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
//是否被MyAutowired注解修饰
MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);
if(annotation!=null){
Class<?> type = declaredField.getType();
//获取该对象,如果有则返回,没有则会创建,递归的跳出条件为两个对象都创建完成(解决循环依赖的代码的一部分)
Object o = getBean(type.getSimpleName());
//设置属性
BeanUtil.setFieldValue(bean,declaredField.getName(),o);
}
}
}
protected InstantiationStrategy getInstantiationStrategy() {
return this.instantiationStrategy;
}
}
实例化策略的接口和两个实现类
package InstantiationStrategy.Interface;
import support.BeanDefinition;
public interface InstantiationStrategy {
Object instantiate(String beanName, BeanDefinition beanDefinition)throws Exception;
}
package InstantiationStrategy.Impl;
import InstantiationStrategy.Interface.InstantiationStrategy;
import net.sf.cglib.proxy.Enhancer;
import support.BeanDefinition;
import java.lang.reflect.Constructor;
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {
@Override
public Object instantiate(String beanName, BeanDefinition beanDefinition) throws Exception {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(beanDefinition.getBeanClass());
Class clazz = beanDefinition.getBeanClass();
Constructor constructorToUse = clazz.getDeclaredConstructor();
if (null == constructorToUse) return enhancer.create();
return enhancer.create(constructorToUse.getParameterTypes(), null);
}
}
package InstantiationStrategy.Impl;
import InstantiationStrategy.Interface.InstantiationStrategy;
import support.BeanDefinition;
import java.lang.reflect.Constructor;
public class SimpleInstantiationStrategy implements InstantiationStrategy {
@Override
public Object instantiate(String beanName, BeanDefinition beanDefinition) throws Exception {
Class clazz = beanDefinition.getBeanClass();
Constructor constructorToUse = clazz.getDeclaredConstructor();
if(null != constructorToUse){
return clazz.getDeclaredConstructor(constructorToUse.getParameterTypes()).newInstance(null);
}
return constructorToUse.newInstance();
}
}
回到BeanFactory
package InstantiationStrategy.Interface;
import support.BeanDefinition;
/**
* 注册BeanDefinition接口
*/
public interface BeanDefinitionRegistry {
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws Exception;
}
DefaultListableBeanFactory
BeanFactory的最终实现类
package Factory.Impl;
import Factory.Abstract.AbstractAutowireCapableBeanFactory;
import Factory.Interface.ConfigurableListableBeanFactory;
import InstantiationStrategy.Interface.BeanDefinitionRegistry;
import MyAnnotation.MyComponent;
import cn.hutool.core.util.ClassUtil;
import support.BeanDefinition;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* BeanFactory的最终实现类
*/
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry {
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(256);
/**
* getBeanDefinition 获取BeanDefinition
* @param beanName
* @return
* @throws Exception
*/
@Override
public BeanDefinition getBeanDefinition(String beanName) throws Exception {
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
throw new Exception(beanName);
}
return bd;
}
/**
* registerBeanDefinition 注册BeanDefinition
* @param beanName
* @param beanDefinition
* @throws Exception
*/
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws Exception {
this.beanDefinitionMap.put(beanName,beanDefinition);
}
//此方法Spring对应类中无,此处用来加载MyComponent修饰类的BeanDefinition
public void loadBeanDefinition(){
//扫描包,获取MyConponent注解标记的类
Set<Class<?>> com = ClassUtil.scanPackageByAnnotation("com", MyComponent.class);
//将扫描到的class放入BeanDefiniton,存入集合
for (Class<?> aClass : com) {
BeanDefinition definition = new BeanDefinition();
definition.setBeanClass(aClass);
this.beanDefinitionMap.put(aClass.getSimpleName(),definition);
}
}
}
三、测试
package com;
import MyAnnotation.MyAutowired;
import MyAnnotation.MyComponent;
@MyComponent
public class DeptService {
@MyAutowired
UserService userService;
}
package com;
import MyAnnotation.MyAutowired;
import MyAnnotation.MyComponent;
@MyComponent
public class UserService {
@MyAutowired
DeptService deptService;
}
package com;
import Factory.Impl.DefaultListableBeanFactory;
import org.junit.Test;
public class test {
@Test
public void test() throws Exception {
DefaultListableBeanFactory defaultListableBeanFactory = new DefaultListableBeanFactory();
defaultListableBeanFactory.loadBeanDefinition();
Object userService = defaultListableBeanFactory.getBean("UserService");
System.out.println("");
}
}
结果是可以成功创建
本次改造主要将原来一个文件中的代码拆分到了整个BeanFactory体系代码中,不过关于其中较为核心的加载BeanDefinition 和填充对象属性部分和Spring的做法有所出入,后续会逐步改造,另外增加了实例化策略相关的内容。
本人水平有限,如有错漏,欢迎指正。
本文用作学习记录分享,如有违规请联系作者删除!