从零开始开发IoC依赖注入框架 -- containerx (深入研究Spring源码)(含github源码)

版权声明:本文为刘少明原创文章,未经博主允许不得转载。 https://blog.csdn.net/lsm135/article/details/78308191

摘要: 自己写了一个开源的IoC控制反转(依赖注入)框架,名为containerx。初学Spring源码的同学,可以先研究下这个小项目。更容易理解Spring的源码

自己写了一个开源的IoC控制反转(依赖注入)框架,名为containerx。初学Spring源码的同学,可以先研究下这个小项目。更容易理解Spring的源码。 很多同学想学习Spring的源码,但是Spring的源码太庞大了。 看相应的书籍,并结合源码来研究。还是很难搞清楚原理(嵌套调用太多,而且架构相当复杂)。 我通过学习郝佳编著的书籍《Spring源码深度解析》,根据Spring的基本原理。写出了一个雏形的依赖注入框架,取名为containerx。 项目的源码地址为

https://github.com/flylib/containerx

开发者 Frank Liu(刘少明) 个人git https://github.com/flylib

邮箱[email protected] 

代码片段如下


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/flylib/containerx
如果觉得有用,欢迎star。

猜你喜欢

转载自blog.csdn.net/lsm135/article/details/78308191