springBoot自定义参数注解
前置条件:新建一个springboot项目
1.新建一个标记注解@Auth
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author wangfan
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Auth {
}
2.新建一个处理器继承HandlerMethodArgumentResolver
import com.example.anno.Auth;
import com.example.po.UserPO;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* @author wangfan
*/
@Component
public class UserParamResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
//判断方法参数是不是UserPO,判断参数是否带有Auth注解
return methodParameter.getParameterType().isAssignableFrom(UserPO.class) && methodParameter.hasParameterAnnotation(Auth.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
//模拟从Redis/security/session里获取信息
UserPO user = new UserPO();
user.setId(1L);
user.setName("wangfan");
return user;
}
}
3.将处理器添加到Mvc
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.annotation.Resource;
import java.util.List;
/**
* @author wangfan
*/
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter{
@Resource
private UserParamResolver userParamResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(userParamResolver);
}
}
4.写个接口测试
import com.example.anno.Auth;
import com.example.po.UserPO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wangfan
*/
@RestController
public class TestController {
@GetMapping("/testAuth")
public UserPO testAuth(@Auth UserPO user){
return user;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY