Spring:AOP注解配置和扫描示例讲解及环绕通知接口耗时实战(11)

本文详细介绍了如何在Spring中通过AOP注解配置声明切面,包括Service层、ServiceImpl实现、切点通知配置以及AOP扫描。接着,展示了如何实现环绕通知来统计接口执行的耗时,模拟线程耗时并测试效果。这个例子在实际开发中具有很高的实用性。
摘要由CSDN通过智能技术生成
声明切面类

@Aspect(切面): 通常是一个类,里面可以定义切入点和通知

使用注解的方式代替这些配置
在这里插入图片描述

Stpe1:Service层

public interface VideoService {

    int save(Video video);

    Video findById(int id);
}

Step2:ServiceImpl实现类

@Service("videoService")
public class VideoServiceImpl implements VideoService {

    @Autowired
    private CustomConfig customConfig;


    public int save(Video video) {

        System.out.println(customConfig.getHost());
        System.out.println("保存video");
        return 1;
    }

    public Video findById(int id) {
        System.out.println("根据id查询视频信息");
        return new Video();
    }
}

Step3:配置切点通知

@Configurati
可以通过在方法前后添加时间戳,然后计算时间差来计算方法耗时。也可以使用Spring AOP的拦截器,在方法执行前后记录时间戳,然后计算时间差。以下是一个使用Spring AOP计算方法耗时示例: 1. 定义一个切面类,实现MethodInterceptor接口 ```java @Component @Aspect public class TimingAspect implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { long startTime = System.currentTimeMillis(); Object result = invocation.proceed(); long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; System.out.println(invocation.getMethod().getName() + " 方法耗时:" + elapsedTime + "ms"); return result; } } ``` 2. 在配置文件中启用AOP,并将切面类作为切点 ```xml <aop:aspectj-autoproxy /> <bean id="timingAspect" class="com.example.TimingAspect" /> <aop:config> <aop:aspect ref="timingAspect"> <aop:pointcut expression="execution(* com.example.service.*.*(..))" /> <aop:around method="invoke" /> </aop:aspect> </aop:config> ``` 3. 在需要计算耗时方法上加上@LogExecutionTime注解 ```java @Service public class MyService { @LogExecutionTime public void doSomething() { // do something } } ``` 4. 定义@LogExecutionTime注解和切面类 ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LogExecutionTime { } @Component @Aspect public class TimingAspect { @Around("@annotation(com.example.LogExecutionTime)") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; System.out.println(joinPoint.getSignature().getName() + " 方法耗时:" + elapsedTime + "ms"); return result; } } ``` 这样,在调用doSomething方法时,就会输出方法耗时的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值