spring-boot使用@aspect切面编程

最后更新:

   我们遇到很多业务场景需要在做一项工作的时候,有跟这个工作相关联的工作一块执行,如在这项工作的前面执行一个事情,或者后面执行一个事情等等。
   现在开发为了方便阅读代码,不影响当前代码结构,我们采取切面编程的方式,另外通过自定义注解的方式来进一步控制切面编程。

1
2
3
4
5
6
7
8
9
//自定义注解
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface pizerLog {
/** 两个控制参数 **/
public String param_a() default "";
public String param_b() default "";
}

   
   spring若要用@Aspect,需要在xml内配置,才能解析切面代码

1
<aop:aspectj-autoproxy/>

   面向切面编程代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Component
@Aspect
public class PizerAspect {
/**service层切面*/
private final String POINT_CUT = "execution(* project.Service..*(..))";
@Pointcut(POINT_CUT)
private void (){}
@Before(value = "pointcut()")
public void doAfterAdvice(JoinPoint joinPoint) throws ClassNotFoundException {
System.out.println("方法前面");
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String param_a = "";
String param_b = "";
if (methods.length>0){
for (Method method : methods) {
if (method.getName().equals(methodName)) {
if (method.getAnnotation(pizerLog.class)!=null){
param_a = method.getAnnotation(pizerLog.class).param_a();
param_b = method.getAnnotation(pizerLog.class).param_b();
break;
}
}
}
}
//拿到两个参数,再根据自己业务进行二次控制
System.out.println("param_a=="+param_a);
System.out.println("param_b=="+param_b);
}
}

   
   spring-boot的service代码

1
2
3
4
5
6
@RestController
public interface RedissonTestService {
@ResponseBody
@RequestMapping("/aasd")
String getRedissonClient();
}

   
   spring-boot的RedissonTestService实现代码

1
2
3
4
5
6
7
8
9
10
11
@Controller
public class RedissonTestServiceImpl implements RedissonTestService {
@JournalLog(operationType = "asdasd",modularTypeName = "1")
public String getRedissonClient() {
System.out.println("方法中");
return "asd";
}
}

   最后访问GET http://localhost:11111/aasd,可以查看切面信息在执行方法前边先执行,若要在后执行或者需要其他方式,请继续查阅@After等等注解。