Jam's story

[Spring] days03- @Aspect 애노테이션을 이용한 AOP 본문

Spring

[Spring] days03- @Aspect 애노테이션을 이용한 AOP

애플쩀 2022. 7. 13. 11:48

[XML 스키마 기반 AOP 구현]

  1. advice 패키지 삭제
  2. xml 내용 제거

스프링 AOP 3가지 방법 중에

+++ XML 스키마 기반 AOP 구현 +++

처리과정

  1. 스프링 AOP 를 사용하기 위해 jar 의존파일 추가
    • weaver.jar 추가
  2. aop.advice 패키지 -- 삭제
    • B, A, A advice 3가지
    • 공통기능을 제공할 클래스 추가
    • aop.LogPrintProfiler.java
      • trace() 구현 - Around Advice
  3. xml 설정파일
    • <aop:config> aop 설정하는 태그
    • Aspect 를 설정
    • Advice 를 어떤 Pointcut 에 적용할지를 설정 (지정)

p.252 AspectJ 의 문법

pointcut

  1. execution 명시자
  2. within 명시자
  3. bean 명시자

 


@Aspect 어노테이션 사용방법 

1.Aspect 어노테이션을 사용하여 Aspect 클래스 구현

 -Aspect 클래스는 Advice를 구현한 메소드 +Pointcut 구현

2.xml파일 <aop:aspectj-autoproxy/> 설정

   자바코딩 @Configuration

                  @EnableAspectJAutoProxy

 

JoinPoint를 파라미터로 사용 
대상객체 및 호출되는 메서드에 대한 정보가 전달되는 파라미터에 대한 정보가 필요한 경우 

 

 

 LogPrintProfiler

package aop.advice;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

//before ,after,around advice를 대신할 공통 기능을 구현할 클래스 
@Component()
@Aspect //<aop:aspect id="traceAspect" ref="logPrintProfiler">
public class LogPrintProfiler {

	@Pointcut("execution(public * aop..*.*(*,*))")
	public void publicMethod() {}
	
    // 1. Around Advice - 처리시간을 로그로 기록 (출력)
	  @Around("publicMethod() {}")
    public Object trace(ProceedingJoinPoint joinPoint) throws Exception {
        String signature = joinPoint.getSignature().toShortString();

        Log log = LogFactory.getLog(this.getClass());
        StopWatch sw = new StopWatch();
        log.info("> " + signature + "() start.");
        sw.start();

        Object result = null;

        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            sw.stop();
            log.info("> " + signature + "() stop.");
            log.info("> " + signature + "() 처리시간: " + sw.getTotalTimeMillis() + "ms");
        }
        return result;
    }
//before과 after는 매개변수를 JoinPoint joinpoint 
//함수명은 마음대로
    @Before("execution(public * aop..*.*(*,*))")
    public void before(JoinPoint joinpoint) {
        String methodName = joinpoint.getSignature().getName();
        Log log = LogFactory.getLog(this.getClass());
        log.info(">>> " + methodName + "() before advice.");
    }

    @After("execution(public * aop..*.*(*,*))")
    public void afterFinally(JoinPoint joinpoint) {
        String methodName = joinpoint.getSignature().getName();
        Log log = LogFactory.getLog(this.getClass());
        log.info(">>> " + methodName + "() afterFinally advice.");
    }
}

 

 

xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
               http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
           ">

    <context:component-scan base-package="aop" />
    <aop:aspectj-autoproxy />

</beans>

 

 

CalculatorImpl

package aop;

import org.springframework.stereotype.Component;

@Component("calc")
public class CalculatorImpl implements Calculator {

	@Override
	public int add(int x, int y) {	
		int result=x+y;
		return result;
	}

	@Override
	public int sub(int x, int y) {
		int result=x-y;	
		return result;
	}

	@Override
	public int mult(int x, int y) {
		int result=x*y;
		return result;
	}

	@Override
	public int div(int x, int y) {
		int result=x/y;
		return result;
	}

}

 

Ex01.java

package springDI;

import org.springframework.context.support.GenericXmlApplicationContext;

import aop.Calculator;
import aop.CalculatorImpl;

public class Ex01 {
public static void main(String[] args) {
	String  resourceLocations="applicationContext.xml";
	GenericXmlApplicationContext ctx= new GenericXmlApplicationContext(resourceLocations);

	//Calculator calc=ctx.getBean("calc", CalculatorImpl.class);
	Calculator calc=ctx.getBean("calcProxy", CalculatorImpl.class);
	System.out.println(calc.add(4, 2));
}
}

 

 

 

실행결과 

 

 

 

 

'Spring' 카테고리의 다른 글

[Spring] MVC2 모델을 이용한 게시판 구현  (0) 2022.07.14
[Spring] 다이나믹웹프로젝트생성과 MVC2패턴  (0) 2022.07.13
[Spring] days02 - AOP  (0) 2022.07.12
[Spring] 뉴렉처강의_DI  (0) 2022.07.12
[Spring] days1  (0) 2022.07.11
Comments