重回Java开发-利用反射模拟Spring

进入公司后一直做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);
	}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值