进入公司后一直做C# 开发,最近需要找工作了,现在把Java 重新捡回来,从spring 开始吧。
Spring的核心,主要是 BeanFactory,及配置文件beans.xml文件,下面是列出关键代码;
beans.xml:
<beans>
<bean id="u" class="com.spring01.dao.impl.UserDaoAccessImpl" />
<bean id="userService" class="com.spring01.service.UserService" >
<property name="userDao" bean="u"/>
</bean>
</beans>
BeanFactory工厂
BeanFactory:
public interface BeanFactory {
public Object getBean(String id);
}
ClassPathXmlApplicationContext实现BeanFactory
ClassPathXmlApplicationContext:
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String, Object> beans = new HashMap<String, Object>();
public ClassPathXmlApplicationContext() throws Exception {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(this.getClass().getClassLoader()
.getResourceAsStream("beans.xml")); // 构造文档对象
Element root = doc.getRootElement(); // 获取根元素HD
List list = root.getChildren("bean");// 取名字为disk的所有元素
for (int i = 0; i < list.size(); i++) {
Element element = (Element) list.get(i);
String id = element.getAttributeValue("id");
String clazz = element.getAttributeValue("class");
Object o = Class.forName(clazz).newInstance();
System.out.println(id);
System.out.println(clazz);
beans.put(id, o);
for (Element propertyElement : (List<Element>) element.getChildren("property")) {
String name = propertyElement.getAttributeValue("name"); // userDAO
String bean = propertyElement.getAttributeValue("bean"); // u
Object beanobj = beans.get(bean);
String methodName = "set" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method m= o.getClass().getMethod(methodName, beanobj.getClass().getInterfaces()[0]);
m.invoke(o, beanobj);
// Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
}
}
}
public Object getBean(String id) {
return beans.get(id);
}