自己動手實現spring創建bean

場景:對賬戶信息進行操作

步驟

  1. 首先,持久化層操作
public interface AccountDao {
    void saveAccount();
}

新增一個賬戶信息,持久化層操作實現類

public class AccountDaoImpl implements AccountDao {
    @Override
    public void saveAccount() {
        System.out.println("保存賬戶成功");
    }
}
  1. 業務層操作
public interface AccountService {
    void saveAccount();
}

業務層操作實現類

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

這裏,我們通過自己定義對BeanFactory來創建bean
3. 創建配置文件

accountService=com.lf.test.service.impl.AccountServiceImpl
accountDao=com.lf.test.dao.impl.AccountDaoImpl
  1. BeanFactory實現
/**
 *
 * 一個創建Bean對象的工廠
 *
 * JavaBean:使用java編寫的可重用組件
 *
 * 創建Service和Dao對象
 *
 * 第一步:需要配置文件來配置我們的service和dao
 *          * 配置內容:唯一標識 -> 全限定類名(key -> value)
 *
 * 第二步:讀取配置文件中配置的內容,反射創建對象
 *
 * 配置文件可以是xml也可以是properties
 *
 */
public class BeanFactory {
    // 定義一個properties
    private static Properties properties;
    // 定義一個map,存放要創建的對象,稱爲容器
    private static Map<String, Object> beans;
    // 使用靜態代碼塊爲Properties對象賦值
    static {
        try {
            // 實例化對象
            properties = new Properties();
            // 獲取properties文件的流對象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(in);
            beans = new HashMap<>();
            // 取出配置文件中所有的bean
            Enumeration keys = properties.keys();
            // 遍歷keys
            while (keys.hasMoreElements()) {
                String key = keys.nextElement().toString();
                String beanPath = properties.getProperty(key);
                Object value = Class.forName(beanPath).newInstance();
                beans.put(key, value);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失敗");
        }
    }
    // 根據bean的名稱,獲取值
    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }
}
  1. 測試
public class TestClient {
    public static void main(String[] args) {
        AccountService accountService = (AccountService) BeanFactory.getBean("accountService");
        accountService.saveAccount();
    }
}

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章