You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
1. 예제 만들기
지금까지 학습한 내용을 활용해서 유용한 스프링 AOP를 만들어보자.
@Trace애노테이션으로 로그 출력하기@Retry애노테이션으로 예외 발생시 재시도 하기먼저 AOP를 적용할 예제를 만들자.
ExamRepository
5번에 1번 정도 실패하는 저장소이다. 이렇게 간헐적으로 실패할 경우 재시도 하는 AOP가 있으면 편리하다.
ExamService
ExamTest
실행해보면 테스트가 5번째 루프를 실행할 때 리포지토리 위치에서 예외가 발생하면서 실패하는 것을 확인할 수 있다.
2. 로그 출력 AOP
먼저 로그 출력용 AOP를 만들어보자.
@Trace가 메서드에 붙어 있으면 호출 정보가 출력되는 편리한 기능이다.@trace
TraceAspect
@annotation(hello.aop.exam.annotation.Trace)
포인트컷을 사용해서@Trace` 가 붙은 메서드에 어드바이스를 적용한다.ExamService - @trace 추가
request()에@Trace를 붙였다. 이제 메서드 호출 정보를 AOP를 사용해서 로그로 남길 수 있다.ExamRepository - @trace 추가
save()에@Trace를 붙였다.ExamTest - 추가
@Import(TraceAspect.class)를 사용해서TraceAspect를 스프링 빈으로 추가하자. 이제 애스펙트가 적용된다.실행 결과
실행해보면
@Trace가 붙은request(),save()호출시 로그가 잘 남는 것을 확인할 수 있다.3. 재시도 AOP
이번에는 좀 더 의미있는 재시도 AOP를 만들어보자.
@Retry애노테이션이 있으면 예외가 발생했을 때 다시 시도해서 문제를 복구한다.@Retry
이 애노테이션에는 재시도 횟수로 사용할 값이 있다. 기본값으로
3을 사용한다.RetryAspect
@annotation(retry),Retry retry를 사용해서 어드바이스에 애노테이션을 파라미터로 전달한다.retry.value()를 통해서 애노테이션에 지정한 값을 가져올 수 있다.retry.value()만큼 재시도한다.ExamRepository - @Retry 추가
ExamRepository.save()메서드에@Retry(value = 4)를 적용했다. 이 메서드에서 문제가 발생하면 4번 재시도 한다.ExamTest - 추가
@Import(TraceAspect.class)는 주석처리하고@Import({TraceAspect.class, RetryAspect.class})를 스프링 빈으로 추가하자.실행 결과
실행 결과를 보면 5번째 문제가 발생했을 때 재시도 덕분에 문제가 복구되고, 정상 응답되는 것을 확인할 수 있다.
참고
스프링이 제공하는
@Transactional은 가장 대표적인 AOP이다.Beta Was this translation helpful? Give feedback.
All reactions