Spring整合AspectJ基于XML实现AOP

Spring整合AspectJ实现AOP

前面我们已经学习了Spring AOP。那我们为什么还需要学习AspectJ,因为AspectJ 更为简单,更加方便。但是在我们的开发中我们不太使用Spring自身的对AOP的实现,更加建议使用AspectJ方式来开发AOP。

介绍

  • AspectJ是一个基于Java语言的AOP框架
  • Spring2.0以后新增了对AspectJ切点表达式支持
  • @AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面
    新版本Spring框架,建议使用AspectJ方式来开发AOP
  • 主要用途:自定义开发
    AspectJ 是一个面向切面的框架,他定义了 AOP 的一些语法,有一个专门的字节码生成器来生成遵守 java 规范的 class 文件。AspectJ 的通知类型不仅包括我们之前了解过的四种通知:前置通知、后置通知、环绕通知和异常通知,而且还多出一种最终通知即无论程序是否正常执行,最终通知的代码会得到执行。

切入点表达式

AspectJ最强大的地方在于他的切入点表达式:

  1. execution() 用于描述方法(掌握)
    语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)

     修饰符,一般省略
     	public		公共方法
     	*			任意
     返回值,不能省略
     	void			返回没有值
     	String		返回值字符串
     	* 			任意
     包,[省略]
     	com.itheima.crm			固定包
     	com.itheima.crm.*.service	crm包下面子包任意 (例如:com.itheima.crm.staff.service)
     	com.itheima.crm..			crm包下面的所有子包(含自己)
     	com.itheima.crm.*.service..	crm包下面任意子包,固定目录service,service目录任意包
     类,[省略]
     	UserServiceImpl			指定类
     	*Impl					以Impl结尾
     	User*					以User开头
     	*						任意
     方法名,不能省略
     	addUser					固定方法
     	add*						以add开头
     	*Do						以Do结尾
     	*						任意
     (参数)
     	()						无参
     	(int)						一个整型
     	(int ,int)					两个
     	(..)						参数任意
     throws ,可省略,一般不写。
    

    综合1

     execution(* com.itheima.crm.*.service..*.*(..))
    

    综合2

     <aop:pointcut expression="execution(* com.itheima.*WithCommit.*(..)) || 
                               execution(* com.itheima.*Service.*(..))" id="myPointCut"/>
    
  2. within:匹配包或子包中的方法(了解)

     within(com.itheima.aop..*)
    
  3. this:匹配实现接口的代理对象中的方法(了解)

     this(com.itheima.aop.user.UserDAO)
    
  4. target:匹配实现接口的目标对象中的方法(了解)

     target(com.itheima.aop.user.UserDAO)
    
  5. args:匹配参数格式符合标准的方法(了解)

     args(int,int)
    
  6. bean(id) 对指定的bean所有的方法(了解)

     bean('userServiceId')
    

AspectJ 通知类型

  • aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。
  • aspectj 通知类型,只定义类型名称。已经方法格式。
  • 个数:6种,知道5种,掌握1种。
    • before:前置通知(应用:各种校验)
      在方法执行前执行,如果通知抛出异常,阻止方法运行
    • afterReturning:后置通知(应用:常规数据处理)
      • 方法正常返回后执行,如果方法中抛出异常,通知无法执行
        必须在方法执行后才执行,所以可以获得方法的返回值。
    • around:环绕通知(应用:十分强大,可以做任何事情)
      • 方法执行前后分别执行,可以阻止方法的执行
        必须手动执行目标方法
    • afterThrowing:抛出异常通知(应用:包装异常信息)
      • 方法抛出异常后执行,如果方法没有抛出异常,无法执行
    • after:最终通知(应用:清理现场)
      • 方法执行完毕后执行,无论方法中是否出现异常
环绕
try{
     //前置:before
    //手动执行目标方法
    //后置:afterRetruning
} catch(){
    //抛出异常 afterThrowing
} finally{
    //最终 after
}

AspectJ和aopalliance通知的区别:
AOP联盟的通知类型具有特性接口,必须实现,从而确定方法名称,而AspectJ的通知类型只定义了类型名称和方法格式,这意味着,我们的切面不需要实现任何方法!!!。

xml中的配置:
在这里插入图片描述
相关的类:
在这里插入图片描述
然后我们可以简单看看两个类的内部实现,就只可以知道是怎么去执行通知的了。在这里插入图片描述

在这里插入图片描述

基于XML整合AspectJ

首先pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cc.study</groupId>
    <artifactId>spring-study</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!-- 4个核心(beans、core、context、expression) -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

目标类

目标类:接口 + 实现

public interface UserService {

    public void addUser();
	public void updateUser();
	public void deleteUser();
}

