當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
springboot切面返回值_SpringBoot实战15-Spring基础-AOP
生活随笔
收集整理的這篇文章主要介紹了
springboot切面返回值_SpringBoot实战15-Spring基础-AOP
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
上篇我們學(xué)習(xí)了《SpringBoot實(shí)戰(zhàn)14-Spring基礎(chǔ)-Spring EL表達(dá)式》,本篇我們學(xué)習(xí)面向切面編程AOP。
7 AOP
面向切面編程(Aspect-Oriented Programming簡(jiǎn)稱AOP),它可以做到添加額外的行為到現(xiàn)有的指定條件的一批Bean上,但是我們并不需要修改Bean的代碼,這樣使得額外行為和Bean本身行為關(guān)注隔離。
學(xué)習(xí)AOP,我們首先要熟悉下面的概念:
- 切面:Aspect,編寫額外行為的地方;
- 連接點(diǎn):Join Point,被攔截的方法;
- 切點(diǎn):PointCut,通過條件匹配一批連接點(diǎn);
- 建言:Advice,對(duì)于每個(gè)連接點(diǎn)需要做的行為;
- 目標(biāo)對(duì)象:符合指定條件的Bean
我們使用AOP開發(fā)需要使用@EnableAspectJAutoProxy注解來開啟AspectJ的支持,Spring Boot已經(jīng)為我們自動(dòng)做了配置,我們無需額外聲明。
我們來編寫一個(gè)使用AOP來記錄操作日志的例子,我們先編寫一個(gè)注解用來給切點(diǎn)作為攔截條件:
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Logging { String value() default "";}目標(biāo)對(duì)象為:
@Servicepublic class PersonService { @Logging("人員新增操作") public void add(String name){ //每個(gè)被攔截的方法都是連接點(diǎn) 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("對(duì)" + name + "進(jìn)行了"+ 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("對(duì)" + name + "進(jìn)行了"+ action + ",返回的名字為:" + retName); } }我們?cè)贘avaConfig執(zhí)行:
@BeanCommandLineRunner aopCle(PersonService personService){ return args -> { personService.add("wyf"); personService.remove("wyf"); personService.query("wyf"); personService.modify("wyf"); };}下一篇《SpringBoot實(shí)戰(zhàn)16-Spring基礎(chǔ)-Spring注解的工作原理》
總結(jié)
以上是生活随笔為你收集整理的springboot切面返回值_SpringBoot实战15-Spring基础-AOP的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vs.net 打开.xaml文件编辑界面
- 下一篇: csv与json互转_CSV文件转JSO