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. 执行
posted @ 2020-04-06 10:22  少年留不住  阅读(158)  评论(0编辑  收藏  举报