Java
的注解在实际项目中使用得很是的多,特别是在使用了Spring
以后。
本文会介绍Java
注解的语法,以及在Spring
中使用注解的例子。
以Junit
中的@Test
注解为例java
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test { long timeout() default 0L; }
能够看到@Test
注解上有@Target()
和@Retention()
两个注解。
这种注解了注解的注解,称之为元注解。
跟声明了数据的数据,称为元数据是一种意思。git
以后的注解的格式是github
修饰符 @interface 注解名 { 注解元素的声明1 注解元素的声明2 }
注解的元素声明有两种形式spring
type elementName(); type elementName() default value; // 带默认值
@Target
注解@Target
注解用于限制注解能在哪些项上应用,没有加@Target
的注解能够应用于任何项上。数组
在java.lang.annotation.ElementType
类中能够看到全部@Target
接受的项app
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 { ... }
若是要支持多项,则传入多个值。ide
@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
注解也用到这个元注解。
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(); } }
能够看到使用注解可以写出很灵活的代码,注解也特别适合作为使用框架的一种方式。因此学会使用注解仍是颇有用的,毕竟这对于上手框架或实现本身的框架都是很是重要的知识。