想对spring的AOP原理做一些深入了解,就先做了一些aop配置,从应用层面对切面有所感知。
基本概念:
1.Joinpoint(连接点):连接点就是你要拦截的点, spring只支持方法类型的连接点。所以连接点实际中就是某一个业务类的方法。
2.Pointcut(切入点):切入点是一种“位置”定义,是对连接点的描述,把一或多个连接点定义为一个切入点。
3.Advice(通知):切面中定义的一些方法,称为“通知”。
4.Aspect(切面): 是切入点和通知的组合,在哪些位置去做切入,并做反应。
5.Proxy(代理) :一个类被 AOP 织入增强后,就产生一个结果代理类
AOP有四种实现方式:手动方式,半自动方式,全自动方式,注解方式
写了一个demo来理解切入的流程:
定义通知类:
public class LogTest {
private Logger logger = Logger.getLogger(LogTest.class);
public void before() {
logger.info("这是LogTest类的before方法!");
}
/**后置增强方法*/
public void afterReturn() {
logger.info("这是LogTest类的afterReturn方法!");
}
/**后置异常增强方法*/
public void afterException() {
logger.info("这是LogTest类的afterException方法!");
}
/**最终增强方法*/
public void after() {
logger.info("这是LogTest类的after方法!");
}
/**环绕增强方法*/
public void around(ProceedingJoinPoint jp) {
logger.info("这是MyLogger类的around方法!");
}
}
连接点的bean:
public class AutoConfigService {
private Logger logger = Logger.getLogger(AutoConfigService.class);
public void add() {
logger.info("这是AutoConfigService类的add方法!");
}
}
现在在beans
<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" default-autowire="byName">
<aop:config>
<aop:pointcut expression="execution(* com.cainiao.arrow.autoconfig. add(..))" id="pointcut"/>
<aop:aspect ref="LogTest">
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:around method="around" pointcut-ref="pointcut"/>
<aop:after-returning method="afterReturn" pointcut-ref="pointcut"/>
<aop:after-throwing method="afterException" pointcut-ref="pointcut"/>
<aop:around method="around" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
执行之后,按照预期的流程执行:
这是LogTest类的before方法!
这是AutoConfigService类的add方法!
这是LogTest类的after方法!
场景:
1.日志类文件
其实并不局限于日志类,像项目里一些场景,很多servide的方法finally都会做相同的收集操作,这些方法就可以横向切出来
2.事务管理
调用方法前开启事务, 调用方法后提交关闭事务
3.缓存优化
第一次调用查询数据库,将查询结果放入内存对象, 第二次调用, 直接从内存对象返回
4.监控时间
一些中间件arsas之类可以做的更好,可以在本地测局部代码的时候用。
5.权限控制
总结:
(1)aop是一个很好的实用工具,项目中有很多点可以通过切面优化
(2)aop的实现需要进一步解读源码。