Spring----AOP面向切面编程

本文详细介绍了Spring框架中AOP(面向切面编程)的实现方式,包括前置通知和后置通知的接口实现,以及如何通过XML配置来定义切点和通知,实现对特定方法的增强。

一.AOP

MethodBeforeAdvice   ----------前置通知需要实现的接口

AfterReturningAdvice  --------后置通知需要实现的接口

二.Schema-based实现步骤

public class MyBeforeAdvice implements MethodBeforeAdvice {
    @Override
    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
        System.out.println("执行前置通知");
    }
}

public class MyAfterAdvice implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object arg0, Method arg1,Object[] arg2, Object arg3) throws Throwable {
        System.out.println("执行后置通知");
    }
}

如果方法中有参数时:

注意:切点的配置<aop:pointcut expression="execution(* com.bjsxt.test.Demo.demo2(String,int)) and arg(name,id)" id="mypoint"/>

<?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">
<!-- 配置通知类对象,在切面中引入 -->
    <bean id="mybefore" class="com.bjsxt.advice.MyBeforeAdvice"></bean>
    <bean id="myafter" class="com.bjsxt.advice.MyAfterAdvice"></bean>
    <!-- 配置切面 -->
    <aop:config>
        <!-- 配置切点 -->
        <aop:pointcut expression="execution(* com.bjsxt.test.Demo.demo2())" id="mypoint"/>
        <!-- 通知 -->
        <aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/>
        <aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/>
    </aop:config>
    <!-- 配置 Demo 类,测试使用 -->
    <bean id="demo" class="com.bjsxt.test.Demo"></bean>
</beans>

public class Test {
    public static void main(String[] args) {
        // Demo demo = new Demo();
        // demo.demo1();
        // demo.demo2();
        // demo.demo3();
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        Demo demo = ac.getBean("demo",Demo.class);
        demo.demo1();
        demo.demo2();
        demo.demo3();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值