spring Ioc的原理
spring Ioc的原理
要了解Ioc,首先要了解的概念
控制反转(Inversion of Control ,Ioc)
应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护由外部容器来负责。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。
依赖注入(Dependency Injection)
在运行期间,有外部容器动态地将依赖对象注入到组件中(构造方法和set方法)
bean中包含了什么
一个Bean包括id,type,和Properties。
基本配置如下:
<bean id="test" class="Test"> <property name="testMap"> <map> <entry key="a"> <value>1</value> </entry> <entry key="b"> <value>2</value> </entry> </map> </property> </bean>
Ioc的核心就是Java的反射机制
首先通过反射实例化一个类
public static Object newInstance(String className) { Class<?> cls = null; Object obj = null; try { cls = Class.forName(className); obj = cls.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } return obj; }
将依赖注入进去
public static void setProperty(Object obj, String name, String value) { Class<? extends Object> clazz = obj.getClass(); try { String methodName = returnSetMthodName(name); Method[] ms = clazz.getMethods(); for (Method m : ms) { if (m.getName().equals(methodName)) { if (m.getParameterTypes().length == 1) { Class<?> clazzParameterType = m.getParameterTypes()[0]; setFieldValue(clazzParameterType.getName(), value, m, obj); break; } } } } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }
反射机制的核心代码
Class<?> cls = Class.forName(className);
Object obj = cls.newInstance();
相关推荐
itjavashuai 2020-07-28
smalllove 2020-07-27
willluckysmile 2020-06-29
TiDBPingCAP 2020-06-21
丽丽 2020-06-11
shenxiuwen 2020-06-10
willluckysmile 2020-06-10
MrFuWen 2020-06-09
yuanye0 2020-06-08
whbing 2020-05-19
yuanye0 2020-05-14
kong000dao0 2020-05-10
方志朋 2020-05-08
somyjun 2020-05-01
suixinsuoyu 2020-04-29
咻pur慢 2020-04-22
tianxiaolu 2020-04-06
吾日五省我身 2020-03-28