개발/Spring

[Spring] Autowired

지산동고라니 2021. 11. 3. 22:06

이전 XML로 Bean을 생성 했을 때에는 Bean을 생성한 후 construct-arg 나 setter로 클래스 내부에서 사용하는 객체를 등록해 주어야 했다. 

 

하지만 @Autowired 어노테이션을 이용한다면 이를 할 필요가 없다. 

@Component
public class TennisCoach implements Coach {

    private FortuneService fortuneService;

	//아래의 생성자에 하는 것도 가능하고 이렇게도 가능함 이 때는 Setter Autowired
    //@Autowired
    //private FortuneService fortuneService;

    @Autowired
    public TennisCoach(FortuneService fortuneService) {
        this.fortuneService = fortuneService;
    }
    

    @Override
    public String getDailyWorkout() {
        return "Practice Something";
    }

    @Override
    public String getDailyFortune() {
        return fortuneService.getFortune();
    }
}

이런식으로 해버리면 TennisCoach라는 빈이 등록된 이후 생성자에서 다시금 스프링의 능력이 발휘 되어 생성자를 적절하게 실행해 준다. 그러기 위해서는 Component 기반으로 스캔하여 작동하는 스프링을 위해 Component라는 어노테이션을 달아 주어야 한다.

 

@Component
public class HappyFortuneService implements FortuneService {

    @Override
    public String getFortune() {
        return "Lucky day!";
    }
}

 

이것 역시도 Spring IOC(Inversion of Control) DI (Dependeny Injection)이라고 하는 기능의 하나이다.

 

그렇다면 2개의 생성자를 만든 후 두 생성자 모두 Autowired를 달아주면 어떠할까? 물론 안된다. 이는 Autowired의 기본 값인 required = true를 false로 값을 주면 true의 생성자만 사용되어 빈을 생성한다. 

 

@Annotaion(required=false)를 주어 하나의 생성자를 무시하도록 할 수 있다.

 

As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with. However, if several constructors are available, at least one must be annotated to teach the container which one to use.

보면 알겠지만 4.3버젼 이후 생성자가 하나인 경우 하나의 생성자에 @Autowired를 달아준다는 이야기. 만약 위와 같은 경우의 코드라면 @Autowired를 달아주지 않아도 된다. 하지만! 다른 사람들과 함께 한다면, 달아주는 것이 맞다