当前位置:网站首页>Spirng之注解使用
Spirng之注解使用
2022-07-21 15:33:00 【InfoQ】
一、注解基础知识点
二、元注解
- METHOD:用于描述方法
- PACKAGE:用于描述包
- PARAMETER:用于描述方法变量
- TYPE:用于描述类、接口或enum类
- SOURCE:在源文件中有效,编译过程中会被忽略
- CLASS:随源文件一起编译在class文件中,运行时忽略
- RUNTIME:在运行时有效
三、自定义注解使用
1、定义注解
//颜色注解
@Target ({ElementType.FIELD,ElementType.METHOD})// 表明该注解可以标注到,属性、方法上
@Retention (RetentionPolicy.RUNTIME)// 表明该注解会保留到运行时
@Inherited //表示该注解可以被继承
@Documented //表明该注解会被生成到javadoc中
public @interface ColorAnnotation {
enum COLOR{RED,GREEN}
String value() default " xx color";
COLOR color() default COLOR.RED;
}
//用来备注的注解
@Target ({ElementType.METHOD,ElementType.FIELD})
@Retention (RetentionPolicy.RUNTIME)
public @interface Description {
String value() default "";
}
@Target ({ElementType.TYPE,ElementType.METHOD})
@Retention (RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
String value() default "ff";
}
2、注解的使用
/**
* @Description: Box
* @Author: 青衣醉
* @Date: 2022/7/20 4:48 下午
*/
@Data
@AllArgsConstructor
public class Box {
@ColorAnnotation(value = "绿色",color = ColorAnnotation.COLOR.GREEN)
String name;
@Description("高")
Integer high;
@Description("宽")
Integer width;
@Description("礼盒")
String desc;
}
3、注解的读取
/**
* @Description: AnnotationController
* @Author: 青衣醉
* @Date: 2022/7/20 2:07 下午
*/
@RestController
@RequestMapping
public class AnnotationController {
@SneakyThrows
@Test
@MyAnnotation("我的盒子是一个")
public void test(){
Box box = new Box ("苹果",10,20,null);
Class<Box> boxClass = (Class<Box>) box.getClass ();
//获取方法上的注解
MyAnnotation test = this.getClass ().getMethod ("test").getAnnotation (MyAnnotation.class);
//获取属性上的注解
ColorAnnotation colorField = boxClass.getDeclaredField ("name").getAnnotation (ColorAnnotation.class);
//获取属性上的注解
Map<String, Description> fieldMap = this.getFieldMapAnnotatedWith (boxClass, Description.class);
StringBuilder sp = new StringBuilder (test.value ());
String s = sp.append (fieldMap.get ("high").value ())
.append (box.getHigh ())
.append (",")
.append (fieldMap.get ("width").value ())
.append (",")
.append (box.getWidth ())
.append (",")
.append (colorField.value ())
.append (box.getName ())
.append (fieldMap.get ("desc").value ()).toString ();
System.out.println (s);
}
/**
*获取class对象中使用了annotation注解的所有属性集合
*返回 key为属性名,value为注解对象的map集合
*/
private <T extends Annotation >Map<String,T> getFieldMapAnnotatedWith(Class<? extends Object> object, Class<T> annotation) {
if (Object.class.equals (object)) {
return Collections.emptyMap ();
}
Field[] declaredFields = object.getDeclaredFields ();
return Arrays.stream (declaredFields)
.filter (field -> field.getAnnotation (annotation) != null)
.collect (Collectors.toMap (field -> field.getName (), field -> field.getAnnotation (annotation)));
}
/**
*获取class对象中使用了annotation注解的所有属性对象集合
*/
private <T extends Annotation >Set<Field> getFieldAnnotatedWith(Class<? extends Object> object, Class<T> annotation) {
if (Object.class.equals (object)) {
return Collections.emptySet ();
}
Field[] declaredFields = object.getDeclaredFields ();
return Arrays.stream (declaredFields)
.filter (field -> field.getAnnotation (annotation) != null)
.collect (Collectors.toSet ());
}
}

边栏推荐
猜你喜欢
Airtest stepped on the pit -- start flash back
[email protected]"/>
ZBar项目简介及安装配置 | [email protected]
关于mysql驱动版本报错解决,Cause: com.mysql.jdbc.exceptions.jdbc4、Unknown system variable ‘query_cache_size
Matlab GUI programming skills (IX): explain the uitable function display table and related operations in detail (create table user interface)
关于sql数据查询的语句
Matlab GUI编程技巧(七):matlablistbox操作-列表框(ListBox)和uilistbox常用操作
124二叉树中的最大路径和
80.26亿元!国家互联网信息办公室对滴滴依法作出网络安全审查相关行政处罚
31下一个排列
Nonparametric test
随机推荐
怎么实现无缝轮播图?用原生js写一遍
C语言中以static说明符开头的变量和函数具有的性质
主机psql连接虚拟机Oracle
线性表的实现
ECCV 2022 | fix the performance damage of large targets caused by FPN: you should look at all objects
VLOOKUP函数
Cookie与Session
缓存穿透、雪崩、一致性问题
124二叉树中的最大路径和
索引
Codeforces Round #690 (Div. 3) C. Unique Number 常规解法
mysql8中timestamp时间戳设置默认值 CURRENT_TIMESTAMP ,Error:1048 - Column ‘createTime‘ cannot be null
Steps for installing and using redis [Linux and windows environment]
英特尔计划出售基带芯片业务,但苹果已放弃?
闻泰科技一季度营收同比猛增184.6%,净利润暴涨256.21%!
Awvs installation and problem solving
Common commands for starting services
How to add a map to a page
Is there any age limit for opening an account? Excuse me, is it safe to open a stock account by mobile phone?
IDEA SSH 工具远程链接失败