自定义注解

简介: 本文介绍如何在Spring框架中实现自定义注解,结合AOP与过滤器应用于日志记录、权限控制等场景。通过定义注解、配置切面与拦截逻辑,展示从基础使用到登录鉴权的完整流程,帮助开发者提升代码可读性与复用性。(238字)

1.前言

自定义注解目前在我使用过的项目中,主要用用作日志丰富,参数处理,其核心还是借助于Spring的AOP进行实现,本文将结合具体代码演示简单的自定义注解实现流程。

2.实现

2.1 定义User

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;
}

2.2 定义UserDAO

@Component
public class UserDao {
    public User findUserById(Integer id) {
        if(id > 10) {
            return null;
        }
        return new User(id, "user-" + id);
    }
}

2.3 定义UserService

@Service
public class UserService {
    private final UserDao userDao;
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }
    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }
}

2.4 定义Controller

@RequestMapping(value = "user/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public User findUser(@PathVariable("id") Integer id) {
    return userService.findUserById(id);
}

此时浏览器访问:http://{domain}/user/1即可出现对应效果

{
    "id": 1,
    "name": "user-1"
}

2.5 定义自定义注解

import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
    String name() default "";
    String value() default "";
}

说明:

  • @interface 不是interface,是注解类  定义注解
  • Documented
  • 这个Annotation可以被写入javadoc  
  • @Retention
  • 修饰注解,是注解的注解,称为元注解
  • SOURCE,     // 编译器处理完Annotation后不存储在class中  
  • CLASS,       // 编译器把Annotation存储在class中,这是默认值  
  • RUNTIME  // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要
  • @Target
  • 注解的作用目标
  • @Target(ElementType.TYPE)                                           //接口、类、枚举、注解
  • @Target(ElementType.FIELD)                                         //字段、枚举的常量
  • @Target(ElementType.METHOD)                                   //方法
  • @Target(ElementType.PARAMETER)                              //方法参数
  • @Target(ElementType.CONSTRUCTOR)                        //构造函数
  • @Target(ElementType.LOCAL_VARIABLE)                     //局部变量
  • @Target(ElementType.ANNOTATION_TYPE)                //注解
  • @Target(ElementType.PACKAGE)                                 //包    


  • 可以定义多个方法,每个方法在使用时参照下面的Controller使用即可,实际就是类似于@PostMapping这样的注解中使用过的value,method,produces等,如下:

2.6 AOP+Controller使用自定义注解

@CustomAnnotation(name = "findUser", value = "根据ID查找用户")
@RequestMapping(value = "user/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public User findUser(@PathVariable("id") Integer id) {
    return userService.findUserById(id);
}
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;
@Component
@Aspect
public class TestLogAspect {
    @Pointcut("@annotation(cn.test.CustomAnnotation)")
    private void pointcut() {}
    @Before("pointcut() && @annotation(annotation)")
    public void advice(JoinPoint joinPoint, CustomAnnotation annotation) {
        System.out.println(
            "类名:["
            + joinPoint.getSignature().getDeclaringType().getSimpleName()
            + "],方法名:[" + joinPoint.getSignature().getName()
            + "]-日志内容-[" + annotation.value() + ", "+annotation.name()+ "]");
    }
}

3.总结

自定义注解其核心是借助于:@Target 和 @Rentention,@Documented组合实现,其实现还是需要依赖于Spring的AOP进行具体体现,除了上面的用作日志拦截,还可以自定义:数据验证注解,权限注解,缓存注解等多种用途,但其实现基本都遵循上述步骤。

4.自定义注解+过滤器实现登陆相关

4.1 定义自定义注解@Login

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.zhicall.majordomo.core.common.enums.YesOrNo;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Login {
  YesOrNo value();
}

4.2 过滤器匹配

package com.zhicall.majordomo.core.security.interceptor;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSON;
import com.zhicall.care.realtime.util.ResultMessageBuilder;
import com.zhicall.care.realtime.util.ResultMessageBuilder.ResultMessage;
import com.zhicall.care.system.basic.BeanFactory;
import com.zhicall.majordomo.core.common.constant.GlobalCst;
import com.zhicall.majordomo.core.common.enums.YesOrNo;
import com.zhicall.majordomo.core.security.annotation.Login;
import com.zhicall.majordomo.core.security.constant.Cst;
import com.zhicall.majordomo.core.security.util.UserAuthHelper;
public class UserLoginInterceptor extends HandlerInterceptorAdapter {
  @SuppressWarnings({ "unchecked", "rawtypes" })
  protected RedisTemplate<String, String> redisTemplate = (RedisTemplate) BeanFactory.getInstance().getBean("redisTemplate");
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Login login = handlerMethod.getMethodAnnotation(Login.class);
    // 方法被 @Login(YesOrNo.No)标记 表示不需要登陆即可访问 否者都要登录
    if (login != null && YesOrNo.NO.equals(login.value())) {
      return true;
    }
    // 做鉴权
        ......
  }
}

