728x90
Repository(5번에 한 번씩 예외가 발생)
@Repository
public class ExamRepository {
private static int seq = 0;
/**
* 5번에 1번 실패하는 요청
*/
public String save(String itemId){
seq++;
if(seq % 5 == 0){ //5번 한번 오류
throw new IllegalStateException("예외 발생");
}
return "ok";
}
}
Service
@Service
@RequiredArgsConstructor
public class ExamService {
private final ExamRepository examRepository;
public void request(String itemId){
examRepository.save(itemId);
}
}
Test
@Slf4j
@SpringBootTest
class ExamTest {
@Autowired
ExamService examService;
@Test
public void test(){
for (int i = 0; i < 5; i++) {
log.info("client request i = {}", i);
examService.request("data" + i);
}
}
}
로그 출력 AOP
Annotation 작성
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Trace {
}
TraceAspect 작성
@Slf4j
@Aspect
public class TraceAspect {
@Before("@annotation(hello.aop.exam.annotation.Trace)")
public void doTrace(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
log.info("[trace] {} args={}", joinPoint.getSignature(), args);
}
}
- @annotation(hello.aop.exam.annotation.Trace) 포인트컷을 사용해서 @Trace 가 붙은 메서드에 어드바이스를 적용한다
Annotation 추가
@Trace
public String save(String itemId){
seq++;
if(seq % 5 == 0){ //5번 한번 오류
throw new IllegalStateException("예외 발생");
}
return "ok";
}
@Trace
public void request(String itemId){
examRepository.save(itemId);
}
실행시 Aspect를 빈으로 등록하고 사용
@Slf4j
@Import(TraceAspect.class)
@SpringBootTest
class ExamTest {
@Autowired
ExamService examService;
@Test
public void test(){
for (int i = 0; i < 5; i++) {
log.info("client request i = {}", i);
examService.request("data" + i);
}
}
}728x90
'스프링 핵심 원리(고급편)' 카테고리의 다른 글
| Ch12. 스프링 AOP(실전 예제) - 프록시와 내부 호출(문제) (0) | 2022.04.22 |
|---|---|
| Ch12. 스프링 AOP(실전 예제) - 재시도 AOP (0) | 2022.04.21 |
| Ch11. 스프링 AOP(포인트컷) - this, target (0) | 2022.04.20 |
| Ch11. 스프링 AOP(포인트컷) - 매개변수 전달 (0) | 2022.04.20 |
| Ch11. 스프링 AOP(포인트컷) - @annotation, @args, bean (0) | 2022.04.20 |