在resources下創建bean.properties
accountService=cn.flypig666.service.impl.AccountServiceImpl
accountDao=cn.flypig666.dao.impl.AccountDaoImpl
創建工廠:BeanFactory.java
創建單例對象效果更好
創建Map<String,Object>類型的容器beans
1 //定義一個Properties對象 2 private static Properties props; 3 4 //定義一個Map,用於存放我們要創建的對象,稱之為容器 5 private static Map<String,Object> beans; 6 7 //使用靜態代碼塊為Properties對象賦值 8 static { 9 try { 10 //實例化對象 11 props = new Properties(); 12 //獲取properties文件的流對象,創建在resources文件夾下的properties文件會成為類根路徑下的文件,不用寫包名 13 InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); 14 props.load(in); 15 //實例化容器 16 beans = new HashMap<String, Object>(); 17 //取出配置文件中所有的 Key 18 Enumeration keys = props.keys(); 19 //遍歷枚舉 20 while (keys.hasMoreElements()){ 21 //取出每個key 22 String key = keys.nextElement().toString(); 23 //根據key獲取value 24 String beanPath = props.getProperty(key); 25 //反射創建對象 26 Object value = Class.forName(beanPath).newInstance(); 27 //把key和value存入容器中 28 beans.put(key,value); 29 } 30 } catch (Exception e) { 31 throw new ExceptionInInitializerError("初始化properties失敗"); 32 } 33 } 34 35 public static Object getBean(String beanName){ 36 return beans.get(beanName); 37 }
1 /** 2 * 根據Bean的名稱獲取bean對象 3 * @param beanName 4 * @return 5 */ 6 public static Object getBean(String beanName){ 7 Object bean = null; 8 try{ 9 String beanPath = props.getProperty(beanName); 10 System.out.println(beanPath); 11 bean = Class.forName(beanPath).newInstance(); 12 }catch (Exception e){ 13 e.printStackTrace(); 14 } 15 return bean; 16 } 17 18 }
通過反射獲取對象
/** * 賬戶業務層實現類 */ public class AccountServiceImpl implements IAccountService { //private IAccountDao accountDao = new AccountDaoImpl(); private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao"); public void saveAccount(){ accountDao.saveAccount(); } }
/** * 模擬一個表現層,用於調用業務層 */ public class Client { public static void main(String[] args) { // IAccountService accountService = new AccountServiceImpl(); IAccountService accountService = (IAccountService) BeanFactory.getBean("accountService"); accountService.saveAccount(); } }