springboot-aop的demo

Posted l1057618497

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot-aop的demo相关的知识,希望对你有一定的参考价值。

  1. pom中添加aop的maven依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>
  1. 写一个方法来使用aop
package com.lan.bbs.controller;

public String login(User user, HttpSession session){
        if(session.getAttribute("user")!=null){
            return "already login";
        }
        User u = userService.selectByAccount(user.gettAccount());
        if (u != null && u.gettAccount().equals(user.gettAccount()) &&
                u.gettPassword().equals(user.gettPassword())) {
            session.setAttribute("user", u);
            if(bloomFilter == null) setCounter(100);
            if (!bloomFilter.mightContain(u.gettAccount())) {
                count ++ ;
            }
            return "login success";
        }
        return "密码错误";
    }
  1. 添加一个切面,加上注释
    @Aspect
    @Component
    注意在springboot默认设置中,@Component组件必须要在application类的同级或者同级目录的下级包中才能被扫描到
package com.lan.bbs.test;
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.springframework.stereotype.Component;

@Aspect
@Component
public class NotVeryUsefulAspect {
    @Pointcut("execution(public * com.lan.bbs.controller.*.*(..))")// the pointcut expression, 对哪些方法使用这个aop
    public void anyOldTransfer() {}// the pointcut signature 方法签名

    @Before("com.lan.bbs.test.NotVeryUsefulAspect.anyOldTransfer()") //before-advice
    public void before(){
        System.out.println("----------aop before -----------------------");
    }

    @After("com.lan.bbs.test.NotVeryUsefulAspect.anyOldTransfer()")
    public void after(){
        System.out.println("----------aop after -----------------------");
    }
}

  1. 执行
    技术图片

以上是关于springboot-aop的demo的主要内容,如果未能解决你的问题,请参考以下文章