Language/JAVA

[디자인패턴]controller pathvariable로 service 구현체 주입하기

paran21 2022. 6. 16. 00:40

인터페이스를 구현하는 여러 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"가 나타나는 것을 확인할 수 있었다.

 

 

깃허브 코드: https://github.com/paran22/interface_impl_prac