Spring-AOP注解实现

AOP注解方式

首先在入口类中开启注解、开启扫描路径,然后开启对AOP相关注解的相关处理:

@Configuration
@ComponentScan(basePackages = "com.lanou3g.spring.simple.say")
@EnableAspectJAutoProxy //开启对AOP相关注解的处理
public class AppByAnnotation {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppByAnnotation.class);
        ISayHello hello = ctx.getBean(ISayHello.class);
        hello.sayHello("JinSaiSai");
    }
}

写一个需要切入的类:

@Component
public class SayHelloImpl implements ISayHello {

    @Override
    public void sayHello() {
      log.info("hello world!");
    }

    @Override
    public void sayHello(String name) {
        log.info("hello, " + name);
    }
}

单独定义一个类用一个方法定义系统中所有用到的切入点表达式:

public class GlobalPointcut {

    /**
     * 通过@Pointcut注解定义切入点表达式
     * 此处表达式含义:拦截com.lanou3g.spring.simple.say包下所有类(包括子包中所有类)中的所有方法
     */
    @Pointcut("execution(* com.lanou3g.spring.simple.say..*.*(..))")
    public void say_all_method() {}

}

定义一个切面,负责收集方法调用的入参、出参(返回值):

public class MethodInOutAspect {

    // 指定该方法是一个环绕通知,通知注解的参数代表引用一个切入点表达式
    @Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")
    public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取连接点方法的名称
        String methodName = joinPoint.getSignature().getName();

        // 获取连接点方法的参数
        Object[] args = joinPoint.getArgs();

        log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 开始执行");
        Object retuVal = joinPoint.proceed();
        log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 返回值: " + retuVal);
        return retuVal;
    }

    @AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")
    public Object afterRM(Object ret) {
        log.debug("[afterRM] 返回值: " + ret);
        return ret;
    }

}

猜你喜欢

转载自blog.csdn.net/csdn_hmt/article/details/92800778