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/nongzihong/Spring-aop-xml


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM