Spring AOP的配置和实现

因为接下来要记录日志,所以把日志的配置文件也一起导入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

然后定义一个注解,带有一个方法参数,目的是记录这个方法的运行时间

import java.lang.annotation.*;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodLog {

    String methodName() default "";  //操作名称

}

接下来定义一个类处理切面,并且获取方法执行的时间,其中

joinPoint.proceed();

是执行这个方法

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;


@Aspect
@Configuration
public class LogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.mayproject.seckill.util.MethodLog)")
    public void pointCutMethod() {
    }

    @Around("pointCutMethod()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        MethodLog methodLog = method.getAnnotation(MethodLog.class);
        String key = methodLog.methodName();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object o = joinPoint.proceed();
        stopWatch.stop();
        String result = MessageFormat.format("{0}, 耗时:{1}ms\r", key, stopWatch.getTime());
        LOGGER.info(result);
        return o;
    }
}

因为日志功能暂时还没完全配好,所以先用打印来代替

然后在使用的时候,在对应方法上面加上这个注解即可

比如:

@Transactional
    @MethodLog(methodName = "秒杀动作")
    public OrderInfo miaosha(MiaoshaUser miaoshaUser,GoodsVo goodsVo){

即可在控制台输入以下结果:

登录动作 耗时:7ms
秒杀动作 耗时:12ms

猜你喜欢

转载自blog.csdn.net/qq_34165535/article/details/81591221