advice는 실행되는 시점에 따라 여러가지 타입으로 작성할 수 있다.
애너테이션 | 설명 |
---|---|
@Before | 타겟 메서드 호출 전 advice 실행 |
@AfterReturning | 타겟 메서드가 정상 종료 (return) 후 advice 실행 |
@AfterThrowing | 타겟 메서드에서 예외가 던져졌을 때 (throws XXException) advice 실행 |
@After | 타겟 메서드 성공 여부 (return or throws)와 무관하게 언제나 advice 실행 |
@Around | advice 내부에서 타겟 메서드 호출 (타겟 메서드의 모든 것을 제어 가능) |
@Before("execution(com.practice.aop.dto.User com.practice..regist(com.practice.aop.dto.User)) && args(user)")
public void before(JoinPoint jp, User user) {
// user = new User("hi", "1234"); // 새로운 값으로는 대체 불가
user.setPass("암호화_" + user.getPass());
}
@AfterReturning(value = "userPointcut()", returning = "user")
public void maskingPW(JoinPoint jp, User user) {
user.setPass("*"); // return 값 조작
}
@AfterThrowing(value = "userPointcut()", throwing = "e")
public void getException(JoinPoint jp, RuntimeException e) {
log.debug("에러 발생");
}
@After("bean(myService)")
public void endlogging(JoinPoint jp) {
log.debug("끝");
}
@Around("execution(* com.example..*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs(); // 파라미터를 가져옴
args[0] = "Modified Value"; // 파라미터 수정
Object result = joinPoint.proceed(args); // 수정된 파라미터로 메서드 호출
return result;
}
@Around("execution(* com.example.service.MyService.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 메서드 실행 전
System.out.println("메서드 실행 전: " + joinPoint.getSignature());
// 메서드 파라미터 로그 출력
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
System.out.println("파라미터 값: " + arg);
}
// 타겟 메서드 실행
Object result = joinPoint.proceed();
// 메서드 실행 후
System.out.println("메서드 실행 후: " + joinPoint.getSignature());
// 리턴 값을 변경 (예: 원래 결과에 " - modified" 추가)
if (result instanceof String) {
result = result + " - modified";
}
// 수정된 리턴 값을 반환
return result;
}
}
joinPoint.getSignature()
를 사용해 호출되는 메서드의 정보를 로그로 출력한다.joinPoint.getArgs()
로 메서드의 파라미터 값을 가져와서 로그로 출력한다.joinPoint.proceed()
가 호출되면, 실제 타겟 메서드가 실행된다.result
에 저장한 후, 그 값이 String
타입이면 " - modified"라는 문자열을 추가로 붙인다.