一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、创建注解接口并定义参数
@Documented
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}
- @interface是用来自定义JAVA Annotation的语法,
- @interface是用来自定义注注解类型的
- @Documented –注解是否将包含在JavaDoc(用于描述类或者方法的作用;Javadoc可以写在类上面和方法上面)中
- @Retention –什么时候使用该注解
- @Target –注解用于什么地方
- @Inherited – 是否允许子类继承该注解
三、创建解析注解类
@Aspect
@Component
public class HLogAspect {
@Pointcut("@annotation(com.threegroups.shopping.Log)")
public void annotationPointCut() {
}
@Before("annotationPointCut()")
public void before(JoinPoint joinPoint){
MethodSignature sign = (MethodSignature)joinPoint.getSignature();
Method method = sign.getMethod();
System.out.print("自定义注解已生效!");
}
}
切面注解 :
@Aspect – 标识为一个切面供容器读取,作用于类
@Pointcut – (切入点):就是带有通知的连接点
@Before – 前置
@AfterThrowing – 异常抛出
@After – 后置
@AfterReturning – 后置增强,执行顺序在@After之后
@Around – 环绕
- 定义切点(@Pointcut)并对其做增强:前置增强、环绕增强、后置增强等。
- @Pointcut()定义表达式切点
- @annotation() 类或者方法表示这个注解类或者方法是切点,即植入程序的点。
- execution定义一个切入点表达式,用来确定哪些类需要代理。@Pointcut(“execution(* com.threegroups.shopping..(…))”)代表shopping包下所有类的所有方法都会被代理
- 时间切入点一般有:@before @after @around @afterretund等。
- JoinPoint对象封装了SpringAop中切面方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该方法信息的JoinPoint对象。
获取代理方法的对象和参数 并添加包装。