[SSM]Spring面向切面编程AOP

目录

十五、面向切面编程AOP

15.1AOP介绍

15.2AOP的七大术语

15.3切点表达式

15.4使用Spring的AOP

15.4.1准备工作

15.4.2基于AspectJ的AOP注解式开发

15.4.3基于XML配置方式的AOP(了解)

15.5AOP的实际案例:事务处理

15.6AOP的实际案例:安全日志


十五、面向切面编程AOP

  • IoC使软件组件松耦合。AOP让你能够捕捉系统中经常使用的功能,把它转化为组件。

  • AOP(Aspect Oriented Programming):面向切面编程。

  • AOP是对OOP(面向对象编程)的补充延伸。

  • AOP底层使用的就是动态代理来实现的。

  • Spring的AOP使用的动态代理是:JDK动态代理+CGLIB动态代理技术。Spring在这两种动态代理中灵活切换,如果是代理接口,会默认使用JDK动态代理,如果要代理某个类,这个类没有实现接口,就会切换使用CGLIB。当然,你也可以强制通过一些配置让Spring只使用CGLIB。

15.1AOP介绍

  • 一般一个系统当中都会有一些系统服务,例如:日志、事务管理、安全等。这些系统服务被称为:交叉业务。

  • 这些交叉业务几乎是通用的,不管你是做银行账户转账,还是删除用户数据。日期、事务管理、安全,这些都是需要的。

  • 如果在每一个业务处理过程中,都掺杂这些交叉业务代码进去的话,存在两方面问题:

    • 第一:交叉业务代码在多个业务流程中反复出现,显然这个交叉业务代码没有得到复用,并且修改这些交叉业务代码的话,需要修改多处。

    • 第二:程序员无法专注核心业务代码的编写,在编写核心业务代码的同时还需要处理这些交叉业务。

  • 使用AOP可以很轻松的解决这些问题。

  • 用一句话总结AOP:将与核心业务无关的代码独立的抽取出来,形成一个独立的组件,然年以横向交叉的方式应用到业务流程当中的过程被称为AOP。

  • AOP的优点:

    • 代码复用性增强。

    • 代码易维护。

    • 使开发者更关注业务逻辑。

15.2AOP的七大术语

  • 连接点 Joinpoint

    • 在程序的整个执行流程中,可以织入切面的位置。方法的执行前后,异常抛出之后的位置。

  • 切点 Pointcut

    • 在程序执行流程中,真正注入切面的方法。(一个切点对应多个连接点)

  • 通知 Advice

    • 通知又叫做增强,就是具体你要织入的代码。

    • 通知包括:

      • 前置通知

      • 后置通知

      • 环绕通知

      • 异常通知

      • 最终通知

  • 切面 Aspect

    • 切点+通知就是切面

  • 织入 Weaving

    • 把通知应用到目标对象上的过程。

  • 代理对象 Proxy

    • 一个目标对象被织入通知后产生的新对象。

  • 目标对象 Target

    • 被织入通知的对象。

 

 

15.3切点表达式

  • 切点表达式用来定义通知(Advice)往哪些方法上切入。

  • 切入点表达式语法格式:

execution([访问控制权限修饰符] 返回值类型 [全限定类名] 方法名(形式参数列表) [异常])
  • 访问控制权限修饰符:

    • 可选项

    • 没写就是4个权限都包括

    • 写public就表示只包括公开的方法

  • 返回值类型:

    • 必填项

    • *表示返回值类型任意

  • 全限定类名:

    • 可选项

    • 两个点".."代表当前包以及子包下的所有类

    • 省略时表示所有的类

  • 方法名:

    • 必填项

    • *表示所有方法

    • set*表示所有的set方法

  • 形式参数列表:

    • 必填项

    • ()表示没有参数的方法

    • (..)参数类型和个数随意的方法

    • (*)只有一个参数的方法

    • (*,String)第一个参数类型随意,第二个参数是String的

  • 异常:

    • 可选项

    • 省略时表示任意异常类型

execution(public * com.hhb.service.*.delete*(..))
  • service包下所有类中以delete开始的所有方法

execution(* com.hhb.mall..*(..))
  • mall包下所有的类的所有的方法

execution(* *(..))
  • 所有类的所有方法

