예를 들어 Java의 Spring 프레임워크에서 AOP 프로그래밍 방식의 사용에 대해 설명합니다.

7773 단어 JavaSpringAOP
1. AOP란 무엇인가
AOP는 Aspect Oriented Programming의 줄임말로 방면으로 프로그래밍하는 것을 의미하며 AOP는 실제적으로 GoF 디자인 모델의 연장이다.
2, Spring AOP 관련 용어:
A, 절단면(Aspect): Spring AOP에서 절단면은 일반 클래스 또는 일반 클래스에서 @Aspect 메모(@AspectJ 스타일)로 구현할 수 있습니다.
B, 연결 점(Joinpoint): Spring AOP에서 하나의 연결 점은 하나의 방법의 실행을 나타냅니다.
C, 알림(Advice): 탄젠트의 특정 연결점(Joinpoint)에서 수행되는 작업입니다.알림에는 "around", "before", "after"등 알림이 있습니다. 스프링을 포함한 많은 AOP 프레임워크는 차단기를 알림 모델로 하고 연결점 중심의 차단기 체인을 유지합니다.
D, 삽입점(Pointcut): 이 방법을 실행할 때 알림을 표시하는 방법 또는 세트를 정의합니다. Spring은 기본적으로 AspectJ 삽입점 구문을 사용합니다.
3. 알림 유형
A, 선행 알림(@Before): 연결점(join point) 이전에 실행된 알림이지만, 이 알림은 연결점 앞의 실행을 막을 수 없습니다(이상이 발생하지 않는 한).
B, 반환 후 알림(@AfterReturning): 연결점(join point)이 정상적으로 완성된 후에 실행되는 알림: 예를 들어 어떤 방법도 이상을 던지지 않고 정상적으로 되돌아오는 방법
C, 예외 던지기 후 알림(@AfterThrowing): 예외 던지기 종료 시 실행되는 알림 방법
D, 후 알림(@After): 연결점이 종료되었을 때 실행되는 알림(정상적인 반환이든 비정상적인 종료든)
E, 서라운드 알림(@Around): 방법 호출과 같은 연결점(join point)을 둘러싼 알림입니다.이것은 가장 강력한 알림 형식입니다. 알림을 둘러싸고 방법 호출 전후에 사용자 정의 행동을 완성할 수 있으며, 연결점을 계속 실행하거나 자신의 반환값을 직접 되돌리거나 이상을 던져서 실행을 끝낼지 여부를 선택할 수 있습니다.
 
4, @AspectJ 스타일의 AOP 구성
Spring AOP 구성에는
A, XML 스타일 = Spring AOP 선언
B, AspectJ 스타일 = 메모 형식으로 Spring AOP 구현
5, 인스턴스
절면류 TestAspect

package com.spring.aop; 
/** 
 *   
 */ 
public class TestAspect { 
 
  public void doAfter(JoinPoint jp) { 
    System.out.println("log Ending method: " 
        + jp.getTarget().getClass().getName() + "." 
        + jp.getSignature().getName()); 
  } 
 
  public Object doAround(ProceedingJoinPoint pjp) throws Throwable { 
    long time = System.currentTimeMillis(); 
    Object retVal = pjp.proceed(); 
    time = System.currentTimeMillis() - time; 
    System.out.println("process time: " + time + " ms"); 
    return retVal; 
  } 
 
  public void doBefore(JoinPoint jp) { 
    System.out.println("log Begining method: " 
        + jp.getTarget().getClass().getName() + "." 
        + jp.getSignature().getName()); 
  } 
 
  public void doThrowing(JoinPoint jp, Throwable ex) { 
    System.out.println("method " + jp.getTarget().getClass().getName() 
        + "." + jp.getSignature().getName() + " throw exception"); 
    System.out.println(ex.getMessage()); 
  } 
 
  private void sendEx(String ex) { 
    //TODO   
  } 
}  

