简易版Spring Ioc (转载)
2016-05-13 11:22
513 查看
package com.ioc.service; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * @author lei 2011-8-22 * * 简单实现了一下Spring的IOC,理解IOC原理,多使用面向接口编程 * */ public class BeanFactory { private Map<String, String> beanDefinitions; BeanFactory(String source) { this.register(source); } public void register(String source) { InputStream in = this.getClass().getResourceAsStream(source); Properties p = new Properties(); try { p.load(in); in.close(); beanDefinitions = new HashMap<String, String>(); for (Map.Entry<Object, Object> entry : p.entrySet()) { beanDefinitions.put(entry.getKey().toString(), entry.getValue().toString()); } } catch (IOException e) { e.printStackTrace(); } } public Object getBean(String name) { try { String value = beanDefinitions.get(name); return Class.forName(value).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { BeanFactory factory = new BeanFactory("hello.properties"); MessageWrite write = (MessageWrite) factory.getBean("messageWrite"); MessageSource source = (MessageSource) factory.getBean("messageSource"); write.write(source.getMessage()); } } interface MessageSource { public String getMessage(); } /** * message * @author lei * 2011-8-22 */ class SimpleMessageSource implements MessageSource { @Override public String getMessage() { return "hello world"; } } /** * 输出Service * @author lei * 2011-8-22 */ interface MessageWrite { public void write(String str); } class SimpleMessageWrite implements MessageWrite { public void write(String str) { System.out.println(str); } } /** * 附上hello.properties * /messageWrite=com.ioc.service.SimpleMessageWrite * /messageSource=com.ioc.service.SimpleMessageSource * */
相关文章推荐
- Spket在Eclipse下的安装和配置(图文教程)
- springMVC学习之url重写:urlrewrite with tuckey UrlRewriteFilter
- Java的数据类型
- Myeclipse 2015 stable 1.0 完美破解方法
- java实现二分查找
- java的五种数据类型解析
- java中的泛型
- Spring管理Filter和Servlet
- spring-test 加 mock
- java中使用jxl导入导出excel实例及其在spring mvc中的应用
- java实现选择排序
- JAVA多线程之多线程的实现
- Description Resource Path Location Type Java compiler level does not match the version of the instal
- java实现插入排序,增加减少循环的功能
- java发送邮件常见问题(附源代码)
- java实现冒泡排序,设立标志位,减少遍历趟数
- springmvc返回json中文乱码及使用jackson自动转换
- java中截取字符串第二个小数点之前的字符串
- spring 下载地址
- Java进阶读书清单及好书推荐