코딩항해기
[실습/Spring] AOP 활용 로그 작성 본문
수업 시간 진행한 실습 기록을 남기려다가 설계 수정하느라 업로드를 깜빡 잊었다.. ㅜㅠ
AOP를 활용해 요청 사항을 만족한 로그를 찍기
1. 서비스 기능에 반환이 있는 경우, 그 반환값이 배열인 경우에는 아무일이 발생하지 않지만, 그 반환값이 DTO일 때 어떤 DTO인지 로그로 안내
2. CUD에 대해서 전에 DB 접근 발생! 후에 DB 변경 완료! 로그로 안내
실습 풀이에서는 CRUD에 접근한 후 JoinPoint로 메서드 명을 받아와 검사하는 방식을 사용했는데, CUD에 대해서라는 말이 있어서 반환 타입이 boolean인 메서드만 접근하는 방식으로 풀었다.
Advice
조건에 맞춰 해당 로그를 실행한다.
@Service //bean 등록
@Aspect
@Slf4j
public class LogAdvice {
@AfterReturning(pointcut = "PointcutCommon.dtoPointcut()", returning = "dto")
public void dtoLogger(Object dto) {
String logMsg = null;
if(dto instanceof BoardDTO) { //게시글 DTO일때
logMsg = "dto is BoardDTO: " + dto;
}
else if(dto instanceof MemberDTO) { //멤버 DTO일때
logMsg = "dto is MemberDTO: " + dto;
}
log.info("AOP log: {}",logMsg);
}
@Before("PointcutCommon.cudPointcut()")
public void cudBeforeLogger(JoinPoint jp) {
log.info("AOP log: DB 접근 발생! {}", jp.getSignature());
}
@After("PointcutCommon.cudPointcut()")
public void cudAfterLogger(JoinPoint jp) {
log.info("AOP log: DB 변경 완료! {}", jp.getSignature());
}
Pointcut
해당 Pointcut을 참고해 AOP를 실행해 공통 기능을 처리하며 Advice 메서드 위에 작성된 조건에 맞춰 실행된다.
@Aspect
public class PointcutCommon {
@Pointcut("execution(* com.koreait.app.biz..*Impl.selectOne(..))")
public void dtoPointcut() {}
@Pointcut("execution(boolean com.koreait.app.biz..*Impl.*(..))")
public void cudPointcut() {}
}
(순서대로 로그인(selectOne), 글 작성(insert C), 게시글 조회(selectOne))
'problem solving > 과제&실습 코딩' 카테고리의 다른 글
[실습/React] todo list (0) | 2024.12.03 |
---|---|
[실습/Spring] 이미지 수정하기 (MultipartFile) (0) | 2024.10.23 |
[실습/Spring] 검색 기능 비동기(ajax)로 변경하기 (2) | 2024.10.14 |
[실습/Spring] 비동기(ajax) id 중복 검사 구현하기 (0) | 2024.10.14 |
[과제/Spring] 수업 실습 코드에 게시글 검색 추가하기 (0) | 2024.10.10 |