Spring中 aop的 xml配置(简单示例)

示例:

  aop,即面向切面编程,面向切面编程的目标就是分离关注点。

比如:小明(一位孩子)想吃苹果,首先得要有苹果,其次才能吃。那么妈妈负责去买水果,孩子负责吃,这样,既分离了关注点,也减低了代码的复杂程度

示例:

孩子类:

@Component
public class Child {
    
    public void eat(){
        System.out.println("小孩子吃苹果");
    }
    
}

妈妈类(切面类):

public class Mom {

    public void buy(){//前置通知
        System.out.println("买水果");
    }

    public void clear(){//后置通知
        System.out.println("收拾果核");
    }

}

 aop2.xml配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3        xmlns:context="http://www.springframework.org/schema/context"
 4        xmlns:p="http://www.springframework.org/schema/p"
 5        xmlns:util="http://www.springframework.org/schema/util"
 6        xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
 7        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">
 8 
 9     <!--目标对象 孩子类-->
10     <bean id="child" class="com.oukele.learning.aop0.Child"/>
11 
12     <!--切面类-->
13     <bean id="mom" class="com.oukele.learning.aop0.Mom"/>
14     <!--面向切面编程-->
15     <aop:config>
16         <!--定义切面-->
17         <aop:aspect ref="mom">
18             <!--定义切点-->
19             <aop:pointcut id="action" expression="execution(* *.*(..))"/>
20             <!-- 声明前置通知 (在切点方法被执行前调用)-->
21             <aop:before method="buy" pointcut-ref="action"/>
22             <!-- 声明后置通知 (在切点方法被执行后调用)-->
23             <aop:after method="clear" pointcut-ref="action"/>
24         </aop:aspect>
25     </aop:config>
26 
27 
28 </beans>

测试类:

public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("aop2.xml");
        Child child = (Child) context.getBean("child");
        child.eat();
    }
}

结果:

1 买水果
2 小孩子吃苹果
3 收拾果核

案例示例下载地址:https://github.com/oukele/Spring-aop-xml

原文地址:https://www.cnblogs.com/oukele/p/10143063.html