package com.spring.service; 
/** 
 *  A 
 */ 
public interface AService { 
   
  public void fooA(String _msg); 
 
  public void barA(); 
} 

package com.spring.service; 
/** 
 * A  
 */ 
public class AServiceImpl implements AService { 
 
  public void barA() { 
    System.out.println("AServiceImpl.barA()"); 
  } 
 
  public void fooA(String _msg) { 
    System.out.println("AServiceImpl.fooA(msg:"+_msg+")"); 
  } 
} 

package com.spring.service; 
 
/** 
 *  Service B 
 */ 
public class BServiceImpl { 
 
  public void barB(String _msg, int _type) { 
    System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")"); 
    if(_type == 1) 
      throw new IllegalArgumentException(" "); 
  } 
 
  public void fooB() { 
    System.out.println("BServiceImpl.fooB()"); 
  } 
 
} 
ApplicationContext

<?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-2.0.xsd 
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" 
  default-autowire="autodetect"> 
  <aop:config> 
    <aop:aspect id="TestAspect" ref="aspectBean"> 
      <!-- com.spring.service --> 
      <aop:pointcut id="businessService" 
        expression="execution(* com.spring.service.*.*(..))" /> 
      <aop:before pointcut-ref="businessService" method="doBefore"/> 
      <aop:after pointcut-ref="businessService" method="doAfter"/> 
      <aop:around pointcut-ref="businessService" method="doAround"/> 
      <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/> 
    </aop:aspect> 
  </aop:config> 
   
  <bean id="aspectBean" class="com.spring.aop.TestAspect" /> 
  <bean id="aService" class="com.spring.service.AServiceImpl"></bean> 
  <bean id="bService" class="com.spring.service.BServiceImpl"></bean> 
 
</beans> 
테스트 클래스 AOPTEST

public class AOPTest extends AbstractDependencyInjectionSpringContextTests { 
   
  private AService aService; 
   
  private BServiceImpl bService; 
   
  protected String[] getConfigLocations() { 
    String[] configs = new String[] { "/applicationContext.xml"}; 
    return configs; 
  } 
   
   
  /** 
   *   
   */ 
  public void testCall() 
  { 
    System.out.println("SpringTest JUnit test"); 
    aService.fooA("JUnit test fooA"); 
    aService.barA(); 
    bService.fooB(); 
    bService.barB("JUnit test barB",0); 
  } 
   
  /** 
   *  After-Throwing 
   */ 
  public void testThrow() 
  { 
    try { 
      bService.barB("JUnit call barB",1); 
    } catch (IllegalArgumentException e) { 
       
    } 
  } 
   
  public void setAService(AService service) { 
    aService = service; 
  } 
   
  public void setBService(BServiceImpl service) { 
    bService = service; 
  } 
} 
 
실행 결과는 다음과 같습니다.

log Begining method: com.spring.service.AServiceImpl.fooA 
AServiceImpl.fooA(msg:JUnit test fooA) 
log Ending method: com.spring.service.AServiceImpl.fooA 
process time: 0 ms 
log Begining method: com.spring.service.AServiceImpl.barA 
AServiceImpl.barA() 
log Ending method: com.spring.service.AServiceImpl.barA 
process time: 0 ms 
log Begining method: com.spring.service.BServiceImpl.fooB 
BServiceImpl.fooB() 
log Ending method: com.spring.service.BServiceImpl.fooB 
process time: 0 ms 
log Begining method: com.spring.service.BServiceImpl.barB 
BServiceImpl.barB(msg:JUnit test barB type:0) 
log Ending method: com.spring.service.BServiceImpl.barB 
process time: 0 ms 
 
log Begining method: com.spring.service.BServiceImpl.barB 
BServiceImpl.barB(msg:JUnit call barB type:1) 
log Ending method: com.spring.service.BServiceImpl.barB 
method com.spring.service.BServiceImpl.barB throw exception 
  


좋은 웹페이지 즐겨찾기