利用AOP自定义注解能在很多时候很好的解耦代码
1. 完善pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 自定义注解
/**
* @author guoxy
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface DoSomething {
String key();
String value();
boolean test() default false;
}
3. 制定切点
@Aspect
@Component
public class AnnotationImpl {
@Pointcut("@annotation(com.learn.practice.annotation.DoSomething)")
public void doSomethingPointCut() {
}
@Before("doSomethingPointCut()")
public void before(JoinPoint joinPoint) {
MethodSignature sign = (MethodSignature) joinPoint.getSignature();
Method method = sign.getMethod();
DoSomething annotation = method.getAnnotation(DoSomething.class);
System.out.println("this before:"+annotation.key()+":" + annotation.value()+":" + annotation.test());
}
@After("doSomethingPointCut()")
public void after(JoinPoint joinPoint) {
MethodSignature sign = (MethodSignature) joinPoint.getSignature();
Method method = sign.getMethod();
DoSomething annotation = method.getAnnotation(DoSomething.class);
System.out.println("this after:"+annotation.key()+":" + annotation.value()+":" + annotation.test());
}
@Around("doSomethingPointCut()")
public Object methodAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around before");
MethodSignature sign = (MethodSignature) joinPoint.getSignature();
Method method = sign.getMethod();
//todo 你可以根据业务逻辑是否调用原来的方法
Object proceed = joinPoint.proceed();
System.out.println("Around after");
return proceed;
}
}
4. 执行控制层
/**
* 测试的控制层
* @author guoxy
*/
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/get")
@DoSomething(key = "aaa",value = "bbb",test = true)
public String getTest(){
System.out.println("this is test method");
return "aaa";
}
}
5.执行结果
Around before
this before:aaa:bbb:true
this is test method
Around after
this after:aaa:bbb:true
写的不好的地方希望多多指正,多多交流学习,萌新接受一切批评指正!
网友评论