Q1.
(08-08 DepartmentServiceTest 참고)
private DepartmentService departmentService; 이걸 걸었는데, import 해오는 구문이 없는데, 뭐지?
A1.
private DepartmentService departmentService; 선언은 DepartmentService 클래스를 사용하기 위한 필드 선언입니다. 하지만 해당 클래스가 import되지 않았다면, 컴파일 오류가 발생할 수 있습니다. DepartmentService 클래스를 import해야 합니다.
다음과 같이 import 구문을 추가해 보세요:
import com.stevek.database.services.DepartmentService; // 실제 패키지 경로로 수정하세요
public class DepartmentServiceTest {
private DepartmentService departmentService;
// 테스트 메서드들...
}
DepartmentService 클래스가 실제로 존재하는 패키지 경로를 정확히 지정해야 합니다. 만약 DepartmentService 클래스가 다른 패키지에 있다면, 해당 패키지 경로를 사용하여 import 구문을 추가해야 합니다.
또한, DepartmentService가 Spring 빈으로 관리되는 서비스라면, @Autowired 어노테이션을 사용하여 주입할 수 있습니다:
import org.springframework.beans.factory.annotation.Autowired;
import com.stevek.database.services.DepartmentService; // 실제 패키지 경로로 수정하세요
public class DepartmentServiceTest {
@Autowired
private DepartmentService departmentService;
// 테스트 메서드들...
}
이렇게 하면 Spring이 DepartmentService 빈을 자동으로 주입해 줍니다.
Q2.
DepartmentService 인터페이스를 상속받은 구현체 DepartmentServiceImpl 에 @Service 어노테이션이 붙어있어. 그러면 Autowired 어노테이션을 DepartmentService에 걸어도, 자동으로 구현체가 주입되는거야?
A2.
네, 맞습니다. Spring에서는 인터페이스 타입의 빈을 주입할 때, 해당 인터페이스를 구현한 클래스에 @Service, @Component, @Repository 등의 어노테이션이 붙어 있으면, 해당 구현체가 자동으로 주입됩니다.
즉, DepartmentService 인터페이스를 상속받은 DepartmentServiceImpl 클래스에 @Service 어노테이션이 붙어 있다면, @Autowired 어노테이션을 사용하여 DepartmentService 타입의 빈을 주입할 때 DepartmentServiceImpl 구현체가 자동으로 주입됩니다.
예를 들어, 다음과 같이 DepartmentService 인터페이스와 DepartmentServiceImpl 구현체가 있다고 가정해봅시다:
// DepartmentService.java
package com.stevek.database.services;
public interface DepartmentService {
// 인터페이스 메서드들...
}
// DepartmentServiceImpl.java
package com.stevek.database.services.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DepartmentServiceImpl implements DepartmentService {
// 구현체 메서드들...
}
이제 다른 클래스에서 DepartmentService를 주입받고자 할 때, 다음과 같이 @Autowired 어노테이션을 사용할 수 있습니다:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SomeComponent {
@Autowired
private DepartmentService departmentService;
// 메서드들...
}
이 경우, Spring은 DepartmentService 인터페이스를 구현한 DepartmentServiceImpl 클래스를 자동으로 주입합니다. 따라서 DepartmentService 타입의 빈을 주입받을 때, DepartmentServiceImpl 구현체가 주입됩니다.
'언어 및 도구들 공부 > Spring' 카테고리의 다른 글
| throw e? (0) | 2024.10.22 |
|---|---|
| 테이블 이름은 단수? 복수? (0) | 2024.10.22 |
| Mapper 에서 Property, column (0) | 2024.10.21 |
| 컨트롤러의 메서드가 리턴하는 주소의 작성방법 중 "/주소" vs "주소" (0) | 2024.10.20 |
| @Value 어노테이션 (0) | 2024.10.19 |