AOP面向切面编程
AOP(Aspect Oriented Programming)面向切面编程,一种编程范式,指导开发者如何组织程序结构。
作用:在不惊动原始设计的基础上为其进行功能增强,前面咱们有技术就可以实现这样的功能即代理模式。
有以下几个概念:
1.通知(Advice)——给目标方法添加额外操作称之为通知,也可以称为增强
2.连接点(Joinpoint)——就是可以增强的地方(方法的前后某个阶段)
3.切入点(Pointcut)——实际增强的地方
4.切面(Aspect)——封装了通知和切入点用来横向插入的类
5.代理(Proxy)——将通知应用到目标类动态创建的对象
6.织入(Weaving)——将切面插入到目标从而生成代理对象的过程
当我们了解了相关概念之后结合代码看看
/**
* AOP切面统计阅读量
*/
@Aspect
@Component
public class ReadingNumAspect {
private final IPersonalCenterService personalCenterService;
private final RedisUtil redisUtil;
public ReadingNumAspect(IPersonalCenterService articleService, RedisUtil redisUtil) {
this.personalCenterService = articleService;
this.redisUtil = redisUtil;
}
//Controller层切入点,这里用到了自定义注解的形式,下面会介绍
@Pointcut("@annotation(tech.niua.core.annotation.ReadingNum)")
private void ControllerAspet(){
}
/**
* 后置通知,统计阅读量
* @param joinPoint
*/
@After("ControllerAspet()")
private void doBefore(JoinPoint joinPoint){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//请求url
System.out.println("------------url:"+request.getRequestURI());
//调用的方法
System.out.println("------------method:"+joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
String[] strs=request.getRequestURI().split("/");
System.out.println(strs[3]);
this.personalCenterService.readingVolumeIncrease(Long.valueOf(strs[3]));
//请求的参数
Map<String, String[]> properties = request.getParameterMap();
Map<Object, Object> returnMap = new HashMap<Object, Object>();
Iterator<Map.Entry<String, String[]>> entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value = values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
returnMap.put(name, value);
}
System.out.println("------------param:"+returnMap.toString());
}
}
接下来我们再来看一定义注解:
import java.lang.annotation.*;
/**
* controller层阅读量拦截
*
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ReadingNum {
String value() default "";
}
首次,我们创建一个注解文件
然后,我们在相应的方法上使用该注解
/**
* 根据id查询帖子
*/
@ReadingNum()
@PostMapping("/student/{id}")
public ResultJson student(@PathVariable Long id) {
//业务代码
}
然后,我们利用切面,将切入点改成该注解,就实现了,自定义注解的切面