IoC 极简实现案例
1.引入依赖
<dependencies>
<dependency>
<!--Dom4j是java的XML解析组件-->
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<!--jaxen是Xpath表达式的解释器-->
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
2.ApplicationContext 接口
public interface ApplicationContext {
public Object getBean(String beanId);
}
3.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="sweetApple" class="com.mkyuan.ioc.entity.Apple">
<property name="title" value="红富士"></property>
<property name="color" value="红色"></property>
<property name="origin" value="欧洲"></property>
</bean>
</beans>
4.ClassPathXmlApplicationContext 类
public class ClassPathXmlApplicationContext implements ApplicationContext {
private Map iocContainer = new HashMap();
public ClassPathXmlApplicationContext() {
try {
String filePath = this.getClass().getResource("/applicationContext.xml").getPath();
filePath = URLDecoder.decode(filePath, "UTF-8");
SAXReader reader = new SAXReader();
Document document = reader.read(filePath);
List<Node> beans = document.getRootElement().selectNodes("bean");
for (Node node : beans) {
Element ele = (Element) node;
String id = ele.attributeValue("id");
String className = ele.attributeValue("class");
Class c = Class.forName(className);
Object obj = c.newInstance();
List<Node> properties = ele.selectNodes("property");
for (Node property : properties) {
Element elementProperty = (Element) property;
String propName = elementProperty.attributeValue("name");
String propValue = elementProperty.attributeValue("value");
String setMethodName = "set"+ propName.substring(0,1).toUpperCase()+propName.substring(1);
System.out.println("准备执行"+setMethodName+"方法注入数据");
Method setMethod = c.getMethod(setMethodName, String.class);
setMethod.invoke(obj,propValue);//通过setter方法注入数据
}
iocContainer.put(id,obj);
}
System.out.println(iocContainer);
System.out.println("Ioc 初始化完毕");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Object getBean(String beanId) {
return iocContainer.get(beanId);
}
}
5.Apple 类
package com.mkyuan.ioc.entity;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Apple {
private String title;
private String color;
private String origin;
}
6.Application 类
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext();
Apple sweetApple = (Apple) context.getBean("sweetApple");
System.out.println(sweetApple);
}
}
7.执行结果