IOC:Inversion of Control,控制反转。指的是对象的创建权反转(交给)给Spring,其作用是实现了程序的解耦合。也可这样解释:获取对象的方式变了。对象创建的控制权不是“使用者”,而是“框架”或者“容器”。
用更通俗的话来说,IOC就是指对象的创建,并不是在代码中用new操作new出来的,而是通过Spring进行配置创建的。其底层实现原理是XML配置文件+SAX解析+工厂设计模式。
public class ApplicationContextImpl implements ApplicationContext {
private Map<String,Object> map = new HashMap<>();
public ApplicationContextImpl() {
try {
String path = "F:\\SSMworkspace\\myioc\\src\\ApplicationContext.xml";
SAXReader reader = new SAXReader();
Document document = reader.read(new File(path));
Element element = document.getRootElement();
System.out.println(element);
List<Node> nodes = element.selectNodes("bean");
if(nodes != null && nodes.size()>0) {
for (Node node : nodes) {
System.out.println(node);
Element ele = (Element) node;
String id = ele.attributeValue("id");
String clazz = ele.attributeValue("class");
System.out.println(id);
System.out.println(clazz);
Class<?> User = Class.forName(clazz);
Object bean = User.newInstance();
System.out.println(bean);
List<Node> prolist = ele.selectNodes("property");
if(prolist != null && prolist.size()>0) {
for (Node n : prolist) {
Element e = (Element) n;
Attribute name = e.attribute("name");
Attribute value = e.attribute("value");
System.out.println(name.getStringValue());
System.out.println(value);
String setMethod = "set"+Character.toUpperCase(name.getStringValue().charAt(0))+name.getStringValue().substring(1);
Class<?> type = User.getDeclaredField(name.getStringValue()).getType();
Method method = User.getDeclaredMethod(setMethod, type);
Object propValue = null;
if(type == String.class) {
propValue = String.valueOf(value.getStringValue());
}else if(type == Integer.class|| type == int.class) {
propValue = Integer.valueOf(value.getStringValue());
}
method.invoke(bean, propValue);
}
}
map.put(id, bean);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Object getBean(String id) {
return map.get(id);
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="haha" class="com.bw.bean.User">
<property name="name" value="lisi"></property>
<property name="age" value="18"></property>
</bean>
</beans>