Java 自定义注解

一、Java 自定义注解的用途、

   1、可以记录在特殊方法进行日志记录

         2、可以进行 特殊鉴权 如 @ValidateRole(“admin") 只有当前用户拥有指定角色时才放行 否则抛自定义异常 无权限

        3、可以用于参数 如 Controller 方法中的参数进行 参数格式验证

 

二、自定义注解记录需要重试的请求数据到数据库

   2.1 pom 节点引入    

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

启动需要加 @EnableAspectJAutoProxy

@SpringBootApplication
@EnableAspectJAutoProxy
@ComponentScan("com.lyb.*")
public class OpenDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(OpenDemoApplication.class, args);
    }
}

 

 

 2.2  自定义注解名称 

复制代码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RecordRetryMessage {


    /**
     * 保存重试消息类型
     * @return
     */
    int messageType() default 1;
}
复制代码

2.3 依赖切面 aspect 实现 自定义注解 

复制代码
@Aspect
@Component
public class RetryMessageAspect {

    @Autowired
    UserInfoService userInfoService;

    @Pointcut("@annotation(com.lyb.web.annotation.RecordRetryMessage)")
    public void retryMessage() {

    }

    @Around("retryMessage()")
    public  Objectaround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] objects = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RecordRetryMessage myLog = signature.getMethod().getAnnotation(RecordRetryMessage.class);
        System.out.println("注解上的参数值:" + myLog.messageType());
        System.out.println("userInfoService.testC() = " + userInfoService.testC());
        objects[1] = "修改后的参数值";


// 如果需要返回值需要
return
joinPoint.proceed(objects);


} }
复制代码

2.4 使用自定义注解 

    @RecordRetryMessage(messageType = 1)
    public  void  testB(String l,String l1) {
        System.out.println("testB(); = ");
    }

 

 

      

 

posted @   xiaoBai1001  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示