简易版Spring Ioc (转载)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | 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 * */ |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步