SpringBoot中AOP的使用

AOP的理解:我们传统的编程方式是垂直化的编程,一个逻辑完毕之后执行另外一段逻辑。但是AOP提供了另外一种思路,它使用的是横向操作,它的作用是在业务逻辑不知情(即业务逻辑不需要做任何的改动)的情况下对业务代码的功能进行增强,这种编程思想的使用场景有很多,例如事务提交、方法执行之前的权限检测、日志打印、方法调用事件等等

1.添加依赖
 

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-aop</artifactId>

</dependency>

2.切面类.

(1)指定切点

(2)这里的涉及的通知类型有:前置通知、后置最终通知、后置返回通知、后置异常通知、环绕通知,在切面类中添加通知

package com.fcc.web.aop;


import com.fcc.domain.annotation.MyInfoAnnotation;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

import org.springframework.context.annotation.Configuration;

import org.springframework.stereotype.Component;



//描述切面类

@Aspect

@Component

public class TestAop {


/*

* 定义一个切入点

*/

@Pointcut("@annotation(com.fcc.domain.annotation.MyInfoAnnotation)")

public void myInfoAnnotation() {

}



// 用@Pointcut来注解一个切入方法

@Pointcut("execution(* com.fcc.web.controller.*.**(..))")

public void excudeController() {

}


/*

* 通过连接点切入

*/

// @Before("execution(* findById*(..)) &&" + "args(id,..)")

// public void twiceAsOld1(Long id) {

// System.out.println("切面before执行了。。。。id==" + id);

//

// }



//@annotation 这个你应当知道指的是匹配注解

//括号中的 annotation 并不是指所有自定标签,而是指在你的注释实现类中 *Aspect 中对应注解对象的别名,所以别被俩 annotation 所迷惑。

@Around(value ="myInfoAnnotation()&&excudeController()&&@annotation(annotation)")

public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint,

MyInfoAnnotation annotation

) {

System.out.println(annotation.value());  

     thisJoinPoin.proceed();//环绕通知必须执行,否则不进入注解的方法

     return null;

}}

2.用以指定切点的注解

package com.fcc.domain.annotation;


import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.METHOD,ElementType.PARAMETER})

public @interface MyInfoAnnotation {

String value() default "";

}

3.测试类

@Controller

@RequestMapping("kkk")

public class BusinessController {



@MyInfoAnnotation(value = "FCC")

@RequestMapping("/test")

@ResponseBody

public String testAOP(){


return "sss";

}

}

控制台输出:FCC

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值