본문 바로가기
Develop/Spring

[Spring] @Autowired @Resource @Qualifire 차이

by dev_m.w 2024. 8. 29.

 

@Autowired 라는 어노테이션을 붙이면, 스프링 컨테이너 에서 타입으로 빈을 검색해서 참조 변수에 자동 주입해준다.

검색된 빈이 n 개이면, 그중에 참조 변수와 이름이 일치하는 것을 주입한다

 

@Component class Door {}


 class Engine {
}
@Component class TurboEngine extends Engine {}
@Component class SuperEngine extends Engine {}


@Component class Car {
   String color;
   int oil;
   Engine engine;
   Door[] doors;
   


   @Autowired
    public Car(@Value("red") String color, @Value("100") int oil, Engine engine, Door[] doors) {
        this.color = color;
        this.oil = oil;
        this.engine = engine;
        this.doors = doors;
    }

 

하지만 부모인 Engine 클래스를 빈으로 등록하지않고 현재 빈에는 engine 타입 자손인 superEngine, TurboEngine  있는경우라면? 

 

 

 

바로 에러가난다. 그이유는 타입으로 검색된 빈이 n 개여서 , 참조변수와 일치하는 것을 주입 하려했으나 그것도 없기떄문에, 둘중에 어떤 타입을 주입해줘야 할지 모르기떄문에 에러가 났다.

 

 

 

이러한 경우는 어떻게 해야될까?

@Qualifer어노테이션을 붙여주고 사용할 빈의 이름을 적어주면된다. 아니면 @Autowired 말고 @Resource 써주면된다.  @Resource는 빈을 이름으로 찾아 주입시켜준다. 

@Autowired
 public Car(@Value("red") String color, @Value("100") int oil, @Qualifier("superEngine") Engine engine, Door[] doors) {
     this.color = color;
     this.oil = oil;
     this.engine = engine;
     this.doors = doors;
 }