11.Spring之AOP

11、AOP

11.1、什么是AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可用性,同时提高了开发的效率。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NX6jFvd9-1642845718567)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220110082700533.png)]

11.2、AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或者功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
  • 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法
  • 目标(Target):被通知对象
  • 代理(Proxy):向目标对象应用通知之后创建的对象
  • 切入点(PointCut):切面通知执行的“地点”的定义
  • 连接点(JointPoint):与切入点匹配的执行点

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kbk4L6KI-1642845718569)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220110083300114.png)]

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tYZGQsH5-1642845718572)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220110083359945.png)]

即AOP在不改变原有代码的情况下,去增加新的功能

11.3、使用Spring实现AOP

【重点】使用 AOP织入,需要导入一个依赖包

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
</dependency>

方式一:使用Spring的API接口【主要SpringAPI接口实现】

方式二:自定义类实现AOP【主要是切面定义】

方式三:使用注解实现

代码show

代码结构图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bviaAJFv-1642845718573)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220122175411724.png)]

代码步骤:

1.创建新模块:spring-09-aop

2.diy包及类

public class DiyPointCut {
    void before() {
        System.out.println("===========方法执行前=========");
    }

    void after() {
        System.out.println("===========方法执行后=========");
    }
}
//方式三:使用注解方式实现aop
@Aspect//标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.gongyi.service.impl.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("--------方法执行前-----------");
    }

    @After("execution(* com.gongyi.service.impl.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("--------方法执行后-----------");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.gongyi.service.impl.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Object proceed = jp.proceed();//执行方法
        System.out.println("环绕后");

        /**
         * Signature signature = jp.getSignature();//获得签名
         System.out.println("signature:" + signature);
         System.out.println(proceed);
         */

    }
}

3.log包及类

public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //args:参数
    // target:目标对象
    @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 {
    //returnValue:返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
    }
}

4.service包及类

public interface UserService {
    void add();
    void delete();
    void update();
    void select();
}
public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("增加了一个用户");

    }

    @Override
    public void delete() {
        System.out.println("删除了一个用户");
    }

    @Override
    public void update() {
        System.out.println("更新了一个用户");
    }

    @Override
    public void select() {
        System.out.println("查询了一个用户");
    }
}

5.资源包-applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--注册bean-->
    <bean id="userService" class="com.gongyi.service.impl.UserServiceImpl"/>
    <bean id="log" class="com.gongyi.log.Log"/>
    <bean id="afterLog" class="com.gongyi.log.AfterLog"/>

    <!-- 方式三-->
    <bean id="annotationPointCut" class="com.gongyi.diy.AnnotationPointCut"/>
    <!--开启注解支持 JDK(默认:proxy-target-class="false"),cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy />

    <!--方式一:使用原生Spring API接口-->
    <!--配置AOP:需要导入AOP的约束-->
    <!-- <aop:config>
         &lt;!&ndash;切入点:expression:表达式,expression(要执行的位置! * * * * *)&ndash;&gt;
         <aop:pointcut id="pointcut" expression="execution(* com.gongyi.service.impl.UserServiceImpl.*(..))"/>

         &lt;!&ndash;执行环绕增加&ndash;&gt;
         <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
         <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
     </aop:config>-->
    <!-- 方式二:自定义类-->
    <!--<bean id="diy" class="com.gongyi.diy.DiyPointCut"/>
    <aop:config>
        &lt;!&ndash;自定义切面,ref要引用的类&ndash;&gt;
        <aop:aspect ref="diy">
            &lt;!&ndash;切入点&ndash;&gt;
            <aop:pointcut id="point" expression="execution(* com.gongyi.service.impl.UserServiceImpl.*(..))"/>
            &lt;!&ndash;通知&ndash;&gt;
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>-->


</beans>


6.测试类:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口:注意点
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}
/**
 * 遇到问题:
 * 1.warning no match for this type name: com.gongyi.serivice.UserServiceImpl [Xlint:invalidAbsoluteTypeName]
 * 原来:
 *  <aop:pointcut id="pointcut" expression="execution(* com.gongyi.serivice.UserServiceImpl.*(..))"/>
 *  修改:
 *   <aop:pointcut id="pointcut" expression="execution(* com.gongyi.serivice.*.*(..))"/>
 *   还有解决方法:
 *   1)把UserServiceImpl实现类放到impl包下,和老师不同是因为spring-aop版本不同
 *2.aop 环绕未出效果:
 *   只打印了:增加了一个用户
* 3.怪异现象:
 * <aop:pointcut id="point" expression="execution(* com.gongyi.service.impl.UserServiceImpl.*(..))"/>
 * 其中com.gongyi.service.impl.UserServiceImpl,手敲:impl包,报红
 * 直接复制粘贴类路径全称ok
 */

代码地址

彩蛋

1.想到AOP就想到代理模式

2.导入AOP约束的方式

1)输入<aop:config alt +enter自动补全

2)在头部信息中拷贝beans相关的配置,改为aop

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nPPCETVO-1642845718574)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220110085854918.png)]

3.学习aop的目的

1)了解如何使用

2)面试时有谈资(从AOP讲到动态代理)

4.aspect在idea中的图标

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OdIPeGUn-1642845718575)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220122180045927.png)]

问题记录

1.warning no match for this type name

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: warning no match for this type name: com.gongyi.serivice.UserServiceImpl [Xlint:invalidAbsoluteTypeName]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: warning no match for this type name: com.gongyi.serivice.UserServiceImpl [Xlint:invalidAbsoluteTypeName]

解决:【和老师schema改一致,老师的是复制beans修改的,我的是alt+enter导入的】

对比老师代码,发现schema导入错了

我的:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0TpiSKXW-1642845718576)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220111085920242.png)]

老师的:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-puhShhiT-1642845718577)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220111085849418.png)]

2.Caused by: org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 17; cvc-complex-type.2.4.c: 通配符的匹配很全面, 但无法找到元素 ‘aop:config’ 的声明。

解决:

https://www.springframework.org/schema/beans/spring-aop.xsd

改为:

https://www.springframework.org/schema/aop/spring-aop.xsd

3.execution中的UserServiceImplements不能点击进去,也不变色

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8uZybAdj-1642845718578)(D:\study\学习笔记\spring学习\11、AOP.assets\image-20220111085420571.png)]

解决:复制进去好了,不要手敲,在notepad++等ide中写好,复制到idea中即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值