一、自定义注解
1、@Documented:指定被标注的注解会包含在javadoc中。
2、@Retention: 指定注解的生命周期(源码、class文件、运行时),其参考值见类的定义:java.lang.annotation.RetentionPolicy
● RetentionPolicy.SOURCE : 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
● RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式。
● RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。
3、@Target:指定注解使用的目标范围(类、方法、字段等),其参考值见类的定义:java.lang.annotation.ElementType
● ElementType.CONSTRUCTOR :用于描述构造器。
● ElementType.FIELD :成员变量、对象、属性(包括enum实例)。
● ElementType.LOCAL_VARIABLE: 用于描述局部变量。
● ElementType.METHOD : 用于描述方法。
● ElementType.PACKAGE :用于描述包。
● ElementType.PARAMETER :用于描述参数。
● ElementType.ANNOTATION_TYPE:用于描述参数
● ElementType.TYPE :用于描述类、接口(包括注解类型) 或enum声明。
4、@Inherited:指定子类可以继承父类的注解,只能是类上的注解,方法和字段的注解不能继承。即如果父类上的注解是@Inherited修饰的就能被子类继承。
jdk1.8又提供了以下两个元注解
5、@Native:指定字段是一个常量,其值引用native code。
6、@Repeatable:注解上可以使用重复注解,即可以在一个地方可以重复使用同一个注解,像spring中的包扫描注解就使用了这个。
7、使用@interface关键词来定义注解。
实现:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogOperate {
}
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
切面(切点加通知):
切点有两种形式:
- execution表达式
execution(* com.test.aspect.service.*.*(..)) 第一个* 代表的是所有返回值类型,第二个*代表的是包下所有的类,第三个*代表的是类下所有的方法,()里的..代表的是所有参数类型
- 注解形式
@annotation(com.hzx.shop.operate.LogOpera)
@Aspect
@Component
@Log4j2(topic = "c.logAdvice")
public class LogAdvice {
@Pointcut("@annotation(com.hzx.shop.operate.LogOperate)")
public void log(){}
@Pointcut("execution(* com.hzx.shop.controller.*.*(..))")
public void executionLog(){}
@Before(value = "executionLog()")
public void before(JoinPoint joinPoint){
log.info("###################executionLog");
}
@Around(value = "log()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
// 记录下请求内容
log.info("################URL : " + request.getRequestURL().toString());
log.info("################HTTP_METHOD : " + request.getMethod());
log.info("################IP : " + request.getRemoteAddr());
log.info("################THE ARGS OF THE CONTROLLER : " + Arrays.toString(joinPoint.getArgs()));
//下面这个getSignature().getDeclaringTypeName()是获取包+类名的 然后后面的joinPoint.getSignature.getName()获取了方法名
log.info("################CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//logger.info("################TARGET: " + joinPoint.getTarget());//返回的是需要加强的目标类的对象
//logger.info("################THIS: " + joinPoint.getThis());//返回的是经过加强后的代理类的对象
Object object = joinPoint.proceed();
return object;
}
}
结果:
参考:
自定义注解
springAop实现日志管理