AOP注解式拦截


1. 自己定义的拦截注解

package com.spring.aop; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD,ElementType.TYPE}) @Documented
public @interface MyAction { String value(); }
2. 定义aop切点

package com.spring.aop; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; @Aspect @Component
public class MyAop { //切点切入自己配置的那个注解MyAction @Pointcut("@annotation(com.spring.aop.MyAction)") //注意这里的写法@annotation() 切入注解 public void annotationPointCat(){}

  /*
  @Pointcut("execution(* com.savage.aop.MessageSender.*(..))") //注意这里的写法execution() 切入类
  private void logSender(){}
*/

    
    @Before("annotationPointCat()")//位置为这个包下的所有类、所有方法、不论参数是什么类型
    public void before(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MyAction myAction =  method.getAnnotation(MyAction.class);
        System.out.println("before: "+myAction.value());
    }
    
    @After("annotationPointCat()")
    public void after(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MyAction myAction =  method.getAnnotation(MyAction.class);
        System.out.println("after: "+myAction.value());
    }
}
3. 编写服务类,应用切面

package com.spring.aop; import org.springframework.stereotype.Component; @Component
public class MyServer {
  /*
  显而易见,利用注解式拦截,会提高切面的复用率
  */ @MyAction(
"ser01") public void ser01(){ System.out.println("call ser01"); } @MyAction("ser02") public void ser02(){ System.out.println("call ser02"); } }
4. Spring配置文件(APP.xml)

base-package="com.spring.aop">
5. 运行   

public static void main(String[] args) { BeanFactory factory = new ClassPathXmlApplicationContext("com/spring/ioc/APP.xml"); MyServer myServer = factory.getBean(MyServer.class); myServer.ser01(); myServer.ser02(); }

依赖jar包    
org.springframework spring-context ${org.springframework-version} commons-logging commons-logging org.springframework spring-webmvc ${org.springframework-version} org.springframework spring-aop ${org.springframework-version} org.aspectj aspectjrt ${org.aspectj-version} org.aspectj aspectjweaver ${org.aspectj-version}
异常:
Caused by: java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
是因为缺少 aspectjweaver 包