在Spring Boot框架中使用AOP

做者簡介java

彬哥,目前任職於餓了麼,從事餓了麼物流側核心系統的開發工做,喜好鑽研各類技術,用技術解決實際問題。app

Spring Boot是基於Spring的用來開發Web應用的框架,功能與Spring MVC有點相似,可是Spring Boot的一大特色就是須要的配置很是少。Spring Boot推薦convention over configuration,也就是約定大於配置,所以Spring Boot會幫你作許多自動的配置,而且Spring Boot使用的是Java Config,幾乎能夠作到零XML文件配置。框架

假設如今有這樣一種場景,須要統計某個接口的處理耗時,咱們可使用AOP來實現,在Spring Boot中使用AOP也很是簡單,只須要一點簡單的配置便可。spa

須要使用AOP的類

@RestController
public class DownloadController {

    @Autowired
    private XmlDownloadService downloadService;

    @Autowired
    private XmlFileClearService clearService;

    @RequestMapping("/download")
    @Timer
    public String download() throws Exception {
        downloadService.download();
        clearService.compress();
        clearService.clearAll();
        return "ok";
    }

}
複製代碼

這是一個使用@RestController註解的Controller類,這個類會去下載一些XML文件,而後壓縮,最後刪除下載的XML文件。如今咱們要統計整個處理過程的耗時,使用AOP來實現。在download上使用了一個@Timer註解,這是一個自定義的普通註解,用來標記這個方法做爲一個切點。code

Aspect類

@Aspect
@Component
public class VipAspect {

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

    private long start;

    //定義切點
    @Pointcut("@annotation(cn.magicwindow.mlink.content.annotation.Timer)")
    public void timer(){}

    //在方法執行前執行
    @Before("timer()")
    public void before() {
        start = System.currentTimeMillis();
    }

    //在方法執行後執行
    @After("timer()")
    public void after() {
        long now = System.currentTimeMillis();
        logger.info("job took time {}s in summary", (now - start) / 1000);
    }
}
複製代碼

這裏使用了註解來標記切點,也能夠直接按照方法名稱來定義,具體的使用方法能夠參考官方文檔。cdn

配置Spring Boot支持AOP

@Configuration
@EnableAspectJAutoProxy
public class Config {
}
複製代碼

只須要使用@EnableAspectJAutoProxy註解開啓Spring Boot的AOP支持便可。接口

最後,在調用download方法以後就會打印出本次處理的用時。ip




閱讀博客還不過癮?開發

歡迎你們掃二維碼加入交流羣,討論和博客有關的技術問題,還能夠和博主有更多互動 文檔

博客轉載、線下活動及合做等問題請郵件至 shadowfly_zyl@hotmail.com 進行溝通
相關文章
相關標籤/搜索