首页 > 技术文章 > 简易版Spring Ioc (转载)

hephec 2016-05-13 11:22 原文

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
 * 
 */

  

推荐阅读