在Spring框架3.X中使用AOP

为了简单期间,我从mykong上找了3.X的脚手架工程,可以参考这里。我略作了调整,改成了JDK 1.8.

1 添加依赖

<!-- aop -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.8.9</version>
</dependency>

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.9</version>
</dependency>

这里用的是1.8.x,如果你参照网上很多用的1.6.x版本的话,会在运行时报这个错:Invalid byte tag in constant pool: 18

2 写一个注解

我这里要验的是对注解 执行aop

package com.mkyong.web.annotation;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface MeterMethod {
}

注意这里是METHOD类型的,因为Spring的AOP的@annotation只支持方法注解。

3 写一个Aspect

package com.mkyong.web.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.util.Arrays;

@Aspect
public class LogAspect {

    @Around("@annotation(com.mkyong.web.annotation.MeterMethod)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("logAround() is running!");
        System.out.println("hijacked class : " + joinPoint.getSignature().getClass().getCanonicalName());
        System.out.println("hijacked method : " + joinPoint.getSignature().getName());
        System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));

        System.out.println("Around before is running!");
        Object res = joinPoint.proceed();
        System.out.println("Around after is running!");

        System.out.println("******");

        return res;

    }

}

4 xml配置

添加2行

<aop:aspectj-autoproxy />
<bean class="com.mkyong.web.aspect.LogAspect" />

如果报错的话,看看顶上加几行

   xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="

      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"

最后就可以验证了

Leave a Reply

Your email address will not be published. Required fields are marked *