天天看点

Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解

地址链接:

​使用完全注解开发实现AOP​​

上一篇写了如何使用注解实现Aop切面编程、这一篇使用xml方式实现aop切面编程。通过对比、可以有效看出两者之间的方便程度

1、创建两个类,增强类和被增强类,创建方法

1.1 被增强类Dog.java

对这个类里的方法进行增强

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 14:58
 */
public class Dog {

    public void show(){
        System.out.println("我是小狗旺财。。。。");
    }
}      

1.2 增强类DogProxy.java

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 14:59
 */
public class DogProxy {
    public void before(){
        System.out.println("我是提前执行的、我是一只黑色的小狗。。。。");
    }
}      

2、在 spring 配置文件中创建两个类对象

<!--创建对象-->
<bean id="dog" class="com.zyz.spring5.aopxml.Dog"></bean>
<bean id="dogProxy" class="com.zyz.spring5.aopxml.DogProxy"></bean>      

3、在 spring 配置文件中配置切入点

有关切入点、切面等术语的讲解。上一篇有专门的讲解。这里不在赘述。开头的链接

<!--配置增强-->
    <aop:config >
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.zyz.spring5.aopxml.Dog.show(..))"/>
        <!--配置切面-->
        <aop:aspect ref="dogProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"></aop:before>
        </aop:aspect>
    </aop:config>      

4、测试

@org.junit.Test
    public void testDemo2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Dog dog = context.getBean("dog", Dog.class);
        dog.show();

    }      

5、测试结果

Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解

6、后语

<?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"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--创建对象-->
    <bean id="dog" class="com.zyz.spring5.aopxml.Dog"></bean>
    <bean id="dogProxy" class="com.zyz.spring5.aopxml.DogProxy"></bean>

    <!--配置增强-->
    <aop:config >
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.zyz.spring5.aopxml.Dog.show(..))"/>
        <!--配置切面-->
        <aop:aspect ref="dogProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"></aop:before>
        </aop:aspect>
    </aop:config>


</beans>