SpringBoot通过注解实现AOP

SpringBoot通过注解实现AOP


新手上路,通过这种方式记录一下,有什么不到位的地方还请谅解!

1.引入依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

2.定义注解

@Target({ElementType.METHOD})  //可用在方法名上
@Retention(RetentionPolicy.RUNTIME)//运行时有效 
public @interface ListenFunction {
}

@Target、@Retention是java中的元注解,

元注解的作用就是负责注解其他注解。Java定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解有以下几种:
@Target @Retention @Documented @Inherited

3.定义切面

@Aspect
@Component
@Order(1)	//如果有多个 可以定义来控制顺序 数字越小执行顺序靠前
public class ListenFunctionAspect {


    @Pointcut("@annotation(com.example.shopping_demo.aspect.ListenFunction)")
    														//自定义注解的路径
    public void pointCut() {
    }
    
   @Before("pointCut()")
    public void doBefore(){
        System.out.println("方法之前运行");
    }

   @After("pointCut()")
    public void doAfter(){
        System.out.println("方法之后运行");
    }
}
    

@Aspect:使当前类成为切面类
@Order( ) :给当前切面标序,按照序号来执行多个切面
@Pointcut:定义切入点,这边是对注解切入,也可以对类切入,
如:@Pointcut (“execution(public * com.example.shopping_demo.controller..(…))”)

4.使用注解

@Service
public class test_Server {
    @ListenFunction
    public void testFunction(){
        System.out.println("我是方法");
    }
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值