public class UserServiceImpl implements UserService {
    @Override
    public void addUser() {
        System.out.println("addUser()");
    }

    @Override
    public void updateUser() {
        System.out.println("updateUser()");
    }

    @Override
    public void deleteUser() {
        System.out.println("deleteUser()");
    }
}

切面类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 切面类,含有多个通知
 */
public class MyAspect {

    public void myBefore(JoinPoint joinPoint){
		System.out.println("前置通知 : " + joinPoint.getSignature().getName());
	}
	
	public void myAfterReturning(JoinPoint joinPoint,Object ret){
		System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
	}
	
	public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("前");
		//手动执行目标方法
		Object obj = joinPoint.proceed();
		
		System.out.println("后");
		return obj;
	}
	
	public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
		System.out.println("抛出异常通知 : " + e.getMessage());
	}
	
	public void myAfter(JoinPoint joinPoint){
		System.out.println("最终通知");
	}

}
Spring配置
前置通知
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       					   http://www.springframework.org/schema/beans/spring-beans.xsd
       					   http://www.springframework.org/schema/aop
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.cc.study.aspectj.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.cc.study.aspectj.MyAspect"></bean>
    <!-- 3 aop编程
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.cc.study.aspectj.UserServiceImpl.*(..))" id="myPointCut"/>

            <!-- 前置通知 
                <aop:before method="" pointcut="" pointcut-ref=""/>
                    method : 通知,及方法名
                    pointcut :切入点表达式,此表达式只能当前通知使用。
                    pointcut-ref : 切入点引用,可以与其他通知共享切入点。
                通知方法格式:public void myBefore(JoinPoint joinPoint){
                    参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等
                例如:
            -->
            <aop:before method="myBefore" pointcut-ref="myPointCut"/>
        </aop:aspect>
    </aop:config>

</beans>


测试

 @Test
    public void demo01(){
        String xmlPath = "aspectj.xml";
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();
        userService.updateUser();
        userService.deleteUser();
    }

在这里插入图片描述

后置通知
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       					   http://www.springframework.org/schema/beans/spring-beans.xsd
       					   http://www.springframework.org/schema/aop
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.cc.study.aspectj.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.cc.study.aspectj.MyAspect"></bean>
    <!-- 3 aop编程
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.cc.study.aspectj.UserServiceImpl.*(..))" id="myPointCut"/>
            <!-- 2.后置通知  ,目标方法后执行,获得返回值
                <aop:after-returning method="" pointcut-ref="" returning=""/>
                    returning 通知方法第二个参数的名称
                通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
                    参数1:连接点描述
                    参数2:类型Object,参数名 returning="ret" 配置的
                例如:
               -->
            <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
        </aop:aspect>
    </aop:config>

</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:aop="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/aop
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.cc.study.aspectj.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.cc.study.aspectj.MyAspect"></bean>
    <!-- 3 aop编程
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.cc.study.aspectj.UserServiceImpl.*(..))" id="myPointCut"/>

            <!-- 3 环绕通知
                <aop:around method="" pointcut-ref=""/>
                通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
                    返回值类型:Object
                    方法名:任意
                    参数:org.aspectj.lang.ProceedingJoinPoint
                    抛出异常
                执行目标方法:Object obj = joinPoint.proceed();
                例如:
                -->
            <aop:around method="myAround" pointcut-ref="myPointCut"/>
        
        </aop:aspect>
    </aop:config>

</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:aop="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/aop
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.cc.study.aspectj.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.cc.study.aspectj.MyAspect"></bean>
    <!-- 3 aop编程
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.cc.study.aspectj.UserServiceImpl.*(..))" id="myPointCut"/>

            <!-- 4 抛出异常
                <aop:after-throwing method="" pointcut-ref="" throwing=""/>
                    throwing :通知方法的第二个参数名称
                通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
                    参数1:连接点描述对象
                    参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
                例如:
                -->
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
      
        </aop:aspect>
    </aop:config>

</beans>


然后改一下updateUser方法:

    @Override
    public void updateUser() {
        int i = 1 / 0;
        System.out.println("updateUser()");
    }

在这里插入图片描述

最终通知
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       					   http://www.springframework.org/schema/beans/spring-beans.xsd
       					   http://www.springframework.org/schema/aop
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.cc.study.aspectj.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.cc.study.aspectj.MyAspect"></bean>
    <!-- 3 aop编程
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.cc.study.aspectj.UserServiceImpl.*(..))" id="myPointCut"/>  
            <!-- 3.5 最终通知 -->
            <aop:after method="myAfter" pointcut-ref="myPointCut"/>
        </aop:aspect>
    </aop:config>

</beans>


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值