/**
* 用来计算方法的运行时间
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface StopWatch {}
写切面方法
@Component
@Aspect
@Slf4j
public class StopWatchAspect {
// @Pointcut("execution(* com.xisoft.*(..))")
// public void stopWatch(){
// }
@Around("@annotation(com.xisoft.frame.annotate.StopWatch)")
public Object myAround(ProceedingJoinPoint point) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start(getMethodName(point));
Signature signature = point.getSignature();
Object returnVal = point.proceed();//放行
stopWatch.stop();
log.info(stopWatch.prettyPrint());return returnVal;}
public String getMethodName(ProceedingJoinPoint joinPoint){
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature =(MethodSignature) signature;
Method method = methodSignature.getMethod();return method.getName();}}
测试
@Service
public class CccService {
@StopWatch
public void testStopWatch() throws InterruptedException {
Thread.sleep(100);
System.out.println("进入了方法");}}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FrameServiceApplication.class)
@Slf4j
public class CCCTest {
@Autowired
private CccService cccService;
@Test
public void test() throws InterruptedException {
cccService.testStopWatch();}}