15.4使用Spring的AOP

  • Spring对AOP的实现包括以下3种方式:

    • 第一种方式:Spring框架结合AspectJ框架实现的AOP,基于注解开发。

    • 第二种方式:Spring框架结合AspectJ框架实现的AOP,基于XML方式。

    • 第三种方式:Spring框架自己实现的AOP,基于XML配置方式。

  • 实际开发中,都是Spring+AspectJ来实现AOP,所有重点学习第一种和第二种方式。

  • 什么时AspectJ?

    • Eclipse组织的一个支持AOP的框架,AspectJ框架是独立于Spring框架之外的一个框架,Spring框架用了AspectJ。

15.4.1准备工作
  • 使用Spring+AspectJ的AOP需要引入的依赖如下:

<dependencies>
        <!--spring-context依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.3</version>
        </dependency>
        <!--spring-aspects依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>6.0.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • Spring配置文件中添加context命名空间和aop命名空间

<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
​
</beans>
15.4.2基于AspectJ的AOP注解式开发

第一步:定义目标类以及目标方法

package com.hhb.service;
​
import org.springframework.stereotype.Service;
​
@Service("userService")
public class UserService {//目标类
​
    public void login() {//目标方法
        System.out.println("系统正在进行身份认证...");
    }
​
    public void logout() {
        System.out.println("退出系统...");
    }
}
package com.hhb.service;
​
import org.springframework.stereotype.Service;
​
@Service("orderService")
public class OrderService {//目标类
    //目标方法
    public void generate(){
        System.out.println("系统正在生成订单");
    }
}

第二步:定义切面类

package com.hhb.service;
​
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
​
@Component("logAspect")
@Aspect //切面类是需要使用@Aspect注解进行标注的
public class LogAspect {//切面
    //切面=通知+切点
    //通知就是增强,就是具体的要编写的增强代码
    //@Before注解标注的放法就是一个前置通知
    @Before("execution(* com.hhb.service..*(..))")
    public void 增强() {
        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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
​
    <!--组件扫描-->
    <context:component-scan base-package="com.hhb.service"/>
​
    <!--开启aspectj的自动代理-->
    <!--spring容器在扫描类的时候,查看该类上是否有@Aspect注解,如果有,则给这个类生成代理对象-->
    <!--
        proxy-target-class="true"  表示强制使用CGLIB动态代理
        proxy-target-class="false" 这是默认值,表示接口使用JDK动态代理,反之使用CGLIB动态代理。
    -->
    <aop:aspectj-autoproxy/>
</beans>

第四步:测试

@Test
public void testBefore() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    UserService userService = applicationContext.getBean("userService", UserService.class);
    userService.login();
    userService.logout();
​
    OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
    orderService.generate();
}

 

通知类型

  • 通知类型包括:

    • 前置通知:@Before目标方法执行之前的通知

    • 后置通知:@AfterReturning目标方法执行之后的通知

    • 环绕通知:@Around目标方法之前添加通知,目标方法之后添加通知

    • 异常通知:@AfterThrowing发生异常之后执行的通知

    • 最终通知:@After放在finally语句块中的通知

  • 测试

 
package com.hhb.service;
​
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
​
@Component("logAspect")
@Aspect
public class LogAspect {//切面
​
    @Before("execution(* com.hhb.service..*(..))")
    public void beforeAdvice() {
        System.out.println("前置通知");
    }
​
    @AfterReturning("execution(* com.hhb.service..*(..))")
    public void afterReturningAdvice() {
        System.out.println("后置通知");
    }
​
    @Around("execution(* com.hhb.service..*(..))")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("前环绕");
        //执行目标
        joinPoint.proceed();
        System.out.println("后环绕");
    }
​
    @AfterThrowing("execution(* com.hhb.service..*(..))")
    public void testAfterThrowing() {
        System.out.println("异常通知");
    }
    
    //最终通知(finally语句中执行的通知)
    @After("execution(* com.hhb.service..*(..))")
    public void testAfter() {
        System.out.println("最终通知");
    }
}

 

  • 当发生异常时

 

 

切面的先后执行顺序

  • 在业务中有多个切面的话,可以使用@Order注解来标识切面类,为@Order注解的value指定一个整数型的数字,数字越小,优先级越高。

