注解的妙用

2024-06-02 15:36
文章标签 注解 妙用

本文主要是介绍注解的妙用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、注解是什么?

在Java中,注解(Annotation)是一种用于在代码中插入元数据的方式。注解不直接影响程序代码的行为,而是提供了一种形式化的方法来说明代码的某些方面,供编译器、开发工具或运行时环境等使用。简单来说,注解是用来提供信息给编译器和JVM(Java虚拟机)的标签,这些信息可以被编译器、开发工具、框架等在编译时或运行时读取并处理。

Java注解有以下几个关键特性:

元注解:用来定义注解的注解,如@Retention, @Target, @Documented, @Inherited等。例如,@Retention(RetentionPolicy.RUNTIME)指定了这个注解在运行时仍然有效,因此可以通过反射机制读取。

目标:注解可以应用在类、方法、构造函数、字段、局部变量声明、包或参数等元素上。@Target元注解指定了一个注解可以被应用于哪些程序元素。

保留策略:通过@Retention元注解指定,决定了注解的生命周期。
有三种保留策略:

  • SOURCE:注解只保留在源码中,编译时会被忽略。
  • CLASS:注解保留在编译后的字节码文件中,但运行时不会被JVM保留。
  • RUNTIME:注解不仅保留在源码和字节码中,JVM在运行时也能访问到,这使得我们可以在程序运行时通过反射读取注解信息。
    默认值:注解的成员可以有默认值,如果在使用注解时没有为成员赋值,则使用默认值。

自定义注解:用户可以定义自己的注解类型,通过@interface关键字进行定义,类似于定义接口。

注解的常见用途包括但不限于:

编译检查:如@Override确保子类正确重写了父类方法。
自动生成文档:如Javadoc使用的@param, @return, @throws等。
测试框架:JUnit的@Test标注测试方法。
配置框架:Spring框架中的@Component, @Service, @Autowired等用于依赖注入和管理Bean。
其他工具处理:如Lombok的@Data自动生成getter/setter等。

二、注解的原理

注解的生效是一个从定义到最终在编译或运行时被识别并采取相应行动的过程,它依赖于注解的保留策略、读取方式以及具体的应用逻辑。

Java注解的生效原理涉及几个核心环节:定义、编译、存储、读取与处理。

以下是注解生效的具体步骤:

1、定义:注解通过@interface关键字定义,类似于接口,其中可以包含方法声明,这些方法实际上定义了注解的属性(也称为成员变量)。方法没有方法体,其返回类型定义了属性的类型。

2、编译时处理:

  • 编译器识别:编译器会检查注解的使用是否合法,比如是否按照@Target指定的目标使用,同时也会处理一些编译时生效的注解,如@Override、@Deprecated等。
  • 注解处理器:除了标准处理外,还可以通过自定义注解处理器(Annotation Processor)在编译期间读取并处理注解,生成额外的源代码、编译时警告或错误,甚至修改现有类。

3、存储:
根据@Retention元注解的设置,决定注解信息如何存储。

  • SOURCE:仅在源码中,编译后丢失。
  • CLASS:编译进.class文件,但JVM运行时不保留。
  • RUNTIME:存储在.class文件中,并能在运行时通过反射访问。

4、运行时读取与处理:

  • 反射:对于RUNTIME保留的注解,程序可以通过反射API(如Class.getAnnotation(), Method.getAnnotations()等)在运行时读取注解信息。
  • 注解处理器/框架:如Spring框架会扫描带有特定注解(如@Component, @Service)的类,并根据这些注解配置应用程序上下文,实现依赖注入等功能。
  • 动态代理:对于需要动态处理注解的场景,可能会利用Java的动态代理机制,如通过java.lang.reflect.Proxy或第三方库如CGLIB,创建代理对象并在调用方法前后处理注解逻辑。

