当我们自己想实现一个Spring框架的时候,想想我们需要实现哪些功能。
先从最基础的部分开始,我们首先需要一个容器,我们可以通过这个容器获取bean。那容器里的bean是从哪来的呢?
然后我们再考虑需要将bean注册到容器里面。
我们定义BeanFactoy作为容器,定义BeanDefinition作为bean的注册类。具体实现如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class BeanFactory { private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(); public void registerBeanDefinition(String name, BeanDefinition obj) { beanDefinitionMap.put(name, obj); } public Object getBean(String name) { return beanDefinitionMap.get(name).getBean(); } }BeanFactory
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class BeanDefinition { private Object bean; public BeanDefinition(Object bean) { this.bean = bean; } public Object getBean() { return bean; } }BeanDefinition
测试代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class ApiTest { @Test public void test_BeanFactory(){ // 1.初始化 BeanFactory BeanFactory beanFactory = new BeanFactory(); // 2.注入bean BeanDefinition beanDefinition = new BeanDefinition(new Object()); beanFactory.registerBeanDefinition("test", beanDefinition); // 3.获取bean Object userService = beanFactory.getBean("test"); userService.toString(); } }View Code
参考文章:https://juejin.cn/post/6989013058035122207#heading-14标签:框架,BeanFactory,spring,Object,getBean,bean,手写,public,BeanDefinition From: https://www.cnblogs.com/xiaodeyao/p/17095386.html