spring boot 使用spring AOP实现拦截器
来源:互联网 发布:linux升级网卡驱动 编辑:程序博客网 时间:2024/06/05 18:29
在spring boot中,简单几步,使用spring AOP实现一个拦截器:1、引入依赖:- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
2、创建拦截器类(在该类中,定义了拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。):-
-
-
-
- @Aspect
- @Component
- public class ControllerInterceptor {
- private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
-
- @Value("${spring.profiles}")
- private String env;
-
-
-
-
- @Pointcut("execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
- public void controllerMethodPointcut(){}
-
-
-
-
-
-
- @Around("controllerMethodPointcut()")
- public Object Interceptor(ProceedingJoinPoint pjp){
- long beginTime = System.currentTimeMillis();
- MethodSignature signature = (MethodSignature) pjp.getSignature();
- Method method = signature.getMethod();
- String methodName = method.getName();
-
- Set<Object> allParams = new LinkedHashSet<>();
-
- logger.info("请求开始,方法:{}", methodName);
-
- Object result = null;
-
- Object[] args = pjp.getArgs();
- for(Object arg : args){
-
- if (arg instanceof Map<?, ?>) {
-
- @SuppressWarnings("unchecked")
- Map<String, Object> map = (Map<String, Object>) arg;
-
- allParams.add(map);
- }else if(arg instanceof HttpServletRequest){
- HttpServletRequest request = (HttpServletRequest) arg;
- if(isLoginRequired(method)){
- if(!isLogin(request)){
- result = new JsonResult(ResultCode.NOT_LOGIN, "该操作需要登录!去登录吗?\n\n(不知道登录账号?请联系老许。)", null);
- }
- }
-
-
- Map<String, String[]> paramMap = request.getParameterMap();
- if(paramMap!=null && paramMap.size()>0){
- allParams.add(paramMap);
- }
- }else if(arg instanceof HttpServletResponse){
-
- }else{
-
- }
- }
-
- try {
- if(result == null){
-
- result = pjp.proceed();
- }
- } catch (Throwable e) {
- logger.info("exception: ", e);
- result = new JsonResult(ResultCode.EXCEPTION, "发生异常:"+e.getMessage());
- }
-
- if(result instanceof JsonResult){
- long costMs = System.currentTimeMillis() - beginTime;
- logger.info("{}请求结束,耗时:{}ms", methodName, costMs);
- }
-
- return result;
- }
-
-
-
-
-
-
- private boolean isLoginRequired(Method method){
- if(!env.equals("prod")){
- return false;
- }
-
- boolean result = true;
- if(method.isAnnotationPresent(Permission.class)){
- result = method.getAnnotation(Permission.class).loginReqired();
- }
-
- return result;
- }
-
-
- private boolean isLogin(HttpServletRequest request) {
- return true;
-
-
-
-
-
-
- }
- }
3、测试
浏览器中输入:http://localhost:8082/api/admin/login
测试结果:
- 2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 请求开始,方法:login
- 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login请求结束,耗时:8ms
证明拦截器已经生效。源代码参考:https://github.com/xujijun/my-spring-boot