5、 实际应用:一旦注解被读取,应用(框架、库或自定义逻辑)会根据注解内容做出相应处理,比如初始化组件、执行验证逻辑、改变执行流程等。

三、注解的一般用法

定义一个注解

定义一个非常简单的,打印方法传参的注解

@Target(ElementType.METHOD) // 作用在方法上
@Retention(RetentionPolicy.RUNTIME)  // 运行时可见(默认编译时可见)
public @interface Introduce {String name() default "";int age() default 0;String address() default "";
}

定义注解处理器

通过反射获取对应注解并解析其中的参数信息。

public class IntroduceHandler {public void handle() {Class<Person> myClass = Person.class;Method[] declaredMethods = myClass.getDeclaredMethods();for (Method method : declaredMethods) {if (method.isAnnotationPresent(Introduce.class)) {Introduce introduce = method.getAnnotation(Introduce.class);String name = introduce.name();int age = introduce.age();String address = introduce.address();System.out.println("name:" + name + ",age:" + age + ",address:" + address);}}}}

使用注解

public class Person {public static void main(String[] args) {new IntroduceHandler().handle();new Person().sayHello("xiaoming");}@Introduce(name = "Tan", age = 18, address = "shanghai")public void sayHello(String name) {System.out.println("Hello " + name);}
}

如上所示,通过代码解析获取对应的注解解析器,当调用 sayHello方法时就可以获取对应参数的并解析出来。这种方式需要手动调用解析处理器,侵入性强。有没有好用的呢?那就是 Spring Aop提供的注解了,框架内自动完成注解解析动作。

注解的高级用法(分布式锁)

目标:在springboot中使用注解完成分布式锁的定义和使用。

springboot前置依赖

基于 Springboot - 2.7.14版本,Java8 环境,基于 redisson框架

  1. 引入核心依赖
 		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.21.0</version></dependency>
  1. redis 参数配置
server:port: 8080
#logging:
#  level:
#    root: debug
spring:redis:# redisson配置redisson:# 如果该值为false,系统将不会创建RedissionClient的bean。enabled: true# mode的可用值为,single/cluster/sentinel/master-slavemode: single# single: 单机模式#   address: redis://localhost:6379# cluster: 集群模式#   每个节点逗号分隔,同时每个节点前必须以redis://开头。#   address: redis://localhost:6379,redis://localhost:6378,...# sentinel:#   每个节点逗号分隔,同时每个节点前必须以redis://开头。#   address: redis://localhost:6379,redis://localhost:6378,...# master-slave:#   每个节点逗号分隔,第一个为主节点,其余为从节点。同时每个节点前必须以redis://开头。#   address: redis://localhost:6379,redis://localhost:6378,...address: redis://127.0.0.1:6379# redis 密码,空可以不填。password:database: 0
  1. redis configuration bean配置
