切入点表达式增强

切入点表达式增强
Spring中通过切入点表达式定义具体切入点,其常用AOP切入点表达式定义及说明
在这里插入图片描述
bean表达式(重点)
bean表达式一般应用于类级别,实现粗粒度的切入点定义,案例分析:

bean(“userServiceImpl”)指定一个userServiceImpl类中所有方法。
bean("*ServiceImpl")指定所有后缀为ServiceImpl的类中所有方法。
说明:bean表达式内部的对象是由spring容器管理的一个bean对象,表达式内部的名字应该是spring容器中某个bean的name。

within表达式(了解)
within表达式应用于类级别,实现粗粒度的切入点表达式定义,案例分析:

within(“aop.service.UserServiceImpl”)指定当前包中这个类内部的所有方法。
within(“aop.service.") 指定当前目录下的所有类的所有方法。
within("aop.service…
”) 指定当前目录以及子目录中类的所有方法。
execution表达式(了解)
execution表达式应用于方法级别,实现细粒度的切入点表达式定义,案例分析:

语法:execution(返回值类型 包名.类名.方法名(参数列表))。

execution(void aop.service.UserServiceImpl.addUser())匹配addUser方法。
execution(void aop.service.PersonServiceImpl.addUser(String)) 方法参数必须为String的addUser方法。
execution(* aop.service….(…)) 万能配置。

@annotation表达式(重点)
@annotaion表达式应用于方法级别,实现细粒度的切入点表达式定义,案例分析

@annotation(anno.RequiredLog) 匹配有此注解描述的方法。
@annotation(anno.RequiredCache) 匹配有此注解描述的方法。
其中:RequiredLog为我们自己定义的注解,当我们使用@RequiredLog注解修饰业务层方法时,系统底层会在执行此方法时进行日扩展操作

练习:定义一Cache相关切面,使用注解表达式定义切入点,并使用此注解对需要使用cache的业务方法进行描述,代码分析如下:

package com.cy.pj.common.aspect;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SysCacheAspect {
	
	private Map<Object ,Object>cache=new ConcurrentHashMap<>();
	@Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
	public void doCache() {}
	@Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
	public void doClear() {}
	
	@AfterReturning("doClear")
	public void doAfterReturning() {
		
		cache.clear();
		
	}
	@Around("doCache()")
	public Object doAround(ProceedingJoinPoint jp) throws Throwable{
		System.out.println("Get Data From Cache");
		Object result=cache.get("dataKey");
		if(result !=null)return result;
		result=jp.proceed();
		System.out.println("Put data to Cache");
		cache.put("dataKey",result);
		return result;
	}
}


版权声明:本文为uzi2200原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。