- pom中添加aop的maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
- 写一个方法来使用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 "密码错误";
}
- 添加一个切面,加上注释
@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 -----------------------");
}
}
- 执行