接着上上一篇: 《springboot学习笔记 02》--访问数据库
需求: 访问接口(http://localhost:8081/mydb2/getStudent)查询Student数据之前, 先校验是否登录
1, pom.xml添加依赖
<!-- aop登录校验 -->
<dependency><!-- spring boot aop starter依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2, 接口getStudent()
@RequestMapping("/getStudent")
public List<Student> getStudent(){
System.out.println("执行StudentController2的getStudent()");
List<Student> list = service.getStudent();
return list;
}
3, 写Aspect类拦截
@Aspect
@Component
public class StudentAspect {
@Before("execution(public * com.test.controller.StudentController2.getStudent(..))")
public void doBefore() {
System.out.println("@Before拦截");
};
@After("execution(public * com.test.controller.StudentController2.getStudent(..))")
public void doAfter() {
System.out.println("@After拦截");
};
}
4, 启动测试
访问: http://localhost:8081/mydb2/getStudent, 能按顺序正确打印日志即ok
PS: 如果出现注解拦截不生效的情况, 有可能是StudentAspect 类的路径问题, 将其加入初始化组件扫描才行。
5, @AfterReturning、@AfterThrowing、@Around用法以及代码优化
## @Pointcut提取出需要拦截的接口路径, 进行统一指定
@Aspect
@Component
public class StudentAspect {
@Pointcut("execution(public * com.test.controller.StudentController2.*(..))")
public void excudeService(){
System.out.println("begin");
}
@Before("excudeService()")
public void doBefore() {
System.out.println("@Before拦截");
};
@After("excudeService()")
public void doAfter() {
System.out.println("@After拦截");
};
@AfterReturning("excudeService()")
public void doAfterReturning() {
System.out.println("@AfterReturning拦截");
};
@AfterThrowing("excudeService()")
public void doAfterThrowing() {
System.out.println("@AfterThrowing拦截");
};
@Around("excudeService()")
public void doAround() {
System.out.println("@Around拦截");
};
}
@AfterReturning、@AfterThrowing、@Around用法和@Before类似, 只是执行顺序略有不同
6, 打印url、method等访问信息
@Before("excudeService()")
public void doBefore() {
System.out.println("@Before拦截");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
System.out.println("url: " + request.getRequestURI());
//method
System.out.println("method: " + request.getMethod());
//ip
System.out.println("ip: " + request.getRemoteAddr());
//类方法
/*System.out.println("类方法: " + joinpoint.getStaticPart().getDeclaredAnnotations());
//参数
System.out.println("参数: " + joinpoint.getClass());*/
};
## 打印类方法时需要给doBefore()传参(Joinpoint joinpoint), 操作时候出现报错, 暂且搁这了;