Spring:AOP快速实现通用日志打印示例讲解(8)

本文通过五个步骤详细介绍了如何在Spring中使用AOP实现通用的日志打印功能,涉及Service接口和实现类定义、横切关注点、AOP约束配置、bean和aop配置以及测试。教程中强调了切入点表达式的重要性,提供了全方法匹配和指定方法匹配的示例。
摘要由CSDN通过智能技术生成

不懂的可以看上一章博文,分别讲解了动态代理和静态代理具体代码示例

  • 需求分析:针对Videoservice接口实现日志打印
  • 三个核心包
    • spring-aop:AOP核心功能,例如代理工厂
    • aspectjweaver:简单理解,支持切入点表达式
    • aspectjrt:简单理解,支持aop相关注解

引入相关包

<dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.6.11</version>
</dependency>
Step1:定义Service接口和实现类
/**
 * 视频对象
 */
public class Video {

    private int id;

    private String title;

    public Video(){}
}
public interface VideoService {

    int save(Video video);

    Video findById(int id);
}
public class VideoServiceImpl implements VideoService {
    public int save(Video video) {
        System.out.println("保存video");
        return 1;
    }

    public Video findById(int id) {
        System.out.println("根据id查询视频信息");
        return new Video();
    }
}
Step2:定义横切关注点
/**
 * 横切关注点
 */
public class TimeHandler {

    public void printBefore(){
        System.out.println("printBefore 日志 time="+ LocalDateTime.now().toString());
    }

    public void printAfter(){
        System.out.println("printAfter 日志 time="+ LocalDateTime.now().toString());
    }
}
Step3:添加schema AOP约束配置
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"
xmlns:aop="http://www.springframework.org/schema/aop"

在这里插入图片描述

Step4:配置bean和aop
    <bean id="timeHandler" class="net.jhclass.project.aop.TimeHandler"></bean>
    <bean id="viedoService" class="net.jhclass.project.service.VideoServiceImpl"></bean>
    <!--
    定义aop
    -->
    <aop:config>
        <!--
        配置横切关注点
        ref:引用横切关注点
        -->
        <aop:aspect id="timeAspect" ref="timeHandler">
            <!--切入点 表达式所有方法-->
            <aop:pointcut id="allMethodLogPointCut" expression="execution(* net.jhclass.project.service.VideoService.*(..))"/>
            <!--通知 具体通知方法名称-->
            <aop:before method="printBefore" pointcut-ref="allMethodLogPointCut"/>
            <aop:after method="printAfter" pointcut-ref="allMethodLogPointCut"/>
        </aop:aspect>
    </aop:config>

可以点开看一下,切入点表达式有没有写错

这里的表达式是全部方法,如果需要指定某个方法,可以这样写

            <aop:pointcut id="allMethodLogPointCut" expression="execution(* net.jhclass.project.service.VideoService.save*(..))"/>

在这里插入图片描述

Step5:测试

注释的地方没关系
在这里插入图片描述
以上的例子就是Spring的AOP配置例子,不复杂

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值