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 본문

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

[스프링AOP실전] 로그 출력 AOP

Seung__ 2022. 1. 9. 11:48

@Trace 가 메서드에 붙어 있으면 호출 정보가 출력되도록 하자.

 

 

 

1. @Trace


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Trace {
}

 

 

2. 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 가 붙은 메서드에
어드바이스를 적용한다.

 

 

 

3. Repository


@Repository
public class ExamRepository {

    private static int seq = 0;

    /**
     * 5번에 한 번 실패하는 요청
     */
    @Trace
    public String save(String itemId){
        seq++;
        if (seq%5 == 0){
            throw new IllegalStateException("예외 발생");
        }

        return "ok";
    }
}

save()에 @Trace 적용

 

 

 

4. Service


@Service
@RequiredArgsConstructor
public class ExamService {

    private final ExamRepository examRepository;

    @Trace
    public void request(String itemId){
        examRepository.save(itemId);
    }
}

request() 에 @Trace 적용

 

 

 

5. Test


@Slf4j
@Import(TraceAspect.class)
@SpringBootTest
class ExamTest {

    @Autowired
    ExamService examService;

    @Test
    void test(){
        for (int i=0; i<5; i++){
            log.info("client request i={}", i);
            examService.request("data"+i);
        }
    }
}
client request i=0
[trace] void hello.aop.exam.ExamService.request(String), args=[data0]
[trace] String hello.aop.exam.ExamRepository.save(String), args=[data0]
client request i=1
[trace] void hello.aop.exam.ExamService.request(String), args=[data1]
[trace] String hello.aop.exam.ExamRepository.save(String), args=[data1]
client request i=2
[trace] void hello.aop.exam.ExamService.request(String), args=[data2]
[trace] String hello.aop.exam.ExamRepository.save(String), args=[data2]
client request i=3
[trace] void hello.aop.exam.ExamService.request(String), args=[data3]
[trace] String hello.aop.exam.ExamRepository.save(String), args=[data3]
client request i=4
[trace] void hello.aop.exam.ExamService.request(String), args=[data4]
[trace] String hello.aop.exam.ExamRepository.save(String), args=[data4]

request(), save()에 AOP가 적용 되었다.

 

 

6. GitHub: 220109 Log AOP


 

GitHub - bsh6463/SpringAOP

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

github.com

 

Comments