一、概述。
上一篇博客講述了用註解的形式實現AOP現在講述另外一種AOP實現的方式利用XML來實現AOP。
二、代碼演示。
準備工作參照上一篇博客《菜鳥學習Spring——60s使用annotation實現簡單AOP》
目錄結構:
其實比起上一篇博客中用annotation來實現AOP的方式我們只要把SecurityHandler.java和配置文件applicationContext.xml更改爲下面內容就可以了。下面我把這兩個文件的代碼寫下來。
SecurityHandler.java
package com.tgb.spring; public class SecurityHandler{ private void checkSecurity(){ System.out.println("checkSecurity"); } }
applicationContext.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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <bean id="userManager" class="com.tgb.spring.UserManagerImpl" /> <bean id="securityHandler" class="com.tgb.spring.SecurityHandler"/> <aop:config> <aop:aspect id="securityAspect" ref="securityHandler"> <aop:pointcut id="addAddMethod" expression="execution(* com.tgb.spring.*.*(..))" /> <aop:before method="checkSecurity" pointcut-ref="addAddMethod" /> </aop:aspect> </aop:config> </beans>
效果圖:
三、總結。
XML實現的AOP對代碼沒有了侵入性並且能夠靈活的配置不用重新編譯。但是有個缺點就是配置文件太多了不好管理。