spring的aop面向切面编程简单示例简介
aop是框架中的一个重要内容,是的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的降低,提高程序的可重用性,同时提高了开发的效率。
主要目的
将日志记录,性能统计,安全控制,事务处理,等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。
pom中依赖:
<!--切面依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.9.RELEASE</version> </dependency>
创建一个切面类
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import java.util.Arrays;
/** * 日志切面类 */ @Component//bean工厂生产实体类,为实体类起名默认 @Aspect//表示该类为切面类 可进行-----> 删除某一个记录 添加日志。 操作日志 事务! (1)开启事务 (2)提交事务 (3)事务回滚 public class LogAspect { @Before(value = "execution(* com.aaa.aop03.ArithmeticCalculatorImpl.*(..))")//相当于service //另外上面的*,第一个*表示方法作用范围及返回的数据,第二个表示是哪个包下面的,但是最好不要有连续 //多个,可以使用*.*简略表示是(* *(..)),不用写那麽多*,至于参数一个用一个点表示,多个用两个点表示,当然也可以不用谢 //@Before(value = "execution(public double com.*.*.*.div(int,int))")//相当于service public void before(JoinPoint joinPoint){ //JoinPoint joinPoint 切点 表示从那个地方进行添加日志信息,程序切入点 String name = joinPoint.getSignature().getName();//得到方法对象及名字 Object[] args = joinPoint.getArgs();//得到参数 System.out.println("AAA--->The "+name+" method begin with "+ Arrays.asList(args)); } @After(value = "execution(* *(..))") //后置通知 相当于finally 一定会执行 public void after(JoinPoint joinPoint){ System.out.println("finally该方法总会被执行"); }
//后置返回通知 他可以得到返回结果。相当于return @AfterReturning(value = "execution(* com.aaa.aop03.ArithmeticCalculatorImpl.*(..))",returning = "r") public void afterReturning(JoinPoint joinPoint,int r){ System.out.printf("============="); String name = joinPoint.getSignature().getName(); System.out.println("BBB--->The "+name+" method ends: "+r); }
//相当于catch(Exception e)//异常通知 只有发生异常时才会被执行。 @AfterThrowing(value = "execution(* *(..))",throwing = "e") public void afterThrowing(Exception e){ System.out.println(e.getMessage()); } }
注意:AfterReturning注解后面的属性returning表示得到程序运行结果,注意在使用时要注意数据类型上下文保持一致,否则这里不能获取到程序运行结果,而且该注解下的方法不会执行
=========================================================================
配置文件开启切面注解
<?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:mvc="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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--包扫描--> <context:component-scan base-package="com.ykq.aop.after"/>
<!--开启切面注解--> <mvc:aspectj-autoproxy /> </beans>
