spring第一節,初識IOC(二)


layout: post
author: zjhChester
header-img: img/post-bg-universe.jpg
catalog: true
tags:
- 工廠模式


Ioc /DI即用於減少程序之間的耦合性

1、JavaBean(用java編寫的可重用組件)》實體類:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-pJkjjz90-1580545902003)(/mdImg/工廠模式.assets/1569224481667.png)]

第一步:編寫配置文件bean.properties

需要一個配置文件來配置我們的service 和 dao

注意路徑必須是全限定類名(包名+類名)

Dao=dao.impl.DaoImpl
Service=service.ServiceImpl

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Ac3irVWM-1580545902005)(/mdImg/工廠模式.assets/1569232538446.png)]

第二步:編寫BeanFactory類

通過讀取配置文件中配置(properties/xml文件)的內容,反射創建對象

package factory;

import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {
    private static Properties properties;

    /**
     * 通過靜態方法在類被加載的時候就加載配置文件
     * 注意事項:通過BeanFactory的類加載器加載配置文件流(找到bean.properties)
     */
    static {
        try{
//            實例化文件
            properties = new Properties();
            /*獲取properties流對象    通過BeanFactory的類加載器加載配置文件流*/
            InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(is);
        }catch (Exception e){
            throw  new ExceptionInInitializerError("初始化失敗BeanFactory");
        }
    }
    /**
     * 生成Bean的靜態方法
     * @param beanName 從配置文件讀取的鍵--》從而獲取需要實例化的類的全限定類名
     * @return  返回實例化之後的Bean
     *
     */
   public static Object getBean(String beanName){
        Object bean = null;
        try{
            String beanPath = properties.getProperty(beanName);
            bean = Class.forName(beanPath).newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }
        return bean;
    }
}

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-m8YK4ARD-1580545902005)(/mdImg/工廠模式.assets/1569232499248.png)]

第三步:編寫測試類

/*通過BeanFactory內部反射實例化類,實現低耦合的編程思路**/
Service service = (Service) BeanFactory.getBean("Service");

測試結果:成功實例化

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-YcwaL120-1580545902005)(/mdImg/工廠模式.assets/1569234247778.png)]

發佈了12 篇原創文章 · 獲贊 13 · 訪問量 3511
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章