SpringBoot中aop的使用

步驟

  • 編寫使用註解的被攔截類,加了這個註解的類或者方法就會被攔截
  • 使用@Aspect聲明一個切面,並通過@Component讓此切面成爲Spring容器管理的Bean
  • 使用@After、@Befor、@Aroud定義建言(advice),可直接將攔截規則(切點)作爲參數。這兒也是業務代碼所在的地方
  • 在配置類上使用@EnableAspectJAutoProxy開啓Spring對AspectJ的支持
  • 啓動類上添加@AopConfig引入

部分代碼

ExecTime.java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExecTime {
    String value() default "";
}

ExecTimeAspect.java 切面

@Aspect
@Component
public class ExecTimeAspect {

    private static final Logger logger = LoggerFactory.getLogger(ExecTimeAspect.class);

    /**
     * 這兒填寫ExecTime.java的全路徑名
     */
    @Pointcut("@annotation(com.xx.annotation.ExecTime)")
    public void annotationPointCut() {
    }

    /**
     * 統計方法執行的時長
     *
     * @param joinPoint the join point
     * @return object
     * @throws Throwable
     */
    @Around("annotationPointCut()")
    public Object wasteTime(ProceedingJoinPoint joinPoint) {
        Object output = null;
        try {
            long start = System.currentTimeMillis();
            output = joinPoint.proceed();
            long elapsedTime = System.currentTimeMillis() - start;

            // 執行的真實類名稱
            String className = joinPoint.getTarget().getClass().getSimpleName();
            logger.info(String.format("method [%s.%s()] execution time:%sms", className, joinPoint.getSignature().getName(), elapsedTime));
        } catch (Throwable throwable) {
            logger.error("aop record method exec time error", throwable);
        }
        return output;
    }
}

AopConfig.java

@Configuration
@ComponentScan("com.xxx)
@EnableAspectJAutoProxy
public class AopConfig {
}

啓動類

@SpringBootApplication(scanBasePackages = "com.xxx")
@Import({AopConfig.class})
public class ApplicationStartUp extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ApplicationStartUp.class);
    }

    public static void main(String[] args) {
        APIVersionChecker.check();
        SpringApplication app = new SpringApplication(ApplicationStartUp.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }
}

實際使用

最後,在需要統計耗時的方法前,加上@ExecTime 註解就可以了
service方法:

    @ExecTime
    @Override
    public List<User> getList(Integer page, Integer pageSize) {
        return userRepository.findList((page-1)*pageSize, pageSize+1);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章