自己用Java实现一个依赖注入框架 (学习Spring源码并写一个简单的Spring框架)- containerx(含github源码)

摘要: 自己用Java实现一个依赖注入框架

自己写一个Spring框架?博主,你在开玩笑吗?NO! 通过研究了Spring源码的核心思想,自己用写一个小框架,加载类似的beans.xml配置,并且把bean都以单例方式注册到容器中,并且用InvocationHandler来实现AOP这个,就是核心思想,而且具备可行性。只不过没有Spring源码那样处理其它的细枝末节。

容器的本质是什么?--ConcurrentHashMap!

key是bean的name, value就是那个单例bean。有没有感觉豁然开朗?这样可以实现带依赖注入功能的容器。

InvocationHandler,还有Proxy.newProxyInstance()...  灵光一闪,是不是有实现AOP的思路了?

 

 我通过学习郝佳编著的书籍《Spring源码深度解析》,根据Spring的基本原理。写出了一个雏形的依赖注入框架,取名为containerx。 项目的源码地址为https://github.com/liushaoming/containerx

 

代码片段如下


public static void inject(Object bean, Map<String, String> properties) {
		Map<String, String> methodMap = new HashMap<String, String>();
		for (Map.Entry<String, String> entry : properties.entrySet()) {
			String configName = entry.getKey();
			String configValue = entry.getValue();
			String configMethodName = "";
			if (configName != null && configName.length() > 0) {
				configMethodName = "set" + String.valueOf(configName.charAt(0)).toUpperCase() + configName.substring(1);
			}
			methodMap.put(configMethodName, configValue);
		}
		
		Class clazz = bean.getClass();
		for (Method method : clazz.getMethods()) {
			String methodName = method.getName();
			if (methodName.startsWith("set") && method.getParameterTypes().length == 1
					&& Modifier.isPublic(method.getModifiers())
					&& methodMap.containsKey(methodName)) {
				try {
					method.invoke(bean, methodMap.get(methodName));
				} catch (Exception e) {
					e.printStackTrace();
				} 
			}
		}
	}

 项目的源码地址为https://github.com/liushaoming/containerx
如果觉得有用,欢迎star。

加群讨论

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值