當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
springboot切面返回值_SpringBoot实战15-Spring基础-AOP
生活随笔
收集整理的這篇文章主要介紹了
springboot切面返回值_SpringBoot实战15-Spring基础-AOP
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上篇我們學習了《SpringBoot實戰14-Spring基礎-Spring EL表達式》,本篇我們學習面向切面編程AOP。
7 AOP
面向切面編程(Aspect-Oriented Programming簡稱AOP),它可以做到添加額外的行為到現有的指定條件的一批Bean上,但是我們并不需要修改Bean的代碼,這樣使得額外行為和Bean本身行為關注隔離。
學習AOP,我們首先要熟悉下面的概念:
- 切面:Aspect,編寫額外行為的地方;
- 連接點:Join Point,被攔截的方法;
- 切點:PointCut,通過條件匹配一批連接點;
- 建言:Advice,對于每個連接點需要做的行為;
- 目標對象:符合指定條件的Bean
我們使用AOP開發需要使用@EnableAspectJAutoProxy注解來開啟AspectJ的支持,Spring Boot已經為我們自動做了配置,我們無需額外聲明。
我們來編寫一個使用AOP來記錄操作日志的例子,我們先編寫一個注解用來給切點作為攔截條件:
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Logging { String value() default "";}目標對象為:
@Servicepublic class PersonService { @Logging("人員新增操作") public void add(String name){ //每個被攔截的方法都是連接點 System.out.println("人員新增"); } @Logging("人員刪除操作") public void remove(String name){ System.out.println("人員刪除"); } @Logging("人員查詢操作") public String query(String name){ System.out.println("人員查詢"); return name; } @Logging("人員修改操作") public String modify(String name){ System.out.println("人員修改"); return name.toUpperCase(); }}下面是我們最重要的部分,切面部分的編寫:
@Aspect //1@Componentpublic class LoggingAspect { @Pointcut("@annotation(top.wisely.springfundamentals.aop.Logging)") //2 public void annotationPointCut(){} @Before("annotationPointCut()") //3 public void beforeAnnotationPointCut(JoinPoint joinPoint){//4 String name = (String) joinPoint.getArgs()[0]; //5 MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String action = methodSignature.getMethod().getAnnotation(Logging.class).value(); //6 System.out.println("對" + name + "進行了"+ action); } @AfterReturning(pointcut = "annotationPointCut()", returning = "retName") //7 public void afterReturningAnnotationPointCut(JoinPoint joinPoint, String retName){ String name = (String) joinPoint.getArgs()[0]; MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String action = methodSignature.getMethod().getAnnotation(Logging.class).value(); System.out.println("對" + name + "進行了"+ action + ",返回的名字為:" + retName); } }我們在JavaConfig執行:
@BeanCommandLineRunner aopCle(PersonService personService){ return args -> { personService.add("wyf"); personService.remove("wyf"); personService.query("wyf"); personService.modify("wyf"); };}下一篇《SpringBoot實戰16-Spring基礎-Spring注解的工作原理》
總結
以上是生活随笔為你收集整理的springboot切面返回值_SpringBoot实战15-Spring基础-AOP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vs.net 打开.xaml文件编辑界面
- 下一篇: 架空输电线路运行规程_架空输电线路通道与