AOP(Aspect Orient Programming),一般称为面向切面编程,作为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、日志、缓存等等。AOP实现的关键在于AOP框架自动创建的AOP代理,AOP代理主要分为静态代理和动态代理,静态代理的代表为AspectJ;而动态代理则以Spring AOP为代表。静态代理是编译期实现,动态代理是运行期实现,可想而知前者拥有更好的性能。本文主要介绍Spring AOP的两种代理实现机制,JDK动态代理和CGLIB动态代理。
静态代理是编译阶段生成AOP代理类,也就是说生成的字节码就织入了增强后的AOP对象;动态代理则不会修改字节码,而是在内存中临时生成一个AOP对象,这个AOP对象包含了目标对象的全部方法,并且在特定的切点做了增强处理,并回调原对象的方法。
Spring AOP中的动态代理主要有两种方式,JDK动态代理和CGLIB动态代理。JDK动态代理通过反射来接收被代理的类,并且要求被代理的类必须实现一个接口。JDK动态代理的核心是InvocationHandler接口和Proxy类。
如果目标类没有实现接口,那么Spring AOP会选择使用CGLIB来动态代理目标类。CGLIB(Code Generation Library),是一个代码生成的类库,可以在运行时动态的生成某个类的子类,注意,CGLIB是通过继承的方式做的动态代理,因此如果某个类被标记为final,那么它是无法使用CGLIB做动态代理的,诸如private的方法也是不可以作为切面的。
我们分别通过实例来研究AOP的具体实现。
直接使用Spring AOP
首先定义需要切入的接口和实现。为了简单起见,定义一个Speakable
接口和一个具体的实现类,只有两个方法sayHi()
和sayBye()
。
public interface Speakable { void sayHi(); void sayBye(); }
@Service public class PersonSpring implements Speakable { @Override public void sayHi() { try { Thread.currentThread().sleep(30); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("Hi!!"); } @Override public void sayBye() { try { Thread.currentThread().sleep(10); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("Bye!!"); } }
接下来我们希望实现一个记录sayHi()
和sayBye()
执行时间的功能。
定义一个MethodMonitor
类用来记录Method执行时间
public class MethodMonitor { private long start; private String method; public MethodMonitor(String method) { this.method = method; System.out.println("begin monitor.."); this.start = System.currentTimeMillis(); } public void log() { long elapsedTime = System.currentTimeMillis() - start; System.out.println("end monitor.."); System.out.println("Method: " + method + ", execution time: " + elapsedTime + " milliseconds."); } }
光有这个类还是不够的,希望有个静态方法用起来更顺手,像这样
MonitorSession.begin(); doWork(); MonitorSession.end();
说干就干,定义一个MonitorSession
public class MonitorSession { private static ThreadLocal<MethodMonitor> monitorThreadLocal = new ThreadLocal<>(); public static void begin(String method) { MethodMonitor logger = new MethodMonitor(method); monitorThreadLocal.set(logger); } public static void end() { MethodMonitor logger = monitorThreadLocal.get(); logger.log(); } }
万事具备,接下来只需要我们做好切面的编码,
@Aspect @Component public class MonitorAdvice { @Pointcut("execution (* com.deanwangpro.aop.service.Speakable.*(..))") public void pointcut() { } @Around("pointcut()") public void around(ProceedingJoinPoint pjp) throws Throwable { MonitorSession.begin(pjp.getSignature().getName()); pjp.proceed(); MonitorSession.end(); } }
如何使用?我用了spring boot,写一个启动函数吧。
@SpringBootApplication public class Application { @Autowired private Speakable personSpring; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { // spring aop System.out.println("******** spring aop ******** "); personSpring.sayHi(); personSpring.sayBye(); Sys