Spring DI 흉내내기-(2)

개발세발·2024년 2월 13일
package com.fastcampus.ch3.diCopy2.diCopy1;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

class Car{ }
class sportCar extends Car{}
class Truck extends Car{}
class Engine{}

class AppContext{
    Map map;

    AppContext() {
        try {
            Properties p = new Properties();
            p.load(new FileReader("config.txt"));
            map = new HashMap(p);
            //반복문으로 클래스 이름을 얻어서 맵에 저장
            for(Object key: map.keySet()){
                Class clazz = Class.forName((String) map.get(key));
                map.put(key, clazz.newInstance());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    Object getBean(String key){
        return map.get(key);

    }

}

public class main2 {
    public static void main(String[] args) throws Exception {
        AppContext ac = new AppContext();
        Car car = (Car)ac.getBean( "car");
        Engine engine = (Engine)ac.getBean("engine");
        System.out.println("car = " + car);
        System.out.println("engine = " + engine);
    }


}

내용

  • "comfig.txt"에 있는 내용을 받아와서 새로운 객체를 생성하여 Map에 key(객체명):value(메모리 주소)의 형태로 저장
  • 이후 getBean 메소드를 이용하여 원하는 key의 value를 얻어옴.

0개의 댓글