package com.tan.training.config;import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** Redisson配置类。*/
@Configuration
@ConditionalOnProperty(name = "spring.redis.redisson.enabled", havingValue = "true")
public class RedissonConfig {@Value("${spring.redis.redisson.mode}")private String mode;/*** 仅仅用于sentinel模式。*/@Value("${spring.redis.redisson.masterName:}")private String masterName;@Value("${spring.redis.redisson.address}")private String address;@Value("${spring.redis.redisson.password:}")private String password;/*** 数据库默认0*/@Value("${spring.redis.redisson.database:0}")private Integer database;@Beanpublic RedissonClient redissonClient() {if (StringUtils.isBlank(password)) {password = null;}Config config = new Config();if ("single".equals(mode)) {config.useSingleServer().setDatabase(database).setPassword(password).setAddress(address);} else if ("cluster".equals(mode)) {String[] clusterAddresses = address.split(",");config.useClusterServers()//集群模式不支持多个数据库概念,默认db 0.setPassword(password).addNodeAddress(clusterAddresses);} else if ("sentinel".equals(mode)) {String[] sentinelAddresses = address.split(",");config.useSentinelServers().setDatabase(database).setPassword(password).setMasterName(masterName).addSentinelAddress(sentinelAddresses);} else if ("master-slave".equals(mode)) {String[] masterSlaveAddresses = address.split(",");if (masterSlaveAddresses.length == 1) {throw new IllegalArgumentException("redis.redisson.address MUST have multiple redis addresses for master-slave mode.");}String[] slaveAddresses = new String[masterSlaveAddresses.length - 1];System.arraycopy(masterSlaveAddresses, 1, slaveAddresses, 0, slaveAddresses.length);config.useMasterSlaveServers().setDatabase(database).setPassword(password).setMasterAddress(masterSlaveAddresses[0]).addSlaveAddress(slaveAddresses);} else {throw new IllegalArgumentException(mode);}return Redisson.create(config);}
}

定义注解

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;@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DistributeLock {int THIRTY_SECOND = 30000;int ONE_MINUTE = 60000;int TEN_MINUTE = 600000;String id();int milliSeconds() default 60000;boolean forceUnlock() default false;
}

定义注解AOP 处理器

@Aspect
@Component
@Lazy(false)
public class DistributeLockAspect {private static final Logger log = LoggerFactory.getLogger(DistributeLockAspect.class);@Autowiredprivate RedissonClient redisson;public DistributeLockAspect() {}@PostConstructpublic void init() {log.info("DistributeLockAspect start!");}@Around("@annotation(com.tan.training.aop.DistributeLock)")public void doHandler(ProceedingJoinPoint pjp) throws Throwable {MethodSignature signature = (MethodSignature)pjp.getSignature();Method method = signature.getMethod();DistributeLock lockAnno = (DistributeLock)method.getAnnotation(DistributeLock.class);if (lockAnno == null) {throw new IllegalAccessException("no @DistributeScheduleLock");} else {String methodFullNameWithId = method.getDeclaringClass().getName() + "." + method.getName() + ":" + lockAnno.id();String lockName = "rLock:" + methodFullNameWithId;synchronized(this) {RLock lock = this.redisson.getLock(lockName);if (lock.isLocked()) {log.debug("{} not obtained the lock at {}", methodFullNameWithId, System.currentTimeMillis());} else {// 确保在异常情况下也能正确地处理锁的释放boolean releaseLockFlag = false;try {releaseLockFlag = true;long b = System.currentTimeMillis();boolean flag = lock.tryLock(10L, (long)lockAnno.milliSeconds(), TimeUnit.MILLISECONDS);log.debug("{} tryLock flag: {}, cost {} ms", new Object[]{methodFullNameWithId, flag, System.currentTimeMillis() - b});if (flag) {long beginTime = System.currentTimeMillis();log.debug("{} obtained the lock at {}", methodFullNameWithId, beginTime);pjp.proceed();log.debug("{} execution cost {} ms", methodFullNameWithId, System.currentTimeMillis() - beginTime);releaseLockFlag = false;} else {releaseLockFlag = false;}} finally {if (releaseLockFlag) {boolean var15 = lockAnno.forceUnlock();if (var15) {lock.unlock();log.debug("{} force to release the lock at {}", methodFullNameWithId, System.currentTimeMillis());}}}boolean forceUnlock = lockAnno.forceUnlock();if (forceUnlock) {lock.unlock();log.debug("{} force to release the lock at {}", methodFullNameWithId, System.currentTimeMillis());}}}}}
}

定时获取锁测试

@Component
public class TaskJob {@Scheduled(cron = "0/5 * * * * ?")// 等待锁过期释放@DistributeLock(id = "changeState", milliSeconds = 10 * 1000,forceUnlock = true)// 使用完,强制释放锁//@DistributeLock(id = "changeState", milliSeconds = 10 * 1000,forceUnlock = true)public void changeStatus() {System.out.println("changeStatus start ....");}
}

如下:非强制释放锁的情况下,锁过期依赖于时间到期。
在这里插入图片描述

总结

注解是一种丰富代码的元数据形式,可以用于标记和控制代码行为。合理使用注解可以提高代码的可读性、可维护性和可测试性。同时,使用注解的过程中需要注意保持注解的简洁、明确和易于理解,避免过度使用注解导致代码臃肿和复杂。本文展示了两种场景下的注解使用小案例,方便大家在定义的时候直接取用,同时也方便加深理解。

这篇关于注解的妙用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1024377

相关文章

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

Spring排序机制之接口与注解的使用方法

《Spring排序机制之接口与注解的使用方法》本文介绍了Spring中多种排序机制,包括Ordered接口、PriorityOrdered接口、@Order注解和@Priority注解,提供了详细示例... 目录一、Spring 排序的需求场景二、Spring 中的排序机制1、Ordered 接口2、Pri

Idea实现接口的方法上无法添加@Override注解的解决方案

《Idea实现接口的方法上无法添加@Override注解的解决方案》文章介绍了在IDEA中实现接口方法时无法添加@Override注解的问题及其解决方法,主要步骤包括更改项目结构中的Languagel... 目录Idea实现接China编程口的方法上无法添加@javascriptOverride注解错误原因解决方

Java中基于注解的代码生成工具MapStruct映射使用详解

《Java中基于注解的代码生成工具MapStruct映射使用详解》MapStruct作为一个基于注解的代码生成工具,为我们提供了一种更加优雅、高效的解决方案,本文主要为大家介绍了它的具体使用,感兴趣... 目录介绍优缺点优点缺点核心注解及详细使用语法说明@Mapper@Mapping@Mappings@Co

Java中注解与元数据示例详解

《Java中注解与元数据示例详解》Java注解和元数据是编程中重要的概念,用于描述程序元素的属性和用途,:本文主要介绍Java中注解与元数据的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参... 目录一、引言二、元数据的概念2.1 定义2.2 作用三、Java 注解的基础3.1 注解的定义3.2 内

一文带你理解Python中import机制与importlib的妙用

《一文带你理解Python中import机制与importlib的妙用》在Python编程的世界里,import语句是开发者最常用的工具之一,它就像一把钥匙,打开了通往各种功能和库的大门,下面就跟随小... 目录一、python import机制概述1.1 import语句的基本用法1.2 模块缓存机制1.

SpringBoot使用注解集成Redis缓存的示例代码

《SpringBoot使用注解集成Redis缓存的示例代码》:本文主要介绍在SpringBoot中使用注解集成Redis缓存的步骤,包括添加依赖、创建相关配置类、需要缓存数据的类(Tes... 目录一、创建 Caching 配置类二、创建需要缓存数据的类三、测试方法Spring Boot 熟悉后,集成一个外

使用@Slf4j注解,log.info()无法使用问题

《使用@Slf4j注解,log.info()无法使用问题》在使用Lombok的@Slf4j注解打印日志时遇到问题,通过降低Lombok版本(从1.18.x降至1.16.10)解决了问题... 目录@Slf4androidj注解,log.info()无法使用问题最后解决总结@Slf4j注解,log.info(

poj 3050 dfs + set的妙用

题意: 给一个5x5的矩阵,求由多少个由连续6个元素组成的不一样的字符的个数。 解析: dfs + set去重搞定。 代码: #include <iostream>#include <cstdio>#include <set>#include <cstdlib>#include <algorithm>#include <cstring>#include <cm

spring—使用注解配置Bean

从Spring2.5开始,出现了注解装配JavaBean的新方式。注解可以减少代码的开发量,spring提供了丰富的注解功能,现在项目中注解的方式使用的也越来越多了。   ** 开启注解扫描          Spring容器默认是禁用注解配置的。打开注解扫描的方式主要有两种: <context:component-scan>组件扫描和<context:annotation