Java的注解在现实项目中运用得异常的多,迥殊是在运用了Spring以后。
本文会引见Java注解的语法,以及在Spring中运用注解的例子。注解的语法
注解的例子
以Junit中的@Test注解为例
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test { long timeout() default 0L; }
可以看到@Test
注解上有@Target()
和@Retention()
两个注解。
这类注解了注解的注解,称之为元注解。
跟声清楚明了数据的数据,称为元数据是一种意义。
以后的注解的花样是
修饰符 @interface 注解名 { 注解元素的声明1 注解元素的声明2 }
注解的元素声明有两种情势
type elementName(); type elementName() default value; // 带默许值
罕见的元注解
@Target
注解
@Target
注解用于限定注解能在哪些项上运用,没有加@Target
的注解可以运用于任何项上。
在java.lang.annotation.ElementType
类中可以看到一切@Target
吸收的项
TYPE
在【类、接口、注解】上运用FIELD
在【字段、罗列常量】上运用METHOD
在【要领】上运用PARAMETER
在【参数】上运用CONSTRUCTOR
在【组织器】上运用LOCAL_VARIABLE
在【局部变量】上运用ANNOTATION_TYPE
在【注解】上运用PACKAGE
在【包】上运用TYPE_PARAMETER
在【范例参数】上运用 Java 1.8 引入TYPE_USE
在【任何声明范例的处所】上运用 Java 1.8 引入
@Test
注解只允许在要领上运用。
@Target(ElementType.METHOD) public @interface Test { ... }
假如要支撑多项,则传入多个值。
@Target({ElementType.TYPE, ElementType.METHOD}) public @interface MyAnnotation { ... }
另外元注解也是注解,也相符注解的语法,如@Target
注解。@Target(ElementType.ANNOTATION_TYPE)
表明@Target
注解只能运用在注解上。
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { ElementType[] value(); }
@Retention
注解
@Retention
指定注解应当保存多长时间,默许是RetentionPolicy.CLASS
。
在java.lang.annotation.RetentionPolicy
可看到一切的项
SOURCE
不包含在类文件中CLASS
包含在类文件中,不载入虚拟机RUNTIME
包含在类文件中,由虚拟机载入,可以用反射API猎取
@Test
注解会载入到虚拟机,可以经由过程代码猎取
@Retention(RetentionPolicy.RUNTIME) public @interface Test { ... }
@Documented
注解
重要用于归档东西辨认。被注解的元素能被Javadoc
或相似的东西文档化。
@Inherited
注解
添加了@Inherited
注解的注解,所注解的类的子类也将具有这个注解
注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface MyAnnotation { ... }
父类
@MyAnnotation class Parent { ... }
子类Child
会把加在Parent
上的@MyAnnotation
继续下来
class Child extends Parent { ... }
@Repeatable
注解
Java 1.8 引入的注解,标识注解是可重复运用的。
注解1
public @interface MyAnnotations { MyAnnotation[] value(); }
注解2
@Repeatable(MyAnnotations.class) public @interface MyAnnotation { int value(); }
有运用@Repeatable()
时的运用
@MyAnnotation(1) @MyAnnotation(2) @MyAnnotation(3) public class MyTest { ... }
没运用@Repeatable()
时的运用,@MyAnnotation
去掉@Repeatable
元注解
@MyAnnotations({ @MyAnnotation(1), @MyAnnotation(2), @MyAnnotation(3)}) public class MyTest { ... }
这个注解照样异常有效的,让我们的代码变得简约不少,Spring
的@ComponentScan
注解也用到这个元注解。
元素的范例
支撑的元素范例
8种基础数据范例(
byte
,short
,char
,int
,long
,float
,double
,boolean
)String
Class
enum
注解范例
数组(一切上边范例的数组)
例子
罗列类
public enum Status { GOOD, BAD }
注解1
@Target(ElementType.ANNOTATION_TYPE) public @interface MyAnnotation1 { int val(); }
注解2
@Target(ElementType.TYPE) public @interface MyAnnotation2 { boolean boo() default false; Class<?> cla() default Void.class; Status enu() default Status.GOOD; MyAnnotation1 anno() default @MyAnnotation1(val = 1); String[] arr(); }
运用时,无默许值的元素必需传值
@MyAnnotation2( cla = String.class, enu = Status.BAD, anno = @MyAnnotation1(val = 2), arr = {"a", "b"}) public class MyTest { ... }
Java
内置的注解
@Override
注解
通知编译器这个是个掩盖父类的要领。假如父类删除了该要领,则子类会报错。
@Deprecated
注解
示意被注解的元素已被弃用。
@SuppressWarnings
注解
通知编译器疏忽正告。
@FunctionalInterface
注解
Java 1.8 引入的注解。该解释会强迫编译器javac
搜检一个接口是不是相符函数接口的规范。
迥殊的注解
有两种比较迥殊的注解
标记注解 : 注解中没有任何元素,运用时直接是
@XxxAnnotation
, 不须要加括号单值注解 : 注解只要一个元素,且名字为
value
,运用时直接传值,不须要指定元素名@XxxAnnotation(100)
应用反射猎取注解
Java
的AnnotatedElement
接口中有getAnnotation()
等猎取注解的要领。
而Method
,Field
,Class
,Package
等类均完成了这个接口,因而均有猎取注解的才能。
例子
注解
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) public @interface MyAnno { String value(); }
被注解的元素
@MyAnno("class") public class MyClass { @MyAnno("feild") private String str; @MyAnno("method") public void method() { } }
猎取注解
public class Test { public static void main(String[] args) throws Exception { MyClass obj = new MyClass(); Class<?> clazz = obj.getClass(); // 猎取对象上的注解 MyAnno anno = clazz.getAnnotation(MyAnno.class); System.out.println(anno.value()); // 猎取属性上的注解 Field field = clazz.getDeclaredField("str"); anno = field.getAnnotation(MyAnno.class); System.out.println(anno.value()); // 猎取要领上的注解 Method method = clazz.getMethod("method"); anno = method.getAnnotation(MyAnno.class); System.out.println(anno.value()); } }
在Spring
中运用自定义注解
注解自身不会有任何的作用,须要有其他代码或东西的支撑才有效。
需求
想象现有如许的需求,顺序须要吸收差别的敕令CMD
,
然后依据敕令挪用差别的处置惩罚类Handler
。
很轻易就会想到用Map
来存储敕令和处置惩罚类的映照关联。
因为项目多是多个成员共同开辟,差别成员完成各自担任的敕令的处置惩罚逻辑。
因而愿望开辟成员只关注Handler
的完成,不须要主动去Map
中注册CMD
和Handler
的映照。
终究结果
终究愿望看到结果是如许的
@CmdMapping(Cmd.LOGIN) public class LoginHandler implements ICmdHandler { @Override public void handle() { System.out.println("handle login request"); } } @CmdMapping(Cmd.LOGOUT) public class LogoutHandler implements ICmdHandler { @Override public void handle() { System.out.println("handle logout request"); } }
开辟人员增添本身的Handler
,只须要建立新的类并注上@CmdMapping(Cmd.Xxx)
即可。
细致做法
细致的完成是运用Spring
和一个自定义的注解
定义@CmdMapping
注解
@Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Component public @interface CmdMapping { int value(); }
@CmdMapping
中有一个int
范例的元素value
,用于指定CMD
。这里做成一个单值注解。
这里还加了Spring
的@Component
注解,因而注解了@CmdMapping
的类也会被Spring建立实例。
然后是CMD
接口,存储敕令。
public interface Cmd { int REGISTER = 1; int LOGIN = 2; int LOGOUT = 3; }
以后是处置惩罚类接口,现实情况接口会庞杂很多,这里简化了。
public interface ICmdHandler { void handle(); }
上边说过,注解自身是不起作用的,须要其他的支撑。下边就是让注解见效的部分了。
运用时挪用handle()
要领即可。
@Component public class HandlerDispatcherServlet implements InitializingBean, ApplicationContextAware { private ApplicationContext context; private Map<Integer, ICmdHandler> handlers = new HashMap<>(); public void handle(int cmd) { handlers.get(cmd).handle(); } public void afterPropertiesSet() { String[] beanNames = this.context.getBeanNamesForType(Object.class); for (String beanName : beanNames) { if (ScopedProxyUtils.isScopedTarget(beanName)) { continue; } Class<?> beanType = this.context.getType(beanName); if (beanType != null) { CmdMapping annotation = AnnotatedElementUtils.findMergedAnnotation( beanType, CmdMapping.class); if(annotation != null) { handlers.put(annotation.value(), (ICmdHandler) context.getBean(beanType)); } } } } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } }
重要事情都是Spring
做,这里只是将实例化后的对象put
到Map
中。
测试代码
@ComponentScan("pers.custom.annotation") public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Main.class); HandlerDispatcherServlet servlet = context.getBean(HandlerDispatcherServlet.class); servlet.handle(Cmd.REGISTER); servlet.handle(Cmd.LOGIN); servlet.handle(Cmd.LOGOUT); context.close(); } }
> 完全项目
总结
可以看到运用注解可以写出很天真的代码,注解也迥殊合适做为运用框架的一种体式格局。
所以学会运用注解照样很有效的,毕竟这关于上手框架或完成本身的框架都是异常重要的学问。
以上就是Java注解的定义及运用引见(代码示例)的细致内容,更多请关注ki4网别的相干文章!