自己手动实现一下spring的配置文件注入原理。具体步骤如下:
1、新建一个IUserService接口,里面定义一个添加用户的方法。源码如下:
public interface IUserService {
public void saveUser();
}
2、编写UserServiceImpl的实现类,具体如下:
public class UserServiceImpl implements IUserService {
@Override
public void saveUser() {
System.out.println("保存用户成功!");
}
}
3、编写spring.xml文件,具体如下:
<beans>
<bean id="userService" class="com.evan.service.impl.UserServiceImpl"></bean>
</beans>
4、编写spring的ApplicationContext接口类模拟,具体如下:
public interface ApplicationContext {
public Object getBean(String name);
}
5、编写ClassPathXmlApplicationContext实现类,在编写实现类之前,需要添加jdom.jar来解析xml文件。具体实现源码如下:
public class ClassPathXmlApplicationContext implements ApplicationContext {
Map<String, Object> map = new HashMap<String, Object>();
public ClassPathXmlApplicationContext(String path) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(this.getClass().getClassLoader()
.getResourceAsStream(path));
Element root = doc.getRootElement();
List listElement = root.getChildren("bean");
for (int i = 0; i < listElement.size(); i++) {
Element beanElement = (Element) listElement.get(i);
String id = beanElement.getAttributeValue("id");
String clazz = beanElement.getAttributeValue("class");
Object obj = Class.forName(clazz).newInstance();
map.put(id, obj);
}
}
@Override
public Object getBean(String name) {
return map.get(name);
}
}
6、编写UserAction代码,来注入UserServiceImpl对象,具体如下:
public class UserAction {
public static void main(String[] args) throws Exception {
String path = "spring.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(path);
IUserService userService = (IUserService) context
.getBean("userService");
userService.saveUser();
}
}
7、项目截图如下:
8、项目的完整源码下载地址(免积分):
http://download.csdn.net/download/zl544434558/8582821
原文地址:http://blog.csdn.net/zl544434558/article/details/44985583