SpringAOP

一.简介

AOP(Aspect Oriented Programming):面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。

  • OOP引入封装、继承、多态等概念来建立一种对象层次结构
  • AOP则利用一种称为“横切”的技术,剖开对象内部,并将公共行为封装到可重用模块,从而减少重复代码,降低耦合。

二.SpringAOP术语

  • 通知(Advice)

        通知定义了切点处所要执行的程序代码以及执行时机

  • 连接点(Join point)

        连接点是在应用执行过程中满足切点范围的具体的点

  • 切点(Poincut)

        切点定义切面插入在哪些方法上,确定切面使用范围

  • 切面(Aspect)

        切面是指封装横切到系统功能的类,包含通知和切点

  • 织入(Weaving)

        织入是把切面插入到目标对象上

三.SpringAOP使用(xml的方式)

1.pom.xml依赖引入

        注意:Spring AOP默认使用aspectj来实现的

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.3.9</version> <!-- 替换为你需要的版本号 -->
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.3</version>
    </dependency>
</dependencies>

2.修改Spring配置文件的头部(因为要用到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">

3.在Spring配置文件中加入AOP切面配置

    <!--AOP配置根节点 -->
    <aop:config>
        <!--定义切点 -->
        <aop:pointcut expression="execution (*service.*.*(..) ) "
            id="pointcut"/>
        <!--定义切面 -->
        <aop:aspect ref="logService">
            <!--定义前置通知 -->
            <aop:before pointcut-ref="pointcut" method="writeLog"/>
        </aop:aspect>
    </aop:config>

4.新增一个日志记录服务类“LogService”,并配置到容器中

//日志服务
@Service
public class LogService {
    //记录日志
    private void writeLog (){
        system.out.println( "开始执行service,时间:"
                            +new Date ().toLocalestring () );
    }
}

5.需要在调用方法时记录传递参数、返回值以及执行结束时间,LogService修改

6.AOP配置修改

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值