Aspect切面的使用实例

一、导入切面库

以maven工程为例,除了springmvc基础的库,需要导入切面库,本例aspectj为例。

    <properties>
        <aspectj.version>1.9.3</aspectj.version>
    </properties>
  ......
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>

二、编写基础植入的类,以打印功能为例。

不得不歌颂一下注解和Spring,引入和配置大大的简化了。

@Aspect
@Slf4j
@Component
public class LogAspectUtil {
    @Pointcut("execution(public * com.sanro.controller..*.*(..))")//配置需要植入打印的包路径
    public void controllerLog() {
    }

    @Before("controllerLog()")
    public void logBefore(JoinPoint joinPoint) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        log.info("full url = " + request.getRequestURL().toString());
        log.info("http method = " + request.getMethod());
        log.info("class method = " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }

    @After("controllerLog()")
    public void logAfter(JoinPoint joinPoint) {
        log.info("controller execute finished... ");
    }

}

三、坐享其成

现在com.sanro.controller目录下的所有controller类都能
1. 在请求进入的时候自动打印请求的url,method等想要的信息和处理动作;
2. 在请求处理结束的时候都能打印时间或者增加想要的处理动作。

转载于:https://www.cnblogs.com/yoyotl/p/11185866.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值