Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[스프링AOP실무주의사항] 내부호출 - 구조변경 본문

인프런/[인프런] 스프링 핵심 원리 - 고급

[스프링AOP실무주의사항] 내부호출 - 구조변경

Seung__ 2022. 1. 11. 22:59

앞선 방법들은 자기 자신을 주입하거나 또는 Provider 를 사용해야 하는 것 처럼 조금 어색한 모습을 만들었다.

가장 나은 대안은 내부 호출이 발생하지 않도록 구조를 변경하는 것이다. 실제 이 방법을 가장 권장한다.

 

 

1. Internal 클래스 분리


/**
 * 구조를 변경(분리)
 */
@Slf4j
@Component
public class CallServiceV3 {

    private final InternalService internalService;

    public CallServiceV3(InternalService internalService) {
        this.internalService = internalService;
    }

    public void external(){
        log.info("call external");
        internalService.internal(); //내부메서드 호출
    }

}
@Slf4j
@Component
public class InternalService {

    public void internal(){
        log.info("call internal");
    }

}

내부 호출을 InternalService 라는 별도의 클래스로 분리했다.

 

 

 

2. Test


@Slf4j
@Import(CallLogAspect.class)
@SpringBootTest
class CallServiceV3Test {

    @Autowired CallServiceV3 callServiceV3;

    @Test
    void external() {
        callServiceV3.external();
    }

}
aop=void hello.aop.internalcall.CallServiceV3.external()
call external
aop=void hello.aop.internalcall.InternalService.internal()
call internal

내부 호출 자체가 사라지고, callService internalService 를 호출하는 구조로 변경되었다. 

덕분에 자연스럽게 AOP가 적용된다.

여기서 구조를 변경한다는 것은 이렇게 단순하게 분리하는 것 뿐만 아니라 다양한 방법들이 있을 수 있다.

예를 들어서 다음과 같이 클라이언트에서 둘다 호출하는 것이다.

  • 클라이언트 --> external()
  • 클라이언트 --> internal()

물론 이 경우 external() 에서 internal() 을 내부 호출하지 않도록 코드를 변경해야 한다. 

그리고 클라이언트 external() , internal() 을 모두 호출하도록 구조를 변경하면 된다. 

(물론 가능한 경우에 한해서)

 

 

 

3. 참고


  • AOP는 주로 트랜잭션 적용이나 주요 컴포넌트의 로그 출력 기능에 사용된다. 
  • 쉽게 이야기해서 인터페이스에 메서드가 나올 정도의 규모에 AOP를 적용하는 것이 적당하다. 
  • 더 풀어서 이야기하면 AOP는 public 메서드에만 적용한다. 
  • private 메서드처럼 작은 단위에는 AOP를 적용하지 않는다.
  • AOP 적용을 위해 private 메서드를 외부 클래스로 변경하고 public 으로 변경하는 일은 거의 없다.
  • 그러나 위 예제와 같이 public 메서드에서 public 메서드를 내부 호출하는 경우에는 문제가 발생한다.
  •  AOP가 잘 적용되지 않으면 내부 호출을 의심해보자.

 

4. GitHub: 220111 AOP & internal call & structure


 

GitHub - bsh6463/SpringAOP

Contribute to bsh6463/SpringAOP development by creating an account on GitHub.

github.com

 

Comments