十、实现AOP的三种方式

十、实现AOP的三种方式

实现AOP的三种方式:

项目结构:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hgj1ocdW-1662876611852)(spring.assets/image-20220911134301187.png)]

1、使用Spring原生接口

本例只演示两个原生接口:MethodBeforeAdviceAfterReturningAdvice

其余接口可自行到 org.springframework.aop 包下查看

UserService.java

package hom.wang.service;

public interface UserService {
    void add();
    //void delete(); // 只演示一个即可,剩下的忽略
    //void change();
    //void query();
}

UserServiceImpl.java

package hom.wang.service;
import org.springframework.stereotype.Service;

public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("增加数据!");
    }
}

BeforeLog implements MethodBeforeAdvice 原生接口

package hom.wang.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
 * Spring原生接口 MethodBeforeAdvice
 * 前置增强
 */
public class BeforeLog implements MethodBeforeAdvice {

    @Override
    public void before(Method method, // 要增强的方法
                       Object[] args, // 入参
                       Object target  // 目标对象
                      ) throws Throwable {
        System.out.println("【法一:实现Spring原生接口】" + 
                           target.getClass().getName() + "-的-" + 
                           method.getName() + "-方法即将被调用!");
    }
}

AfterLog implements AfterReturningAdvice 原生接口

package hom.wang.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

/**
 * Spring原生接口 AfterReturningAdvice
 * 后置增强
 */
public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, // 返回值
                               Method method, // 要增强的方法
                               Object[] args, // 入参
                               Object target // 目标对象
                              ) throws Throwable {
        System.out.println("【法一:实现Spring原生接口】" + 
                           target.getClass().getName() + 
                           "-的-" + method.getName() + 
                           "-方法执行完毕,返回值是-" + returnValue);
    }
}

applicationContext.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="userService2" class="hom.wang.service.UserServiceImpl"/>
    <bean id="beforeLog2" class="hom.wang.log.BeforeLog"/>
    <bean id="afterLog2" class="hom.wang.log.AfterLog"/>

    <!-- 配置AOP -->
    <!-- 方式一:使用Spring原生接口 -->
    <aop:config>
        <!-- 1、首先需要一个切入点(expression写execution表达式) -->
        <aop:pointcut id="logPointcut" 
                      expression="execution(* hom.wang.service.UserServiceImpl.*(..))"/>

        <!-- 2、执行环绕增强 -->
        <aop:advisor advice-ref="beforeLog2" pointcut-ref="logPointcut"/>
        <aop:advisor advice-ref="afterLog2" pointcut-ref="logPointcut"/>
    </aop:config>
    
</beans>

TestCode:

ApplicationContext xmlContext = 
    new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userServiceXml = xmlContext.getBean(UserService.class);
userServiceXml.add();

Result:

【法一:实现Spring原生接口】hom.wang.service.UserServiceImpl-的-add-方法即将被调用!
增加数据!
【法一:实现Spring原生接口】hom.wang.service.UserServiceImpl-的-add-方法执行完毕,返回值是-null

2、自定义切面

DiyPointCut.java

package hom.wang.diy;

public class DiyPointCut {

    public void before(){
        System.out.println("【法二:自定义切面】============before=============");
    }

    public void after(){
        System.out.println("【法二:自定义切面】============after=============");
    }
}

applicationContext.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 id="userService2" class="hom.wang.service.UserServiceImpl"/>
    <bean id="beforeLog2" class="hom.wang.log.BeforeLog"/>
    <bean id="afterLog2" class="hom.wang.log.AfterLog"/>

    <!-- 配置AOP -->
    <!-- 方式一:使用Spring原生接口 -->
    <aop:config>
        <!-- 1、首先需要一个切入点(expression写execution表达式) -->
        <aop:pointcut id="logPointcut" 
                      expression="execution(* hom.wang.service.UserServiceImpl.*(..))"/>

        <!-- 2、执行环绕增强 -->
        <aop:advisor advice-ref="beforeLog2" pointcut-ref="logPointcut"/>
        <aop:advisor advice-ref="afterLog2" pointcut-ref="logPointcut"/>
    </aop:config>

    <bean id="diy" class="hom.wang.diy.DiyPointCut"/>

    <!-- 方式二:自定义 -->
    <aop:config>
        <!-- 自定义切面:ref要切入的类 -->
        <aop:aspect ref="diy">
            <!-- 切入点 -->
            <aop:pointcut id="diyPointcut" 
                          expression="execution(* hom.wang.service.UserServiceImpl.*(..))"/>
            <!-- 通知 -->
            <aop:before method="before" pointcut-ref="diyPointcut"/>
            <aop:after-returning method="after" pointcut-ref="diyPointcut"/>
        </aop:aspect>
    </aop:config>
    
