Spring DI -2

이규훈·2022년 11월 11일
0

스프링 정리

목록 보기
17/30

객체 찾기

By Name - key로 찾기
By Type - Value로 찾기

이름으로 찾기
map.get(id)

타입으로 찾기
obj instanceof 이용

    Object getBean(String key) {//ByName
        return map.get(key);
    }
    Object getBean(Class clazz){//ByType
        for(Object obj :map.values()){
            if(clazz.isInstance(obj))
                return obj;
        }
        return null;
    }

객체 자동 연결 - @Autowired

class Car{
	Engine engine;
    Door door;
}

이 있다고 하면
그동안은
car.engine = engine;
car.door= door;
이렇게 저장을 하였는데

class Car{
	 @Autowired Engine engine;
     @Autowired Door door;
}

이러면 자동연결을 해준다. map에 저장되어있는 객체들에서 뒤져서 찾아서 알아서 저장해준다. 알아서 대입해준다.

@Resource

@Autowired은 타입을 찾아서 연결 (value)
@Resource은 이름을 찾아서 연결 (key)

class Car{
	 @Resource Engine engine;
     @Resource Door door;
}

이러면 key에서 engine, door를 찾아서 객체(빈)에 저장한다.

private void doAutowired(){
	//map에 저장된 객체의 iv중에 @AutoWired가 붙어 있으면
    //map에서 iv의 타입에 맞는 객체를 차장서 연결(객체의 주소를 iv에 저장한다)
	for(Object bean: map.values()){
    	for(Field fld : bean.getClass().getDeclaredFields()){
        	if(fld.getAnnotation(Autowired.class)!=null) //byType
            	fld.set(bean, getBean(fld.getType())); // car.engine = obj;
        }
    }
}
profile
개발취준생

0개의 댓글

관련 채용 정보