4.3 Controller中具体使用

@Login(YesOrNo.NO)
@RequestMapping(value = "/filter", method = RequestMethod.POST)
public @ResponseBody ResultMessageBuilder.ResultMessage filter(String companyId, String code) {
    List<TabInfoVo> merchantsInfoDtos = new ArrayList<>();
    merchantsInfoDtos = historyTradeService.filter(companyId, code);
    return ok("查询成功", merchantsInfoDtos);
}
相关文章
|
缓存 监控 NoSQL
解析Redis缓存雪崩及应对策略
解析Redis缓存雪崩及应对策略
|
前端开发 JavaScript 数据可视化
最棒的 7 个 Laravel admin 后台管理系统推荐
Laravel 已经凭借自己的易用性及低门槛成为 github 上 stars 第一的 PHP 框架,本文将介绍我精心为大家挑选出来的 Laravel admin 后台管理系统,从抽象程度最低(灵活但代码量大)到抽象程度最高(代码量小但不灵活)来帮助大家选择合适自己的 Laravel admin 后台管理系统。
3639 0
|
2月前
|
负载均衡 应用服务中间件 Nacos
Nacos配置中心
本文详细讲解了Nacos作为配置中心的核心功能与实践应用,涵盖配置管理、热更新、共享配置及优先级规则,并通过搭建Nacos集群实现高可用部署,帮助开发者掌握微服务环境下配置的集中化管理方案。
 Nacos配置中心
|
2月前
|
SpringCloudAlibaba Java Nacos
SpringCloud概述
Spring Cloud是微服务架构的综合解决方案,由Spring团队推出,具备约定大于配置、组件丰富、开箱即用等特点。为解决Netflix组件停更问题,阿里推出Spring Cloud Alibaba,集成Nacos、Sentinel、Seata等高性能中间件,成为主流技术栈选择。
Flutter之运行提示Could not update files on device: Connection closed before full header was received
Flutter之运行提示Could not update files on device: Connection closed before full header was received
1013 0
|
Linux 调度
linux中进程与cpu核的绑定
linux中进程与cpu核的绑定
536 0
|
存储 前端开发 安全
上门服务家政系统开发技术规则
上门服务家政系统的开发涵盖市场调研、需求分析、功能规划、系统设计与开发实施等多个阶段。首先,通过调研明确市场需求与用户期望;其次,规划服务预约、支付、评价等功能;接着设计前端、后台及数据库;最后,进行系统开发、测试与优化,确保稳定可靠。
|
存储 运维 BI
云HIS综合管理系统源码,门诊预约挂号、收费结算、排班、医护协同、药房、药库、电子病历等功能模块
_HIS系统摘要:_ HIS是医院信息管理系统,涵盖门诊、住院、药房、药库管理等,支持财务、病人及物资信息处理。门诊医生工作站具备友好的交互,与多系统接口集成。功能包括医生就诊、查询、住院预约、数据设置及用户管理。云HIS采用SaaS模式,适合基层医疗机构,提供综合管理和业务支持,确保运营监管并易于扩展。系统展示包括业务首页、综合管理系统、费用统计和出院结算界面。
537 8
云HIS综合管理系统源码,门诊预约挂号、收费结算、排班、医护协同、药房、药库、电子病历等功能模块
|
XML JSON 安全
深度思考:总结SOA、WSDL、SOAP、REST、UDDI之间的关系
总结起来,SOA是面向服务的架构原则,WSDL用于描述这些服务的接口,SOAP和REST是实现这些服务通讯的两种不同方法,SOAP强调严格的规范和协议扩展性,而REST强调易用性和轻量级通信。最后,UDDI定义了服务发现的机制,虽然在现实中应用不广,但在理论上是链接消费者和服务提供者的要素。这些组件和协议互相支持,共同构成了实现和利用SOA的完整生态系统。
400 2
|
存储 图形学
【unity实战】Unity实现2D人物双击疾跑
【unity实战】Unity实现2D人物双击疾跑
320 0