의존성주입

joseon0thing·2023년 1월 13일
0

Spring

목록 보기
1/1
post-thumbnail

의존 관계 주입 (Dependency Injection)

어떤 객체가 사용하는 의존 객체를 직접 만들어 사용하는 게 아니라, 주입 받아 사용하는 방법

생성자 주입 (Constructor Injection)

@Controller
public class Test{
	
    @Autowired // 단일 생성자일 경우 생략 가능
    public TestService(TestService testService){
    	this.testService = testService;
    }
} 
Lombok을 사용할 경우

Lombok: Getter, Setter, ToString, hashCode 등 메소들을 간편하게 사용할 수 있게 해준다.

@Controller
@RequiredArgsConstructor //생성자 자동 생성
public class Test{

    private final testService;
} 

필드 주입 (Field Injection)

필드에 @Autowired

@Controller
public class Test{
	
    @Autowired
    TestService testService;
}

수정자 주입 (Setter Injection)

@Controller
public class Test{

	private testService;
	
    @Autowired
    public void TestService(TestService testService){
    	this.testService = testService;
    }
}
profile
정리.velog

0개의 댓글