什么是aop:
aop 面向切面编程,起到拦截器的角色,比如有一个业务上线之后,想在这个业务运行时加上时间的打印
// 老旧的思路
void doTask(String parameter){
System.out.println("我开始了"+new Date().toLocalString);
xxxxx
xxxxx
xxxxxxx
}
这样的业务如果有十个 一百个 一千个呢?
这时候就可以使用aop.
aop的核心概念有以下几点
1、横切关注点
对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点
2、切面(aspect)
类是对物体特征的抽象,切面就是对横切关注点的抽象
3、连接点(joinpoint)
被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器
4、切入点(pointcut)
对连接点进行拦截的定义
5、通知(advice)
所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类
6、目标对象
代理的目标对象
7、织入(weave)
将切面应用到目标对象并导致代理对象创建的过程
8、引入(introduction)
在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段
···
aop怎样写:
首先需要引入org.aspectj:aspectjweaver.jar,有这个以来才能利用注解。
第一种利用注解
// 定义一个切面类
@Aspect
// 标记为组件 使spring运行时自动扫描
@Component
class TestPrint {
// 定义切点 这里@Ponitcut注解通常是一个正则表达式,这里可以写符合条件的哪些包或者拥有特定注解的方法
// 方法体内部空方法不影响切入点的定义
@Pointcut("execution(public * org.xxx..*.*Controller.*..))||@annotation(org.jeecg.common.aspect.annotation.AutoDict)")
public void excudeService() {}
// 定义 通知逻辑 这里的注解@Around() 代表通知操作 "excudeService()"表示切点的定义
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
//这里的入参ProceedingJoinPoint 代表着连接点即被切入的点 ProceedingJoinPoint继承joinPoint 并且暴露proceed()方法获取切点的对象。
System.out.println("我开始了"+new Date().toLocalString);
return pjp.proceed(); ;
}
// 这个方法给老xml用
public void timePrint() {
System.out.println("我开始了"+new Date().toLocalString);
}
}
第二种老的xml写法,定义一个aop.xml
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
// 定义拦截实体
<bean id="dotask" class="com.xxx.aop.taskServiceImpl" />
<bean id="timeHandler" class="com.xxx.aop.testPrint" />
// 定义操作过程
<aop:config>
// 定义一类aop处理
<aop:aspect id="time" ref="TestPrint ">
<aop:pointcut id="dotask" expression="execution(* com.xxx.aop.*(..))" />
<aop:before method="timePrint" pointcut-ref="addAllMethod" />
<aop:after method="timePrint" pointcut-ref="addAllMethod" />
</aop:aspect>
</aop:config>
</beans>
aspectjweaver相对于xml好控制 另有提供@Before @After增强注解方便自定义织入时机
···