AOP:Aspect Oriented Programming,面向切面编程
需要引入新的命名空间
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- bean definitions here -->
</beans>
以上绿色的为新引入的AOP命名空间
然后需要引入<aop:aspectj-autoproxy/>
因为用到了@Component所以加入:
<context:annotation-config/>
<context:component-scan base-package="org.example"/>
AspectJ:专门产生动态代理的框架,Spring使用了此框架。
package com.bjsxt.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect //作为一个切面
@Component //需要将此类交给Spring,作为一个组件初始化
public class LogInterceptor {
@Pointcut("execution(public * com.bjsxt.dao..*.*(..))") //指定加到哪个类的哪个方法上,dao包下的任何子包下的任何方法,参数为任何值,返回值为任何值
public void myMethod(){};
@Before("myMethod()") //很显然,这个是本类中的方法,在执行myMethod方法前先执行before方法
public void before() {
System.out.println("method before");
}
@Around("myMethod()")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}
注意:首先这个对象一定要是Spring管理起来的,自己new出来的没用,Spring管不到。
写程序的时候不要依赖于@Before先还是@Around先这种先后顺序。
如果这个类没有实现接口,那么Spring会使用CGLIB这种直接修改二进制码的方法帮你实现。
概念:
JoinPoint:连接点,在哪些个点上把代码加进去;
PointCut:相当于是JointPoint的一个集合;
Aspect:切面,简单理解为切面类;
Advice:加载切入点的逻辑,比如@Before,@After;
Target:织入到哪个对象中去,Target表示的就是那个对象;
Weave:织入