当前位置: 移动技术网 > IT编程>开发语言>Java > Spring之AOP快速入门(xml配置)

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

2020年07月12日  | 移动技术网IT编程  | 我要评论
1 官方AOP解释AOP(Aspect Oriented Programming)称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想个人理解的aop用我自己的话来说就比如一个人(A) 在排队,然后这个人有权决定是否让别人(B)插队,类比到程序里这个人就是一个方法(目标对象)而别人相当于切面对象;是否决定让别人插队就是配置织入(告诉框架哪些方法需要进行增强)代码实现目标对象(A)----要执行的方法publi

相关阅读——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类里的方法决定的。

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

谢谢阅读

本文地址:https://blog.csdn.net/weixin_44376261/article/details/107252938

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网