Groovy 注解
注解
1.概念:注解是元数据的形式,其中它们提供关于不是程序本身的一部分的程序的数据。注释对它们注解的代码的操作没有直接影响。
2.作用范围
(1)编译器信息 -编译器可以使用注解来检测错误或抑制警告。
(2)编译时和部署时处理 -软件工具可以处理注解信息以生成代码,XML文件等。
(3)运行时处理 -一些注解可以在运行时检查。
3.定义注解
(1)@interface - at符号字符(@)向编译器指示以下是注解。
(2)特点:注解可以以没有主体的方法的形式和可选的默认值来定义成员。
(3)几种类型的注解:
字符串类型
@interface Simple {
String str1() default "HelloWorld";
}
枚举类型
enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun }
@interface Scheduled {
DayOfWeek dayOfWeek()
}
类类型
@interface Simple {}
@Simple
class User {
String username
int age
}
def user = new User(username: "Joe",age:1);
println(user.age);
println(user.username);
注释成员值
@interface Example {
int status()
}
@Example(status = 1)
关闭注解参数
Groovy中注解的一个很好的特性是,你也可以使用闭包作为注解值。因此,注解可以与各种各样的表达式一起使用。
@interface OnlyIf {
Class value()
}
@OnlyIf({ number<=6 })
void Version6() {
result << 'Number greater than 6'
}
@OnlyIf({ number>=6 })
void Version7() {
result << 'Number greater than 6'
}
元注解和组合注解
元注解:可以在注解类上进行的注解。
组合注解:当前注解类上有元注解。
参考:https://blog.csdn.net/flurr66/article/details/105133451
元注解定义:
@Service
@Transactional
@AnnotationCollector
@interface TransactionalService {
}
@TransactionalService
class MyTransactionalService {}