Javaweb 獲取properties檔案的內容,模擬spring如何建立實列
阿新 • • 發佈:2020-07-24
/** * 模擬spring容器如何建立例項 * (1) 提供一個config.properties配置檔案,在這個檔案中配置介面和實現類對應關係 * EmpService=com.tedu.EmpServiceImpl * (2) 在當前類中讀取 config.properties檔案中的配置資訊,將檔案中的所有配置讀取到 * Properties物件中 * (3) 提供一個getBean方法,接收介面名(例如:EmpService),根據介面名到Properties * 物件中獲取該介面對應的實現類的全限定類名(com.tedu.EmpServiceImpl), * 在基於反射建立該類的例項,作為方法的返回值直接返回即可! * */ public class BeanFactory { //用於載入config.properties檔案中的所有內容 private static Properties prop; static { try { //初始化prop prop = new Properties(); //獲取指向config.properties檔案的流物件 ClassLoader loader = BeanFactory.class.getClassLoader();//獲取一個類載入器 InputStream in = loader.getResourceAsStream("config.properties"); //將config.properties檔案中的所有內容載入prop物件中 prop.load( in ); } catch (Exception e) { e.printStackTrace(); } } /** * 根據介面名,到config.properties檔案中獲取該介面對應子類的全限定類名 * 再基於反射建立該子類的例項 * @param interName 介面名(也是config.properties檔案中的key) * @return Object 根據傳入的介面名,返回該介面對應的子類例項 */ public static Object getBean(String interName) { try { //根據介面名,到config.properties檔案中獲取該介面對應子類的全限定類名 String className = prop.getProperty( interName ); //通過子類的全限定類名獲取該類的位元組碼物件 Class clz = Class.forName(className); //在通過該類的位元組碼物件,獲取該類的例項 Object obj = clz.newInstance(); return obj; } catch (Exception e) { e.printStackTrace(); } return null; } }