Spring实现Aop

  1. 导包
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

方式一:使用Spring的API接口

  • 日志的java文件
package com.kuang.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {

    // method:要执行的目标对象的方法
    // args: 参数
    // target: 目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");

    }
}

  • 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.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>
    
<!--    方式一:使用原生spring api接口-->
<!--    配置aop 导入aop的约束-->
    <aop:config>
<!--        切入点: expression:表达式 execution(要执行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>

<!--        执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    </aop:config>
</beans>
  • 测试类
import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest09 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        动态代理代理的是接口:注意点
        UserService userService = context.getBean("userService", UserService.class);
        userService.delete();
    }
}

方式二:自定义类
-再增加一个java日志文件

package com.kuang.log;


import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {

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

  • 自定义类
package com.kuang.div;

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

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


}

  • xml注册
<!--    方式二:自定义类-->
    <bean id="diy" class="com.kuang.div.DiyPointCut"/>

    <aop:config>
<!--        自定义切面, ref要引出的类-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:before method="befor" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
  • 测试类不变
    方式三:注解
  • 注解类
package com.kuang.div;
//方式三:使用注解方式实现AOP

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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 Annocationpointcut {
    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void befor(){
        System.out.println("=============方法执行前=========");
    }
    @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=============方法执行后=========");
    }
    //在环绕增强中,我们可以给定一个参数,代表我们要获取切入的点
    @Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");

        //执行方法
        Object proceed = jp.proceed();

        System.out.println("环绕后");
        System.out.println(proceed);
    }

}

  • xml注册
<!--    方式三-->
    <bean id="annocationpointcut" class="com.kuang.div.Annocationpointcut"/>
<!--    开启注释支持 JDK(默认 expose-proxy="false")  cglib(expose-proxy="true")-->
    <aop:aspectj-autoproxy expose-proxy="false"/>
</beans>
  • 测试不变
Spring框架提供了一种简单且强大的方式来实现面向切面编程(AOP)。下面是使用Spring实现AOP的步骤: 1. 添加依赖:在项目的构建文件(如Maven或Gradle)中添加Spring AOP的依赖项。 2. 创建切面类:创建一个Java类,该类包含要在目标方法执行前、执行后或抛出异常时执行的逻辑。这个类被称为切面类。 3. 定义切点:在切面类中,使用@Pointcut注解定义一个切点,它表示在哪些方法上应用切面逻辑。 4. 编写通知:在切面类中编写通知方法,通知方法定义了切点被触发时要执行的逻辑。Spring提供了几种类型的通知,例如@Before(前置通知)、@After(后置通知)、@AfterReturning(返回通知)和@AfterThrowing(异常通知)。 5. 配置AOP:将切面类配置为Spring的bean,并将其与目标对象关联起来。这可以通过XML配置文件或使用基于注解的配置来完成。 6. 测试:使用Spring容器创建目标对象的实例,并调用目标方法。你将看到切面逻辑会在切点处被触发执行。 这是一个简单的示例,演示了如何在Spring实现AOP: ```java // 切面类 @Aspect public class LoggingAspect { // 定义切点 @Pointcut("execution(* com.example.MyService.*(..))") public void myServiceMethods() {} // 前置通知 @Before("myServiceMethods()") public void beforeAdvice() { System.out.println("Before advice executed."); } // 后置通知 @AfterReturning("myServiceMethods()") public void afterReturningAdvice() { System.out.println("After returning advice executed."); } } // 配置文件中定义切面和目标对象的关联 <aop:aspectj-autoproxy/> <bean id="myService" class="com.example.MyService"/> <bean id="loggingAspect" class="com.example.LoggingAspect"/> // 测试 public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MyService myService = context.getBean(MyService.class); myService.doSomething(); } } ``` 这是一个简单的例子,展示了如何在Spring中使用AOP。你可以根据自己的需求扩展和定制切面逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值