spring recipes读书笔记--理解IOC原理
假设将开发一个系统,功能之一是生产HTML或PDF格式的报表。
首先创建生产报表的通用接口,然后分别生产HTML格式和PDF格式报表
public class Container{ private Map<String,Object> components; public Container(){ components = new HashMap<String,Object>(); try{ Properties props=new Properties(); props.load(new FileInputStream("components.properties")); for(Map.Entry entry : props.entrySet()){ String key = (String)entry.getKey(); String value=(String)entry.getValue(); processEntry(key,value); } }catch(Exception e){ throws new RuntimeException(e); } } private void processEntry(String key,String value) throws Exception{ String[] parts=key.split("\\."); if(parts.length == 1){ [color=red]//新建组件[/color] Object component = Class.forName(value).newInstace(); components.put(parts[0],component); }else{ [color=red]//依赖注入[/color] Object component = components.get(parts[0]); Object reference = components.get(value); PropertyUtils.setProperty(component,parts[1],reference); } } public Object getComponent(String id){ return components.get(id); }}