1.环境搭建
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
2.目录结构
3.模拟bean配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans>
<bean id="user" class="spring.ioc3.entity.Student">
<property name="name" value="xiaoming"/>
<property name="address" value="xiaoyingdajie"/>
</bean>
</beans>
4.Application文件
package spring.ioc3.context;
public interface Application {
public Object getBean(String beanId);
}
5.ClassPathApplication文件
package spring.ioc3.context;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ClassPathApplication implements Application {
Map beanAll = new HashMap();
public ClassPathApplication() {
try {
String filePath = this.getClass().getResource("/applicationContext1.xml").getPath();
filePath = new URLDecoder().decode(filePath, "UTF-8");
SAXReader reader = new SAXReader();
Document d = reader.read(new File(filePath));
List<Node> nodes = d.getRootElement().selectNodes("bean");
for (Node node : nodes) {
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 = node.selectNodes("property");
for (Node p : properties) {
Element e = (Element) p;
String name = e.attributeValue("name");
String value = e.attributeValue("value");
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method method = c.getMethod(methodName, String.class);
method.invoke(obj, value);
}
beanAll.put(id, obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Object getBean(String beanId) {
return beanAll.get(beanId);
}
}
6.XMLApplication文件
package spring.ioc3;
import spring.ioc3.context.Application;
import spring.ioc3.context.ClassPathApplication;
import spring.ioc3.entity.Student;
public class XMLApplication {
public static void main(String[] args) {
Application application = new ClassPathApplication();
Student stu = (Student) application.getBean("user");
System.out.println(stu.getAddress());
System.out.println(stu.getName());
}
}
实例化后输出: