인터페이스를 구현하는 여러 service 구현체가 있을 때, controller에서 pathvariable을 통해 구현체를 주입할 수 있다.
먼저 인터페이스를 하나 만들고, A와 B 두개의 구현체를 만들었다.
public interface TestInterface {
void save();
Type getType();
}
@Service
public class TestAImpl implements TestInterface {
Type type;
public Type getType() {
return Type.A;
}
@Override
public void save() {
System.out.println("save A");
}
}
@Service
public class TestBImpl implements TestInterface {
Type type;
public Type getType() {
return Type.B;
}
@Override
public void save() {
System.out.println("save B");
}
}
public enum Type {
A, B
그리고 controller에 pathvariable로 type을 받고, type을 getType 메서드를 이용해서 해당하는 구현체를 가져온다.
@RestController
@RequiredArgsConstructor
public class TestController {
private final List<TestInterface> testInterfaces;
@GetMapping("/api/test/{type}")
public void test(@PathVariable Type type) {
TestInterface testInterface = findTestInterface(type);
testInterface.save();
}
private TestInterface findTestInterface(Type type) {
return this.testInterfaces.stream()
.filter(testInterface -> type.equals(testInterface.getType()))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 타입입니다."));
}
}
그러면 해당하는 구현체의 save메서드가 실행된다.
http://localhost:8080/api/test/B 으로 get 요청을 하면 TestBImpl 서비스의 save가 실행되어
console에 "save B"가 나타나는 것을 확인할 수 있었다.
'Language > JAVA' 카테고리의 다른 글
[프로그래머스] 예산 (0) | 2022.07.15 |
---|---|
[프로그래머스] K번째수 #Arrays.copyOfRange (0) | 2022.07.01 |
[Java with Unit Test] equals와 hashCode (0) | 2022.06.16 |
[프로그래머스] 신규 아이디 추천 (0) | 2022.01.29 |
[프로그래머스] 시저 암호 (0) | 2022.01.27 |