前言:Aop注解增强模式,可以在项目的方法中加入注解模式直接增强某方法。
不多废话,看代码
1:导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
2:编写普通方法,下面以controller为例
package com.apiyuanser.module.controller;
import com.apiyuanser.aop.AopStrong;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin
public class YuanController {
@Value("${config.info}")
private String str;
@PostMapping("/get")
@AopStrong
public String getStr(){
System.out.println("add..........");
return str;
}
}
3:新增注解apimgr
package com.apiyuanser.aop;
import org.springframework.core.annotation.Order;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Order(-1)
public @interface AopStrong {
String value() default "";
}
4:编写aop
package com.apiyuanser.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AopStrongAspect {
@Pointcut("@annotation(com.apiyuanser.aop.AopStrong)")
public void cutpoits(){}
@Before("cutpoits()")
public void beforeMethon(){
System.out.println("前置增强");
}
@After("cutpoits()")
public void afterMethon(){
System.out.println("后置增强");
}
@Around("cutpoits()")
public Object aroundMethod(ProceedingJoinPoint proce) throws Throwable {
System.out.println("环绕前");
Object proceed = proce.proceed();
System.out.println("proceed为:" + proceed);
System.out.println("环绕后");
return proceed;
}
}
5:配置文件里面写controller中str的值
config:
info: 123
6:调用controller的/get方法
会返回: 123
7:控制台
8:如有问题,欢迎提出