package com.hhb.service;
​
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
​
@Component("logAspect")
@Aspect 
@Order(0)
public class LogAspect {//切面
​
    @Before("execution(* com.hhb.service..*(..))")
    public void beforeAdvice() {
        System.out.println("前置通知");
    }
​
    @AfterReturning("execution(* com.hhb.service..*(..))")
    public void afterReturningAdvice() {
        System.out.println("后置通知");
    }
​
    @Around("execution(* com.hhb.service..*(..))")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("前环绕");
        joinPoint.proceed();
        System.out.println("后环绕");
    }
​
    @AfterThrowing("execution(* com.hhb.service..*(..))")
    public void testAfterThrowing() {
        System.out.println("异常通知");
    }
​
    @After("execution(* com.hhb.service..*(..))")
    public void testAfter() {
        System.out.println("最终通知");
    }
}
package com.hhb.service;
​
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
​
@Aspect
@Component
@Order(1)//数字越小,优先级越高
public class SecurityAspect {
    @Before("execution(* com.hhb.service..*(..))")
    public void beforeAdvice() {
        System.out.println("前置通知,安全");
    }
}

 

通用切点

  • 之前的切点表达式缺点:

    • 切点表达式重复写了多次,没有得到复用。

    • 如果要修改切点表达式,需要修改多处,难维护。

  • 改进:将切点表达式单独的定义出来,在需要的位置引入即可。如下:

package com.hhb.service;
​
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
​
@Component("logAspect")
@Aspect //切面类是需要使用@Aspect注解进行标注的
@Order(0)
public class LogAspect {//切面
​
    //定义通用的切点表达式
    @Pointcut("execution(* com.hhb.service..*(..))")
    public void 通用切点() {
        //这个方法只是一个标记,方法名随意,方法体中也不需要写任何代码
    }
    
    /* @Before("execution(* com.hhb.service..*(..))")*/
    @Before("通用切点()")
    public void beforeAdvice() {
        System.out.println("前置通知");
    }
​
    @AfterReturning("通用切点()")
    public void afterReturningAdvice() {
        System.out.println("后置通知");
    }
​
    @Around("通用切点()")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("前环绕");
        joinPoint.proceed();
        System.out.println("后环绕");
    }
​
    @AfterThrowing("通用切点()")
    public void testAfterThrowing() {
        System.out.println("异常通知");
    }
​
    @After("通用切点()")
    public void testAfter() {
        System.out.println("最终通知");
    }
}

 

package com.hhb.service;
​
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
​
@Aspect
@Component
@Order(1)//数字越小,优先级越高
public class SecurityAspect {
    @Before("com.hhb.service.LogAspect.通用切点()")
    public void beforeAdvice() {
        System.out.println("前置通知,安全");
    }
}

连接点

@Before("通用切点()")
public void beforeAdvice(JoinPoint joinPoint) {
    System.out.println("前置通知");
    System.out.println("目标方法的方法名:"+joinPoint.getSignature().getName());
}
  • JoinPoint在Spring容器调用这个方法的时候传过来,我们可以直接使用。

  • joinPoint.getSignature(); 获取目标方法的签名。

  • 通过方法的签名可以获取到一个方法的具体信息。

全注解式开发AOP

  • 就是编写一个类,在这个类上面使用大量注解来代替spring的配置文件,如下Spring6Config:

package com.hhb.service;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
​
@Configuration//代替spring.xml文件
@ComponentScan({"com.hhb.service"})//组件扫描
@EnableAspectJAutoProxy(proxyTargetClass = true)//启用aspectj的自动代理机制
public class Spring6Config {
}
  • 测试程序发生变化

@Test
public void testNoXML(){
    ApplicationContext applicationContext=new AnnotationConfigApplicationContext(Spring6Config.class);
    OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
    orderService.generate();
}
15.4.3基于XML配置方式的AOP(了解)

第一步:编写目标类

package com.hhb.service;
​
public class UserService {//目标对象
​
    //目标方法
    public void logout() {
        System.out.println("系统正在退出...");
    }
}

第二步:编写切面类,并编写通知

package com.hhb.service;
​
import org.aspectj.lang.ProceedingJoinPoint;
​
public class TimerAspect {
    //通知
    public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        //前环绕
        long begin = System.currentTimeMillis();
        //目标
        joinPoint.proceed();
        //后环绕
        long end = System.currentTimeMillis();
        System.out.println("耗时" + (end - begin) + "毫秒");
    }
}

