一、什么是注解
对于很多初次接触的开发者来说应该都有这个疑问?Annotation是Java5开始引入的新特征,中文名称叫注解。它提供了一种安全的类似注释的机制,用来将任何的信息或元数据(metadata)与程序元素(类、方法、成员变量等)进行关联。为程序的元素(类、方法、成员变量)加上更直观更明了的说明,这些说明信息是与程序的业务逻辑无关,并且供指定的工具或框架使用。Annontation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的声明语句中。
Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。
二、注解的作用
1、生成文档。这是最常见的,也是java 最早提供的注解。常用的有@param @return 等
2、跟踪代码依赖性,实现替代配置文件功能。比如Dagger 2依赖注入,未来java开发,将大量注解配置,具有很大用处;
3、在编译时进行格式检查。如@override 放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出。
三、注解的原理
注解本质是一个继承了Annotation的特殊接口,其具体实现类是Java运行时生成的动态代理类。而我们通过反射获取注解时,返回的是Java运行时生成的动态代理对象$Proxy1。通过代理对象调用自定义注解(接口)的方法,会最终调用AnnotationInvocationHandler的invoke方法。该方法会从memberValues这个Map中索引出对应的值。而memberValues的来源是Java常量池。
四、注解的使用基础
1.注解的定义:Java文件叫做Annotation,用@interface表示。
2.元注解:@interface上面按需要注解上一些东西,包括@Retention、@Target、@Document、@Inherited四种。
3.注解的保留策略:
@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
4.注解的作用目标:
@Target(ElementType.TYPE) // 接口、类、枚举、注解
@Target(ElementType.FIELD) // 字段、枚举的常量
@Target(ElementType.METHOD) // 方法
@Target(ElementType.PARAMETER) // 方法参数
@Target(ElementType.CONSTRUCTOR) // 构造函数
@Target(ElementType.LOCAL_VARIABLE) // 局部变量
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) // 包
5.注解包含在javadoc中:
@Documented
6.注解可以被继承:
@Inherited
7.注解解析器:用来解析自定义注解。
五、常用注解
1.)Override
java.lang.Override是一个标记类型注解,它被用作标注方法。它说明了被标注的方法重载了父类的方法,起到了断言的作用。如果我们使用了这种注解在一个没有覆盖父类方法的方法时,java编译器将以一个编译错误来警示。
2.)Deprecated
Deprecated也是一种标记类型注解。当一个类型或者类型成员使用@Deprecated修饰的话,编译器将不鼓励使用这个被标注的程序元素。所以使用这种修饰具有一定的“延续性”:如果我们在代码中通过继承或者覆盖的方式使用了这个过时的类型或者成员,虽然继承或者覆盖后的类型或者成员并不是被声明为@Deprecated,但编译器仍然要报警。
3.)SuppressWarnings
SuppressWarning不是一个标记类型注解。它有一个类型为String[]的成员,这个成员的值为被禁止的警告名。对于javac编译器来讲,被-Xlint选项有效的警告名也同样对@SuppressWarings有效,同时编译器忽略掉无法识别的警告名。
@SuppressWarnings("unchecked")
六、注解例子-spring日志
package com.zjq.eureka.user.aspect;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface SpringLog {
/** 模块 */
String title() default "";
/** 功能 */
String action() default "";
/** 请求地址 */
String requestUrl();
}
package com.zjq.eureka.user.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Aspect
@Component
public class LogAspect {
//切入点
@Pointcut(value = "@annotation(com.zjq.eureka.user.aspect.SpringLog)")
private void pointcut() {
log.info("进入切入点!" );
}
/**
* 在方法执行前
*
* @param point
* @param myLog
* @return
*/
@Around(value = "pointcut() && @annotation(myLog)")
public Object around(ProceedingJoinPoint point, SpringLog myLog) {
log.info("执行了around方法");
String requestUrl = myLog.requestUrl();
String title = myLog.title();
String action = myLog.action();
//拦截的类名
Class<? extends Object> clazz = point.getTarget().getClass();
//拦截的方法
Method method = ((MethodSignature) point.getSignature()).getMethod();
log.info("执行了 类:" + clazz + " 方法:" + method + " 自定义请求地址:" + requestUrl);
log.info("请求模块:" +title+ "功能描述:" + action );
try {
return point.proceed(); //执行程序
} catch (Throwable throwable) {
throwable.printStackTrace();
return throwable.getMessage();
}
}
/**
* 方法执行后
*
* @param joinPoint
* @param myLog
* @param result
* @return
*/
@AfterReturning(value = "pointcut() && @annotation(myLog)", returning = "result")
public Object afterReturning(JoinPoint joinPoint, SpringLog myLog, Object result) {
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// HttpSession session = request.getSession();
log.info("执行了afterReturning方法");
log.info("执行结果:" + result);
return result;
}
/**
* 方法执行后 并抛出异常
*
* @param joinPoint
* @param myLog
* @param ex
*/
@AfterThrowing(value = "pointcut() && @annotation(myLog)", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, SpringLog myLog, Exception ex) {
log.info("执行了afterThrowing方法");
log.info("请求:" + myLog.requestUrl() + " 出现异常");
}
}
@SpringLog(requestUrl="/testAspect",action="测试日志注解",title="注解")
@RequestMapping(value="/testAspect", method=RequestMethod.GET)
public String testAspect() {
return "success";
}