메모장

AOP 로그 실습 (@ 어노테이션 으로 변경) 본문

Spring/개념정리

AOP 로그 실습 (@ 어노테이션 으로 변경)

Itchild 2024. 7. 4. 13:42
728x90
반응형

 

 

1. applicationContext.xml 설정하기

 

<aop:aspectj-autoproxy /> << @ 어노테이션 방식으로 코드 작성할게 !

 

2. Advice 클래스 객체화

 

@Component 안에 있는 좀더 명확한 @Service 레이어를 사용한다.

 

3. Pointcut 설정해주기

 

execution 실행할게~ 범위는

( * output 은 정해지지 않았다.

com.spring.biz..*Impl << ~Impl 로 끝나는 클래스를

*(..) input의 인자는 여러개가 들어올 수 있어서 (..) 으로 표시 )

 

4. JoinPoint 설정

 

 

5. Aspect 결합하기

 

@Aspect 어노테이션으로 결합해주기

 


AOP (@ 어노테이션 모듈화 작업)

 

AOP 의 @ 어노테이션으로 변경한 코드를 모듈화 해보자 !

 

Pointcut 클래스를 만들어 분리

 

 

Advice 한곳에 모아 응집도 높이기

package com.spring.biz.common;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import com.spring.biz.member.MemberVO;

@Service
@Aspect
public class LogAdvice {
	@Before("PointCutCommon.aPointcut()")
	public void beforeLog() {
		System.out.println("횡단관심: 비즈니스 메서드 수행 전에 호출됨");
	}
	
	@After("PointCutCommon.bPointcut()")
	public void afterLog() {
		System.out.println("[횡단관심]");
		System.out.println("     비즈니스 메서드 수행 후에 호출됨");
		System.out.println();
	}
	
	@AfterReturning(pointcut="PointCutCommon.cPointcut()", returning="returnObj")
	public void afterReturningLog(JoinPoint jp, Object returnObj) {
		String methodName=jp.getSignature().getName();
		System.out.println("횡단관심 : "+methodName+"의 반환 이후의 로그");
		if(returnObj instanceof MemberVO) {
			MemberVO mVO=(MemberVO)returnObj;
			if(mVO.getRole().equals("ADMIN")) {
				System.out.println("[관리자 입장]");
			}
			else {
				System.out.println("[사용자 입장]");
			}
		}
		else {
			System.out.println("[데이터 열람]");
		}
	}
	
	@AfterThrowing(pointcut="PointCutCommon.dPointcut()", throwing="exceptObj")
	public void afterThrowingPrintLog(JoinPoint jp, Exception exceptObj) {
		String methodName = jp.getSignature().getName();
		System.out.println("횡단 관심 : "+methodName+"에서 예외가 발생해서 출력되는 로그");
		System.out.println("예외 메세지 : "+exceptObj.getMessage());
	}
	
	@Around("PointCutCommon.ePointcut()")
	public Object aroundPrintLog(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("around 로그 전");
		StopWatch sw=new StopWatch();
		sw.start();
		Object obj=pjp.proceed();
		sw.stop();
		String methodName=pjp.getSignature().getName();
		System.out.println(methodName+" 메서드를 수행하는데에 소요한 시간은 "+sw.getTotalTimeMillis()+"초입니다.");
		System.out.println("around 로그 후");
		return obj;
	}
}
 

 

 

728x90
반응형

'Spring > 개념정리' 카테고리의 다른 글

Spring JDBC 실습 (selectAll / One)  (1) 2024.07.04
Spring JDBC  (1) 2024.07.04
AOP 실습2 (after-throwing,around 실습)  (0) 2024.07.04
AOP 실습 (.xml)  (0) 2024.07.04
AOP (.xml 방식)  (0) 2024.07.04