轉載自:http://www.oschina.net/code/snippet_107039_5892java
簡易版Spring Ioc編程
- 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 {
- 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
- *
- */