第三步:编写的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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
​
    <!--纳入spring ioc-->
    <bean id="userService" class="com.hhb.service.UserService"/>
    <bean id="timerAspect" class="com.hhb.service.TimerAspect"/>
​
    <!--aop的配置-->
    <aop:config>
        <!--切点表达式-->
        <aop:pointcut id="mypointcut" expression="execution(* com.hhb.service..*())"/>
        <!--切面=通知+切点-->
        <aop:aspect ref="timerAspect">
            <aop:around method="aroundAdvice" pointcut-ref="mypointcut"/>
        </aop:aspect>
    </aop:config>
</beans>

第四步:测试

15.5AOP的实际案例:事务处理

  • 项目中的事务控制是在所难免的,在一个业务流程当中,可能需要多条DML语句共同完成,为了保证数据的安全,这多条DML语句要么同时成功,要么同时失败,这就需要添加事务控制的代码。

  • 控制事务的代码就是和业务逻辑没有关系的”交叉业务“。可以使用AOP思想解决,可以把以上控制事务的代码作为环绕通知,切入到目标类的方法当中。

业务类

package com.hhb.service;
​
import org.springframework.stereotype.Service;
​
@Service
public class AccountService {
    public void transfer() {
        System.out.println("正在转账");
    }
​
    public void withdraw() {
        System.out.println("正在取款");
        String s=null;
        s.toString();
    }
}
package com.hhb.service;
​
import org.springframework.stereotype.Service;
​
@Service
public class OrderService {
    public void generate() {
        System.out.println("正在生成订单");
    }
​
    public void cancel() {
        System.out.println("订单已取消");
    }
}

事务切面类

package com.hhb.service;
​
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
​
@Component
@Aspect
public class TransactionAspect {
    //编程式事务解决方案
    @Around("execution(* com.hhb.service..*(..))")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) {
        try {
            //前环绕
            System.out.println("开启事务");
            //执行目标
            joinPoint.proceed();
            //后环绕
            System.out.println("提交事务");
        } catch (Throwable e) {
            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:context="http://www.springframework.org/schema/context"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
​
    <!--组件扫描-->
    <context:component-scan base-package="com.hhb.service"/>
    <!--启动自动代理-->
    <aop:aspectj-autoproxy/>
</beans>

测试

 

15.6AOP的实际案例:安全日志

  • 项目开发结束,已经上线了并且运行正常。客户提出新的需求:凡是在系统中进行修改、删除、新增操作的,都要把这个人记录下拉,因为这几个操作是属于危险行为。

业务类

package com.hhb.biz;
​
import org.springframework.stereotype.Service;
​
@Service
public class UserService {
​
    public void saveUser(){
        System.out.println("新增用户信息");
    }
​
    public void deleteUser(){
        System.out.println("删除用户信息");
    }
​
    public void modifyUser(){
        System.out.println("修改用户信息");
    }
​
    public void getUser(){
        System.out.println("获取用户信息");
    }
}
package com.hhb.biz;
​
import org.springframework.stereotype.Service;
​
@Service
public class VipService {
​
    public void saveVip(){
        System.out.println("新增会员信息");
    }
​
    public void deleteVip(){
        System.out.println("删除会员信息");
    }
​
    public void modifyVip(){
        System.out.println("修改会员信息");
    }
​
    public void getVip(){
        System.out.println("获取会员信息");
    }
}

切面类

package com.hhb.biz;
​
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
​
import java.text.SimpleDateFormat;
import java.util.Date;
​
@Component
@Aspect
public class SecurityLogAspect {
    @Pointcut("execution(* com.hhb.biz..save*(..))")
    public void savePointcut() {
    }
​
    @Pointcut("execution(* com.hhb.biz..delete*(..))")
    public void deletePointcut() {
    }
​
    @Pointcut("execution(* com.hhb.biz..modify*(..))")
    public void modifyPointcut() {
    }
​
    @Before("savePointcut()||deletePointcut()||modifyPointcut()")
    public void beforeAdvice(JoinPoint joinPoint) {
        //系统时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String nowTime = sdf.format(new Date());
        //输出日志信息
        System.out.println(nowTime + " XXX : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }
}

测试

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ja kar ta

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值