</beans>

TestCode:

ApplicationContext xmlContext = 
    new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userServiceXml = xmlContext.getBean(UserService.class);
userServiceXml.add();

Result:

【法一:实现Spring原生接口】hom.wang.service.UserServiceImpl-的-add-方法即将被调用!
【法二:自定义切面】============before=============
增加数据!
【法二:自定义切面】============after=============
【法一:实现Spring原生接口】hom.wang.service.UserServiceImpl-的-add-方法执行完毕,返回值是-null

3、使用注解

详细注解实现可参阅 六、aspectJ框架实现AOP(注解)

AnnotationPointCut.java

package hom.wang.diy;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

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

    @Pointcut("execution(* hom.wang.service.UserServiceImpl.*(..))")
    public void pointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("【法三:使用注解】======方法执行前(注解实现)=====");
    }

    @AfterReturning("pointcut()")
    public void afterReturning(){
        System.out.println("【法三:使用注解】======方法返回后(注解实现)======");
    }
}

applicationContext.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 id="userService2" class="hom.wang.service.UserServiceImpl"/>
    <bean id="beforeLog2" class="hom.wang.log.BeforeLog"/>
    <bean id="afterLog2" class="hom.wang.log.AfterLog"/>

    <!-- 配置AOP -->
    <!-- 方式一:使用Spring原生接口 -->
    <aop:config>
        <!-- 1、首先需要一个切入点(expression写execution表达式) -->
        <aop:pointcut id="logPointcut" 
                      expression="execution(* hom.wang.service.UserServiceImpl.*(..))"/>

        <!-- 2、执行环绕增强 -->
        <aop:advisor advice-ref="beforeLog2" pointcut-ref="logPointcut"/>
        <aop:advisor advice-ref="afterLog2" pointcut-ref="logPointcut"/>
    </aop:config>

    <!-- 方式二:自定义 -->
    <bean id="diy" class="hom.wang.diy.DiyPointCut"/>

    <aop:config>
        <!-- 自定义切面:ref要切入的类 -->
        <aop:aspect ref="diy">
            <!-- 切入点 -->
            <aop:pointcut id="diyPointcut" 
                          expression="execution(* hom.wang.service.UserServiceImpl.*(..))"/>
            <!-- 通知 -->
            <aop:before method="before" pointcut-ref="diyPointcut"/>
            <aop:after-returning method="after" pointcut-ref="diyPointcut"/>
        </aop:aspect>
    </aop:config>

    <!-- 方式三:使用注解 -->
    <!-- 开始AOP注解支持
		( 
                默认 JDK(proxy-target-class="false")
				CGLIB(proxy-target-class="true")
   		) -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <bean class="hom.wang.diy.AnnotationPointCut"/>
</beans>

TestCode:

ApplicationContext xmlContext = 
    new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userServiceXml = xmlContext.getBean(UserService.class);
userServiceXml.add();

Result:

【法一:实现Spring原生接口】hom.wang.service.UserServiceImpl-的-add-方法即将被调用!
【法二:自定义切面】============before=============
【法三:使用注解】======方法执行前=====
增加数据!
【法三:使用注解】======方法返回后======
【法二:自定义切面】============after=============
【法一:实现Spring原生接口】hom.wang.service.UserServiceImpl-的-add-方法执行完毕,返回值是-null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

纯纯的小白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值