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

本文介绍Spring AOP的应用,包括五种增强类型:前置通知、后置通知、环绕通知、异常抛出通知及引介通知。此外,还展示了如何通过XML配置实现AOP,涉及目标类、增强类、切点及代理的定义。

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

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> 

测试代码

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

学亮编程手记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值