반응형

@AspectJ Based AOP with Spring



(원문 위치 : http://www.tutorialspoint.com/spring/aspectj_based_aop_appoach.htm )

@AspectJ는 Java 5 annotation으로 선언(annotated)된 java class로 aspect를 선언하는 형태로 참조(조회?)한다. @AspectJ 지원은 XML schema기반 설정파일에 아래 요소를 포함하여 가능하게 된다.
<aop:aspectj-autoproxy/>
(추가적인 라이브러리에 대한 언급이 있으나 maven으로 실행시 별도로 추가하지 않았다. - XML schema 기반과 동일)


Declaring an aspect

Aspect class는 아래와 같이 @Aspect로 선언되는 것을 제외하면 다른 일반 bean과 같고 다른 class처럼 method와 field를 갖을 수 있다.

package org.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AspectModule {

}

이것은 아래와 같이 다른 bean과 같이 XML에서 설정될 것이다.

<bean id="myAspect" class="org.xyz.AspectModule">
   <!-- configure properties of aspect here as normal -->
</bean>

Declaring a pointcut

 pointcut은 다른 advice와 실행되어지기 위한 관심(기능?)의 joint point(즉 함수)를 결정하는 것을 돕니다. @AspectJ기반 설정으로 작업에서 pointcut선언은 두 부분을 갖는다.

- 관심있는 함수 실행을 정확하게 결정하는 pointcut 표현(expression)

- 이름과 파라미터를 구성하는 pointcut 시그니쳐(signature). 함수의 실제 body는 관계없고 사실 비어있을 수 있다.


아래 예제는 com.xyz.myapp.service 패키지의 class에서 유용한 모든 함수의 실행에 부합하는 'businessService'로 이름지어진 pointcut을 정의한다. 

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression 
private void businessService() {}  // signature

아래 예제는 com.tutorialspoint  패키지의 Student class에서 유요한 getName()함수의 실행에 부합하는 'getname'으로 이름붙여진 pointcut을 정의한다.

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.tutorialspoint.Student.getName(..))") 
private void getname() {}

Declaring advices

아래와 같이 @{ADVICE-NAEM} annotation을 사용하여 다섯가지 advice의 어떤것이라도 선언할 수 있다. 이 예제는 businessService() pointcut 시그니쳐 함수를 이미 정의했다고 가정한다.

@Before("businessService()")
public void doBeforeTask(){
 ...
}

@After("businessService()")
public void doAfterTask(){
 ...
}

@AfterReturning(pointcut = "businessService()", returning="retVal")
public void doAfterReturnningTask(Object retVal){
  // you can intercept retVal here.
  ...
}

@AfterThrowing(pointcut = "businessService()", throwing="ex")
public void doAfterThrowingTask(Exception ex){
  // you can intercept thrown exception here.
  ...
}

@Around("businessService()")
public void doAroundTask(){
 ...
}

advice에 대해 inline pointcut을 정의할 수 있다. 아래 예제는 before advice에 대한 inline pointcut정의이다.

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
 ...
}

@AspectJ Based AOP Example

AOP기반 @AspectJ에 관련되어 위에 언급된 개념을 이해하기 위한 예제를 보자.


[003] HelloWorld Example 강좌를 참조하여 프로젝트를 생성한다.

[018-1] XML Schema Based AOP with Spring 강좌를 참조하여 pom.xml에 의존관계를 추가한다.


Logging.java:

package com.tutorialspoint;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;

@Aspect
public class Logging {

   /** Following is the definition for a pointcut to select
    *  all the methods available. So advice will be called
    *  for all the methods.
    */
   @Pointcut("execution(* com.tutorialspoint.*.*(..))")
   private void selectAll(){}

   /** 
    * This is the method which I would like to execute
    * before a selected method execution.
    */
   @Before("selectAll()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }

   /** 
    * This is the method which I would like to execute
    * after a selected method execution.
    */
   @After("selectAll()")
   public void afterAdvice(){
      System.out.println("Student profile has been setup.");
   }

   /** 
    * This is the method which I would like to execute
    * when any method returns.
    */
   @AfterReturning(pointcut = "selectAll()", returning="retVal")
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }

   /**
    * This is the method which I would like to execute
    * if there is an exception raised by any method.
    */
   @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
   public void AfterThrowingAdvice(IllegalArgumentException ex){
      System.out.println("There has been an exception: " + ex.toString());   
   }
   
}

Student.java:

package com.tutorialspoint;

public class Student {
   private Integer age;
   private String name;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
	  System.out.println("Age : " + age );
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }
   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

MainApp.java:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      Student student = (Student) context.getBean("student");

      student.getName();
      student.getAge();
      
      student.printThrowException();
   }
}

Beans.xml:

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

    <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 
      
</beans>

실행 결과는 아래와 같다. XML Schema 기반관련 강좌의 예제와 선언방식의 차이를 제외하고는 동일하기 때문에 별도의 부연설명은 추가하지 않았다.

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
..... 

other exception content 

반응형

+ Recent posts