注解:
如何理解注解(Annotation)
1)JDK1.5推出的新特性
2)JAVA中的一种元数据(描述数据的数据,类似xml)
3)JAVA中的一种特殊的class(注解最终会编译成.clss文件)
注解的应用场景
1)描述类及其成员(属性,方法)
2)替换项目中xml放在对相关对象的描述
例如:spring框架中的相关注解
注解 | 描述 |
---|---|
@Configuration | 描述配置类对象 |
@Service | 描述业务层对象 |
@controller | 描述控制层对象 |
@Responsitory | 描述数据层对象 |
@ RestControllerAdvice | 描述控制全局的异常处理 |
@Bean | 描述bean对象,一般修饰方法将返回值交给spring管理 |
@Autowired | 实现bean对象的自动装配 |
注解的定义
借助@interface关键字进行定义
@Retention 用于描述注解何时有效
RetentionPolicy.RUNTIME 指运行时有效
RetentionPolicy.SOURCE 指编译时有效
说明:自定义注解包括框架的很多注解都是运行时有效,在运行时可以通过反射技术获取这些注解
并给予注解的描述,实现相关的操作
@Target用于描述注解可以修饰的对象(类,属性,方法)
ElementType.METHOD 指修饰方法
ElementType.TYPE 指修饰类
ElementType.EIELD 指修饰属性
注解应用案例分析实现
1)与编译器结合使用
2)与发射API结合使用
例如:通过反射获取类上的注解及属性或方法
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
/**自定义注解
* 通过反射获取类上的注解*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Controller{
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Service{
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Autowired{
}
@Service
class SysLogService{
}
@Controller("logController")
class SysLogController{
@Autowired
private SysLogService sysLogService;
}
public class TestAnnotation01 {
public static void main(String[] args) throws Exception {
//获取类上的注解
Class<?> cls = Class.forName("annotation.SysLogController");//包名.类名
boolean flag = cls.isAnnotationPresent(Controller.class);
System.out.println(flag);
//获取注解的参数值
Controller con = cls.getDeclaredAnnotation(Controller.class);
System.out.println(con.value());
//获取类中的属性
Field[] fs=cls.getDeclaredFields();
for (Field f : fs) {
if(f.isAnnotationPresent(Autowired.class)){
System.out.println("执行DI操作");
}
}
}
}