Springboot自定义注解(并捕捉异常)

本文介绍了如何在Springboot中定义一个自定义注解@RequiresLogin,用于标记需要登录才能访问的Controller方法。通过切面编程,实现了注解的功能,并自定义了异常类来捕获未登录的异常。此外,还提到了全局登录校验可通过创建拦截器类并继承HandlerInterceptor来实现,注册拦截器后即可生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义一个方法注解,要求登录才能访问

import java.lang.annotation.*;


@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresLogin {

}

在controller方法上加上注解 @RequiresLogin

import com.example.demo.annotation.RequiresLogin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RequiresLogin
    @GetMapping("/annotation")
    public String getLoginInfo() {
        System.out.println("Into method.");
        return "OK";
    }

使用切面,发挥注解作用

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.re
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值