AOP的使用有两种
1 使用自定义注解
思路:
- 创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
- 创建切面类,在切面类定义切点和通知注解
@Aspect
@Component
public class LogAsPect {
private final static Logger log = LoggerFactory.getLogger(LogAsPect.class);
// 表示匹配带有自定义注解的方法
@Pointcut("@annotation(com.qidian.midplatform.annotation.Log)")
public void pointcut() {
}
@AfterReturning(value = "pointcut()")
public void returning(){
//自定义通知注解 此时省略
}
}
- 在具体方法上面使用注解
@Log("")
public ResultVO getMethod(String sys_id, String method){
//...
}
2 使用切面类
自定义切面类,切点指向实际的方法即可.省略了自定义注解
@Aspect
@Component
public class LogAsPect {
private final static Logger log = LoggerFactory.getLogger(LogAsPect.class);
@Around("execution(* com..service.impl.MidService.*(..))")
// @Around("execution(* com..service.impl.MidService.*(..))")
// execution指向的就是实际的方法 使用的是表达式,可以自由定义
public Object around(ProceedingJoinPoint point) {
Object result =null;
// ...
}
这篇博客介绍了在Java中使用AOP(面向切面编程)的两种方法:1) 创建自定义注解并定义切面类,通过@Pointcut和@AfterReturning实现方法调用后的日志记录;2) 直接在切面类中使用@Around注解指定方法切点,进行环绕通知。示例展示了如何在具体业务方法上应用自定义注解以触发切面逻辑。
1256

被折叠的 条评论
为什么被折叠?



