何为Aop
AOP(Aspect Oriented Programming)
意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一
维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,
也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。
利用AOP可以对业务逻辑的各个部分进行隔离,
从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,
同时提高了开发的效率。
名称概念
-
切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
-
通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
-
目标(Target):被通知对象。
-
代理(Proxy):向目标对象应用通知之后创建的对象。
-
切入点(PointCut):切面通知 执行的 “地点”的定义。
-
连接点(JointPoint):与切入点匹配的执行点。
Aop实现方式1 原生api接口实现
- log类(前置)
public class Log implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法"+",返回值为:"+returnValue);
}
}
<!--方式1 使用原生api接口-->
<aop:config>
<!--切入点 expression:表达式 execution:要执行的位置-->
<aop:pointcut id="pointcut" expression="execution(* com.xu.service.UserServiceImpl.*(..))"/>
<!-- 执行环绕增强-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
方式2 自定义类
- 自定义类diyPointCut
public class diyPointCut {
public void before(){
System.out.println("-------方法执行前------");
}
public void after(){
System.out.println("············方法后执行··········");
}
}
<!--方式2 自定义类-->
<bean id="diy" class="com.xu.diy.diyPointCut"/>
<aop:config>
<!--自定义切面 ref要指定的类-->
<aop:aspect ref="diy">
<!-- 切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.xu.service.UserServiceImpl.*(..))"/>
<!-- 通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
方式3 使用注解
- annotationPointCut类
@Component
@Aspect
public class annotationPointCut {
@Before("execution(* com.xu.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("~~~~方法执行前~~~~");
}
@After("execution (* com.xu.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("~~~~方法执行后~~~~");
}
@Around("execution (* com.xu.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint point) throws Throwable {
System.out.println("-----环绕前------");
//类似过滤
point.proceed();
System.out.println("-----环绕后------");
}
}
<context:component-scan base-package="com.xu.diy"/>
<!--开启注解 默认JDK执行 true为cglib-->
<aop:aspectj-autoproxy proxy-target-class="false"/>