SpringAOP的实现

本文详细介绍了如何使用Spring AOP实现方法增强,包括使用Spring接口、自定义AOP代理和注解三种方式。通过在UserService的CRUD操作中添加日志打印,展示了前置通知、后置通知以及环绕通知的实现过程,为实际开发中的日志管理和功能增强提供了参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备步骤

1、导包(使用AOP依赖的包)

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

2、接口及实现类准备

  • UserService接口
package indi.stitch.service;

public interface UserService {
    void add();
    void delete();
    void update();
    void retrieve();
}
  • UserServiceImpl实现类
package indi.stitch.service;

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

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

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

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

实现步骤

案例:为CRUD操作增加打印日志功能

实现方式一:使用Spring的接口
创建代理类,定义通知方法

  • MethodBeforeAdvice:前置增强接口
    参数:
    method:要执行的目标对象的方法
    args:目标方法参数
    target:目标对象
    方法:
    before:执行目标方法前自动调用
package indi.stitch.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class BeforeLog implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + target.getClass().getName() + "的" + method.getName() + "方法");
    }
}
  • AfterReturningAdvice:后置增强接口
    参数:
    returnValue:返回值
    method:执行完成的的目标对象的方法
    args:目标方法参数
    target:目标对象

    方法:
    afterReturning:方法执行完成返回后自动调用

package indi.stitch.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(method.getName() + "方法执行结束,返回值为:" + returnValue);
    }
}	

将Bean注册到Spring容器中
execution表达式参数说明:
execution(* indi.stitch.service.UserServiceImpl.*(…))

符号含义
execution()表达式主体
*表示返回值为任意类型
indi.stitch.service.UserServiceImpl指定的接口实现类
.*类中所有方法
(…)方法的参数
<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--头文件加入AOP命名空间-->
    <!--添加Bean依赖-->
    <bean id = "userService" class = "indi.stitch.service.UserServiceImpl" />
    <bean id = "beforeLog" class = "indi.stitch.log.BeforeLog" />
    <bean id = "afterLog" class = "indi.stitch.log.AfterLog" />

    <!--配置AOP:需要导入AOP的约束-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* indi.stitch.service.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut" />
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" />
    </aop:config>
</beans>

测试类

import indi.stitch.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationConfig.xml");
        UserService service = context.getBean("userService", UserService.class);
        service.add();
    }
}

测试结果
在这里插入图片描述

实现方式二:自定义AOP实现

自定义代理类和通知方法

package indi.stitch.diy;

public class DiyPointCut {

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

    public void after() {
        System.out.println("=================方法执行后=================");
    }
}

配置自定义切面类

<!--方式二,自定义切面类-->
    <bean id = "diy" class = "indi.stitch.diy.DiyPointCut" />
    <aop:config>
        <!--自定义切面,ref 要引用的类-->
        <aop:aspect ref = "diy" >
            <!--切入点,即要横向切入的类-->
            <aop:pointcut id="point" expression="execution(* indi.stitch.service.UserServiceImpl.*(..))"/>
            <!--通知,即要切入的方法-->
            <aop:before method="before" pointcut-ref="point" />
            <aop:after method="after" pointcut-ref="point" />
        </aop:aspect>
    </aop:config>

测试类

import indi.stitch.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationConfig.xml");
        UserService service = context.getBean("userService", UserService.class);
        service.add();
    }
}

测试结果
在这里插入图片描述

实现方式三:注解实现AOP

创建注解代理类

package indi.stitch.annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect // 标记这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* indi.stitch.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("=============方法执行前=============");
    }

    @After("execution(* indi.stitch.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("=============方法执行后=============");
    }

    // 在环绕增强中,我们可以给定一个参数,代表我们要获取代理切入的点
    @Around("execution(* indi.stitch.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("=============环绕前=============");
        System.out.println(pj.getSignature());
        Object proceed = pj.proceed();
        System.out.println("=============环绕后=============");
        System.out.println(proceed);
    }
}

xml配置注解代理类及注解支持

<!--方式三:注解实现AOP-->
    <bean id = "annotationPointCut" class="indi.stitch.annotation.AnnotationPointCut" />
    <!--开启注解支持-->
    <aop:aspectj-autoproxy />

测试类

import indi.stitch.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationConfig.xml");
        UserService service = context.getBean("userService", UserService.class);
        service.add();
    }
}

测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值