의존성 주입

정하윤·2023년 1월 29일
0

의존성 주입에는 3가지가 있다.

생성자 주입; Constructor Injection
필드 주입; Field Injection
수정자 주입; Setter Injection

예시로는

생성자 주입

@Controller
public class CocoController {
  //final을 붙일 수 있음
    private final CocoService cocoService;
  //---------------------------------------------------------
  //@Autowired 
    public CocoController(CocoService cocoService) {
        this.cocoService = cocoService;
    }
}

필드주입

@Controller
public class CocoController {
	
    @Autowired 
    private CocoService cocoService;
}

수정자 주입

@Controller
public class CocoController {
    private CocoService cocoService;
    
    @Autowired
    public void setCocoService(CocoService cocoService) {
    	this.cocoService = cocoService;
    }
}

이러한 식으로 작성을 한다. 밑에는 오늘 강의를 들으면서 나온 오류이다.

오류

The bean 'memberService', defined in class path resource [hello/hellospring/service/SpringConfig.class], could not be registered. A bean with that name has already been defined in file [/Users/jeonghayun/Desktop/spring/hello-spring/out/production/classes/hello/hellospring/service/MemberService.class] and overriding is disabled.

해결방안

오류를 읽어보고 느낀점은 생성자 주입과 필드 주입을 동시에 사용하고 있어서 뜬것 같아서 생성자 주입을 지우고 실행하니 오류가 없어졌다. 당연한것일수도 있지만 의존성 주입의 종류들중 2개를 동시에는 적용될수 없다는것을 알게되었다.

0개의 댓글