springboot自定义注解的过程

关于自定义注解的方法,以下是自己的看法,有问题欢迎指出,意在帮助自己日后查看,以下只写了实现过程,没有对其做解释和理解。

第一,引入需要的jar,pom配置

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

第二,编写注解接口

package com.example.springboottest1.annotations;

import java.lang.annotation.*;

/**
 * @author Administrator
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Permission {
    String value() default "";
}

第三,利用切面处理注解接口

package com.example.springboottest1.Aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PermissionAspect {
    public static final Logger logger = LoggerFactory.getLogger(PermissionAspect.class);
    
    //注解接口所在包的位置
    @Pointcut("@annotation(com.example.springboottest1.annotations.Permission)")
    public void annotationPointcut() {

    }

    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) {
        // 此处进入到方法前  可以实现一些业务逻辑
    }

    @Around("annotationPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        boolean hasToken = false;
        //这里可以写自己的一些判断方法,然后写一些具体的逻辑
        if (!hasToken){
            String mes = "The token parameter is not included in the requested parameter, the parameter is not valid.";
            logger.info(mes);
        }
        return joinPoint.proceed();
    }

    /**
     * 在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
     * @param joinPoint
     */
    @AfterReturning("annotationPointcut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        
    }
}

第四,测试注解是否生效,写个测试类试一下

package com.example.springboottest1.controller;

import com.example.springboottest1.annotations.Permission;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Administrator
 */
@RestController
public class HelloWord {
    @Permission
    @RequestMapping("/hello")
    public String getHello(){
        return "hello world";
    }
}

第五,启动项目验证注解是否生效,控制台能打印出那一行日志,代表着就生效了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值