beanDao接口和實現類git
public interface BeanDao { // 模擬add方法 void add(); } public class BeanDaoImpl implements BeanDao { @Override public void add() { System.out.println("添加bean信息"); } }
beanService接口和實現類github
public interface BeanService { void add(); } public class BeanServiceImpl implements BeanService { BeanDao dao = new BeanDaoImpl(); @Override public void add() { dao.add(); } }
測試類及運行結果spring
public class Demo { @Test public void demo01() { BeanService service = new BeanServiceImpl(); service.add(); } }
從代碼結構中能夠看出: beanService中沒有beanDao的耦合度很高, 若是沒有BeanDao的實現類, 編譯時就會報錯ide
工廠類代碼:測試
public class BeanFactory { public static Object getInstance(String className) { try { Class<?> clazz = Class.forName(className); Object obj = clazz.newInstance(); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } }
有了工廠類代碼之後咱們就能夠改造一下beanServiceImpl線程
public class BeanServiceImpl implements BeanService { BeanDao dao = (BeanDao) BeanFactory.getInstance("cn.ann.dao.impl.BeanDaoImpl"); @Override public void add() { dao.add(); } }
運行結果仍是同樣的code
配置文件bean.properties對象
beanDao=cn.ann.dao.impl.BeanDaoImpl
beanFactoryblog
public class BeanFactory { private static Map<String, String> props = new HashMap<>(); static { try (InputStream is = BeanFactory.class.getClassLoader(). getResourceAsStream("bean.properties")) { Properties prop = new Properties(); prop.load(is); Set<String> keys = prop.stringPropertyNames(); keys.forEach((key) -> props.put(key, prop.getProperty(key))); } catch (IOException e) { e.printStackTrace(); } } public static Object getInstance(String key) { if (props.containsKey(key)) { try { Class<?> clazz = Class.forName(props.get(key)); Object obj = clazz.newInstance(); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } else { throw new RuntimeException("配置文件中不存在該key"); } } }
BeanDao dao = (BeanDao) BeanFactory.getInstance("beanDao");
BeanFactory接口
public class BeanFactory { private static Map<String, Object> instances = new HashMap<>(); static { try (InputStream is = BeanFactory.class.getClassLoader(). getResourceAsStream("bean.properties")) { Properties prop = new Properties(); prop.load(is); Set<String> keys = prop.stringPropertyNames(); keys.forEach((key) -> { try { instances.put(key, Class.forName(prop.getProperty(key)).newInstance()); } catch (Exception e) { e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } } public static Object getInstance(String key) { if (instances.containsKey(key)) { return instances.get(key); } else { throw new RuntimeException("配置文件中不存在該key"); } } }
本篇到此結束, 這篇文章的重點是關於耦合這方面的, 因此並無考慮關於線程的問題
本篇代碼下載連接: 點擊此處 的 spring01-introduce