2021-12-09 注解类1

注解类


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

@Documented

@Retention(RetentionPolicy.RUNTIME)

public @interface SelfAnnotate {

boolean verify()default false;

}

@target type意思是这个注解可以作用在类上面 method 就是可以作用在方法上面

目前没有找到一个途径 写在类上面 然后里面的方法上不加注解也能被切到;

boolean verify()default false; 把它看成属性就行了

切面类


@Aspect

@Component

public class NameAspect {

@Pointcut("@annotation(com.***.config.annotate.SelfAnnotate)")

public void access() {

}

@Before("@annotation(selfAnnotate)")

public void doBefore(JoinPoint joinPoint,SelfAnnotate selfAnnotate)throws Throwable {

System.out.println(selfAnnotate.verify());

System.out.println("-aop 日志记录启动-" );

}

@Around("@annotation(selfAnnotate)")

public Object around(ProceedingJoinPoint pjp,SelfAnnotate selfAnnotate) {

System.out.println("-aop 日志环绕阶段-" );

if (selfAnnotate.verify()) {

try {

return pjp.proceed();

}catch (Throwable e) {

e.printStackTrace();

}

}

return "登录失败";

}

@After("@annotation(selfAnnotate)")

public void after(JoinPoint joinPoint,SelfAnnotate selfAnnotate) {

System.out.println("-aop 日志记录结束-" );

}

}

如果用@Before("@annotation(selfAnnotate)")这种方式 下面入参一定要写上注解这个类

为什么要多加一个参数:因为想把方法上注解配置的属性用在这里

比如我要进行一个权限校验,方法上注解里可以填上这个string 然后在切面开始的时候去进行验证

joinPoint中获得的都是和方法有关的信息

ProceedingJoinPoint 理解成是切面代理出来的对象

pgp.process()里面就是通过反射调用被代理的方法

around 会在before和after方法前面执行

@RestController
@RequestMapping("/annotate")
@SelfAnnotate(verify = true)
public class AnnotateTest {

    @GetMapping("lanjie")
    @SelfAnnotate(verify = true)
    public String goFrist(@RequestParam("name") String name, @RequestParam("age") Integer age) {
        System.out.println(name);
        System.out.println(age);
        return "登录成功";
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容