关于Java注解的理解
自从用了Spring Boot框架之后,注解几乎就是绕不开的一个东西了。不用再在xml里面配置东西,直接用注解在java代码里面标注,灰常的方便。
此前对于Java注解的机制还是比较模糊的,不了解为毛线在某些类上头标个注解就能实现相应的功能,最近看了一下相关资料,手动实现了一下。
记录一下我的思考过程:
首先先看一下常用注解的源码
// Controller的源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
String value() default "";
}
// Service的源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
String value() default "";
}
一毛一样,没有任何区别来着
可是Service和Controller虽说都是Spring的Bean,但是功能相差甚远,为什么源码却是一样。
翻了一下人家的blog,原来注解是不提供任何逻辑的,它仅仅只是一个标注作用,然后带点数据,逻辑是需要靠其他的代码实现的。
比如
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ToaAnnotation {
String value() default "";
}
@ToaAnnotation("target")
public class AnnotationTarget {
}
public class YoawebApplication {
try{
Class cls =Class.forName("com.example.yoaweb.annotation.AnnotationTarget");
if (cls.isAnnotationPresent(ToaAnnotation.class)){
ToaAnnotation annotation =(ToaAnnotation) cls.getAnnotation(ToaAnnotation.class);
System.out.println(annotation.value());
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
在main函数中,我们可以获得到注解的value值,我们可以也可以去通过isAnnotationPresent查看该类有没有用某注解标注。
Spring的底层想必也是这样,扫描包,查看有没有相应注解,有的话根据注解的类型生成相应的Spring Bean。