基于Spring的AOP快速实现通用日志打印

需求分析:针对Videoservice接口实现日志打印

三个核心包:
spring-aop:AOP核心功能,例如代理⼯⼚
aspectjweaver:简单理解,⽀持切⼊点表达式
aspectjrt:简单理解,⽀持aop相关注解

添加依赖,其他依赖包含在spring-context、spring-core中,不需要额外添加

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

定义service接口和实现类

VideoService接口:

import net.xdclass.sp.domain.Video;
public interface VideoService {
    int save(Video video);
    Video findById(int id);
}

VideoService实现类:

import net.xdclass.sp.domain.Video;
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();
    }
}

定义横切关注点

TimeHandler类:

import java.time.LocalDateTime;
//横切关注点
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());
    }
}

添加schema

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"

在这里插入图片描述

配置bean和aop

<bean id="timeHandler" class="net.xdclass.sp.aop.TimeHandler"/>
<bean id="videoService" class="net.xdclass.sp.service.VideoServiceImpl"/>

 <aop:config>
        <!--横切关注点-->
        <aop:aspect id="timeAspect" ref="timeHandler">
            <!--定义切入点表达式-->
            <aop:pointcut id="allMethodLogPointCut" expression="execution(* net.xdclass.sp.service.VideoService.*(..))"/>
            
            <!--配置前置通知和后置通知-->
            <aop:before method="printBefore" pointcut-ref="allMethodLogPointCut"/>
            <aop:after method="printAfter" pointcut-ref="allMethodLogPointCut"/>
        </aop:aspect>
    </aop:config>

运行主类测试:

public class App {
    public static void main(String [] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		VideoService  videoService = (VideoService)context.getBean("videoService");
        videoService.save(new Video());
        videoService.findById(33);
    }
}

定义一个横切关注点(对方法拦截后的处理,前置后置通知),在applicationContext.xml中配置bean(横切关注点的类和service实现类),配置aop(横切关注点下定义切入点表达式、配置前置通知和后置通知)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

豆浆两块钱

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

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

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

打赏作者

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

抵扣说明:

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

余额充值