Java 注解定义及切面应用示例
Java定义一个注解可以使用'@interface'关键字,如下所示:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default '';
}
其中:
- '@Retention(RetentionPolicy.RUNTIME)'表示该注解在运行时可以被反射获取;
- '@Target(ElementType.METHOD)'表示该注解可以用在方法上;
定义切面可以使用AOP(面向切面编程)框架,比如Spring AOP。在Spring AOP中,切面可以通过定义切点和切面实现,如下所示:
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* com.example.demo.service.*.*(..))")
public void servicePointcut() {}
@Around("servicePointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
// do something before method invocation
Object result = joinPoint.proceed();
// do something after method invocation
return result;
}
}
其中:
- '@Aspect'表示该类是一个切面;
- '@Component'表示该类可以被Spring容器管理;
- '@Pointcut("execution(* com.example.demo.service..(..))")'定义了一个切点,表示拦截com.example.demo.service包下的所有方法;
- '@Around("servicePointcut()")'定义了一个切面,表示在servicePointcut()切点匹配的方法执行前后执行doAround()方法。
原文地址: https://www.cveoy.top/t/topic/lFrK 著作权归作者所有。请勿转载和采集!