公用的方法就是切面,织入到切点
横跨多个功能模块
把切面织入到连接点的位置
目标对象中有很对位置都可以被织入(这些可以被织入的位置被称为连接点joinpoint)
切点pointcunt是连接点中真正织入的点(也就是说不是所有的连接点都织入代码,有些连接点虽然可以被织入,但是实际上并不织入)
定义一个切面类(在这个类上面打上@Aspect注解)
首先@Before表示这个方法在目标方法执行前被调用
execution(* com.example.MyService.*(..))表示去MyService这个类里面寻找切点
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.example.MyService.*(..))")
public void function2() {
// 在目标方法执行之前执行的逻辑
System.out.println("Before advice executed");
}
}
真正的切点就是MyService这个类中加了@MyAnnotation注解的方法,所以最后的效果就是在执行function1()方法之前会先运行function2()方法
@Service
public class MyService {
@MyAnnotation
public void function1() {
// 目标方法逻辑
}
}
@Component
@Aspect
public class AlphaAspect
{
//定义两个内容,切点pointcut,通知advice
@Point("execution()")//这里规定将切面织入到哪些位置,即哪些包下的哪些方法
public void pointcut()
{
}
@Before("pointcut()")
public void before()
{
System.out.println("before");
}
@After("pointcut()")
public void after()
{
System.out.println("after");
}
}
通知advice分成:
前置通知: before advice
后置通知: after advice
环绕通知: around advice
返回值后通知:afterReturning advice
异常通知:afterThrowing advice
实战:利用before,在调用方法之前记录谁在什么时候调用了这个方法,这个日志只会在后台控制台输出,不会在前端浏览器打印
按以下格式打印:
用户XXXX在xxxxx时刻访问了 com.nowcoder.community.service.xxx
@Component
@Aspect
public ServiceLogAspect
{
private static final Logger logger=LoggerFactory.getLogger(ServiceLogAspect.class);
//定义两个内容,切点pointcut,通知advice
@Point("execution(com.nowcoder.community.service.*.*(..))")//这里规定将切面织入到哪些位置,即哪些包下的哪些方法
public void pointcut()
{
}
@Before("pointcut()")
public void before()
{
//获取当前用户ip
//获取当前时间
String now=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
logger.info(.....);
}
}
在业务方法的前后增加一些通用的操作(最常见的通用操作就是打印日志