Spring之AOP快速入门(xml配置)

相关阅读——Spring之AOP快速入门(注解)

1 官方AOP解释

AOP(Aspect Oriented Programming)称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想

个人理解的aop

用自己的话来说就比如一个人(A) 在排队,然后aop代理对象就相当于管理者,管理者就有权决定让他人(B)排任意位置的队,类比到程序里这个已经排队的人就是一个方法(目标对象)
而他人相当于切面对象;
管理者安排他人排队与否,如何排队就是配置织入(告诉框架哪些方法需要进行增强)

代码实现

目标对象(A)----要执行的方法

public class Target implements TargetInterface {


    @Override
    public void save() {
        System.out.println("排队ing-------");
    }
}

切面对象(B)----要切入目标对象的方法

public class Advice {
    public void before() {

        System.out.println("前面插队--------");
    }

    public void after() {
        System.out.println("后面插队--------");
    }

}

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 http://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="target" class="com.aop.jdk.Target"></bean>

<!--    切面对象:要切入目标对象的方法-->
    <bean id="advice" class="com.aop.jdk.Advice"></bean>

<!--   配置织入:告诉框架哪些方法是需要增强的-->
    <aop:config>
        <aop:aspect ref="advice">
        <aop:before method="before" pointcut="execution(public void com.aop.jdk.Target.save())"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AllTest {

    @Autowired
    private TargetInterface targetInterface;
    @Test
    public void test1(){
        targetInterface.save();
    }
}

运行结果
运行结果

一些理解说明

在这里插入图片描述
ps:!!!此图的D是advice!!!!!
要执行A,A声明了一个切点,切点位置在这个A的前面(before),要切入的切面对象是advice,切入的方法是before();为什么是before呢?因为A声明切点的那个标签有一个method="before",这个是根据advice类里的方法决定的。

在这里插入图片描述
环绕通知写法
在这里插入图片描述

谢谢阅读
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值