首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

spring recipes读书笔记-懂得IOC原理

2012-11-07 
spring recipes读书笔记--理解IOC原理假设将开发一个系统,功能之一是生产HTML或PDF格式的报表。首先创建生

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);    }}

现在容器可以从基于文本的配置文件中读取组件定义了,当组件定义改变,如需要HtmlReportGenerator时,不用修改一行java代码。

热点排行