zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringAOP编程-传统基于JDK代理的AOP开发

JDK代理编程AOP开发 基于 传统
2023-09-14 09:02:02 时间

1、spring的传统aop编程它支持的增强(advice)有五种:

1) 前置通知 目标方法执行前增强 org.springframework.aop.MethodBeforeAdvice 2) 后置通知
目标方法执行后增强 org.springframework.aop.AfterReturningAdvice
3) 环绕通知
4) 异常抛出通知
目标方法抛出异常后的增强 org.springframework.aop.ThrowsAdvice
5) 引介通知 在目标类中添加一些新的方法或属性

2、 基本jar包

1) bean
2) core
3) context
4) expression
5) aop
6)需要aop联盟的依赖jar包

这里写图片描述

3、编写目标(target)

这里写图片描述

4、增强(advice)

这里写图片描述

5、在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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 目标target -->
    <bean id="orderService" class="cn.nwtxxb.aop.OrderServiceImpl"></bean>
    <!-- 通知advice -->
    <bean id="orderServiceAdvice" class="cn.nwtxxb.aop.OrderHelper"></bean>
    <!-- 定义切点 pointcut -->
    <!-- <bean id="orderServicePointCut" class="org.springframework.aop.support.NameMatchMethodPointcut">
        <property name="mappedNames">
            <list>
                <value>add</value>
                <value>update</value>
            </list>
        </property>
    </bean>  -->
    <bean id="orderServicePointCut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
        <property name="pattern" value=".*Order"></property>
    </bean>
    <!-- 切面aspect=pointcut+advice -->
    <bean id="orderServiceAspect" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="advice" ref="orderServiceAdvice"/>
        <property name="pointcut" ref="orderServicePointCut"/>      
    </bean> 
    <!-- 代理 proxy -->
    <bean id="orderServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="orderService"/>
        <property name="interceptorNames" value="orderServiceAspect"/>
        <property name="proxyInterfaces" value="cn.nwtxxb.aop.IOrderService"/>
    </bean>
</beans> 

测试代码

这里写图片描述