Spring切面中实现自定义注解

1.首先写出一个自定义注解。

package com.salong.aspect.test;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Login {
    String username() default "";
    String password() default "";
}

上面我们写了一个Login的注解,其中包含了username和password两个基本属性,如何写注解这里不详述,不清楚的可以先去补习。

2.自定义一个调用类,代码如下:

package com.salong.aspect.test;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/aspect")
public class index {

    @RequestMapping("/hello")
    @Login(username = "小明1",password = "123")
    public void hello(){
        System.out.println("hello world");
    }

    @RequestMapping("/hello2")
    @Login(username = "小明2",password = "456")
    public void hello2(){
        System.out.println("hello world2");
    }
}

在这里我们写了两个接口,分别是/aspect/hello和/aspect/hello2,都用了Login这个注解,但是注解的内容不一样,一个是小明1,密码123,一个是小明2,密码456.

3.制作注解切面,代码如下:

package com.salong.aspect.test;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class AspectDemo {
    
    //切入点为使用了Login注解的任何地方
    @Pointcut("@annotation(com.salong.aspect.test.Login)")
    public void logPointCut() {

    }

    @Before(value = "logPointCut()")
    public void check(){

        System.out.println("check");
    }


    @After(value = "logPointCut()")
    public void bye(){


        System.out.println("bye");
    }



    @Around("logPointCut() && @annotation(login)")
    public Object around(ProceedingJoinPoint joinPoint, Login login){

        System.out.println("around");
        //输出使用login注解时候的username属性值
        System.out.println(login.username());
        //输出使用login注解时候的passwo属性值
        System.out.println(login.password());
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }
}

这样,所有的类就写好了,运行项目,打开浏览器。分别测试一下hello和hello2这两个接口,输入:

http://localhost:8080/aspect/hellohttp://localhost:8080/aspect/hello2,然后去看代码,可以看到注解中的配置已经被读取到了,而且在运行两个接口之前,切面也成功的切入进去了。这样就大功告成了。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

却诚Salong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值