Spring AOP의 몇 가지 구현 방법 요약

7579 단어 springaop
AOP 핵심 개념
1. 횡단 관심점
어떤 방법에 대해 차단을 하고, 차단한 후에 어떻게 처리하는지, 이런 관심사를 횡단 관심사라고 부른다
2. 절단면(aspect)
유형은 물체 특징에 대한 추상이고, 절단면은 횡단 관심점에 대한 추상이다
3. 연결점(joinpoint)
차단된 점, 스프링은 방법 형식의 연결점만 지원하기 때문에 스프링에서 연결점은 차단된 방법을 가리키며, 실제 연결점은 필드나 구조기일 수도 있다
4, 삽입점(pointcut)
연결점을 차단하는 정의
5. 알림(advice)
알림이란 연결점에 가로막힌 후 실행할 코드를 가리키며, 알림은 전치, 후치, 이상, 최종, 주위 알림 다섯 종류로 나뉜다
6. 대상 객체
에이전트의 대상 객체
7, 짜임 (weave)
대상 객체에 탄젠트를 적용하고 프록시 객체를 생성하는 프로세스
8. 도입(introduction)
코드를 수정하지 않는 전제에서 운행 기간에 클래스를 동적으로 추가할 수 있는 방법이나 필드를 도입한다
Spring AOP 구현에 필요한 패키지:
1. Spring에서 제공하는 jar 패키지
2、aopalliance.jar
3、aspectjweaver.jar
Spring AOP 방식:
1. Java 동적 에이전트
이 방법은 인터페이스의 실례에 대해 에이전트를 만듭니다
applicationContext.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" 
  xmlns:tx="http://www.springframework.org/schema/tx" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> 
     
    <bean id="concreteImplementor" class="com.marving.aop.ConcreteImplementor" /> 
  
    <bean id="interceptorHandler" class="com.marving.aop.InterceptorHandler" /> 
     
    <aop:config> 
      <aop:aspect id="interceptor" ref="interceptorHandler"> 
        <aop:pointcut id="addAllMethod" expression="execution(* com.marving.aop.Abstration.*(..))" /> 
        <aop:before method="doSomething" pointcut-ref="addAllMethod" /> 
        <aop:after method="doSomething" pointcut-ref="addAllMethod" /> 
      </aop:aspect> 
    </aop:config> 
</beans> 
그 중에서 Abstration은 인터페이스이고 Concrete Implementor는 실현 클래스이고 Interceptor Handler는 프록시 차단 클래스입니다.

public interface <span style="font-size:12px;">Abstration</span> { 
  public void operation() 
} 

//  
public class ConcreteImplementor implements Implementor{ 
 
  @Override 
  public void operation() {   
    System.out.println("ConcreteImplementor"); 
  } 
 
} 

public class InterceptorHandler{  
  public void printTime(){ 
    System.out.println("CurrentTime = " + System.currentTimeMillis()); 
  } 
} 
2. CGLIB 생성 에이전트
CGLIB는 프록시 객체가 클래스인 경우에 사용됩니다.
MethodInterceptor 인터페이스를 실현하고public Object intercept(Object obj, Method m, Object []args, MethodProxy proxy)throws Throwable 방법으로 에이전트를 생성합니다.
3. BeanNameAutoProxyCreator 구현 AOP
Spring은 우리에게 자동 에이전트 메커니즘을 제공하여 용기가 우리에게 자동으로 에이전트를 생성하고 번거로운 설정 작업에서 우리를 해방시켰다. 내부에서 Spring은 BeanPostProcessor를 사용하여 자동으로 이 작업을 완성했다.
구성은 다음과 같습니다.

<bean id="MyInterceptor" class="com.yesjpt.interceptor. MyInterceptor"></bean>  
<bean  
  class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
  <property name="beanNames">  
    <list>  
      <value>*Service</value>  
    </list>  
  </property>  
  <property name="interceptorNames">  
    <list>  
      <value>MyInterceptor</value>  
    </list>  
  </property>  
 </bean> 

여기서 *Service는 에이전트를 차단해야 하는 bean으로 Service로 끝나는 것을 모두 차단하고 MyInterceptor를 사용하여 차단합니다. 여러 개의 차단기를 설정하여 순서대로 실행할 수 있습니다.

import java.lang.reflect.Method; 
import org.aopalliance.intercept.MethodInterceptor; 
import org.aopalliance.intercept.MethodInvocation; 
/** 
 * @author 
 * 
 */  
public class MyInterceptor implements MethodInterceptor{  
  
  @Override  
  public Object invoke(MethodInvocation invocation) throws Throwable {  
      
    Method method = invocation.getMethod();//   
    Object[] arguments = invocation.getArguments();//   
    /* 
     *  ,  
     *  , ,  
     */  
    //   
    this.beforeReslove();  
    Object proceed = invocation.proceed();//   
    //   
    proceed = this.afterReslove();  
    return proceed;  
  } 
   private Object afterReslove() { 
      System.out.println("CurrentTime = " + System.currentTimeMillis()); 
     return null; 
   } 
   private void beforeReslove() { 
      System.out.println("CurrentTime = " + System.currentTimeMillis()); 
   }   
} 
4, 메모 AspectJ를 사용하여 AOP 구현
ApplicationContext.xml 가입

<aop:aspectj-autoproxy/> 
탄젠트 처리 클래스 생성하기

package com.marving.aop; 
import java.util.Arrays; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut; 
import org.springframework.stereotype.Component;  
@Aspect 
@Component  
public class AspectHandler { 
   
  @Pointcut("execution(* com.marving.service.BaseServ+.*(..))") 
  private void doMethod() { 
  } 
 
    /** 
   * This is the method which I would like to execute before a selected method 
   * execution. 
   */ 
  @Before("doMethod()") 
  public void beforeAdvice() { 
    System.out.println("before method invoked."); 
  } 
 
  /** 
   * This is the method which I would like to execute after a selected method 
   * execution. 
   */ 
  @After("doMethod()") 
  public void afterAdvice() { 
    System.out.println("after method invoked."); 
  } 
 
  //  controller , aspect()  
  @Around("doMethod()") 
  public Object around(ProceedingJoinPoint pjp) throws Throwable{ 
    Object result = null; 
    String methodName = pjp.getSignature().getName(); 
    try { 
      System.out.println("The method [" + methodName + "] begins with " + Arrays.asList(pjp.getArgs())); 
      result = pjp.proceed(); 
    } catch (Throwable e) { 
      System.out.println("The method [" + methodName + "] occurs expection : " + e); 
      throw new RuntimeException(e); 
    } 
    System.out.println("The method [" + methodName + "] ends"); 
    return result; 
  } 
} 

표현식 execution(*com.marving.service.BaseServ+.*(...)삽입점 함수 일치@Before@After@Around는 차단 방법이 실행되기 전, 중, 후를 차단하고 처리 함수를 실행합니다.
@Around @Before @After 세 주석의 차이점 @Before는 차단 방법이 실행되기 전에 논리를 실행합니다. @After는 차단 방법이 실행된 후에 논리를 실행합니다. @Around는 차단 방법의 앞뒤에 논리를 동시에 실행할 수 있다.
주의해야 할 것은 Around가 차단 방법을 한 후에 하나의 방법 집행 결과를 되돌려야 한다는 것이다. 그렇지 않으면 원래의 방법은 정상적으로 집행할 수 없다.
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기