摘要: 自己用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。
加群讨论