標籤:aop 代理
接著上篇文章,我們將採用新的方式進行動態代理。
ObjectNameAutoProxyCreator建立代理
實現思路
根據設定檔中的配置,Spring容器會根據此配置,為合格對象建立代理。
具體代碼
設定檔
<?xml version="1.0"?><configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/> </sectionGroup> </configSections> <spring> <context> <resource uri="config://spring/objects"/> </context> <objects xmlns="http://www.springframework.net"> <object id="beforeAdvice" type="AOPExample.LogBeforeAdvice,AOPExample"/> <!--在容器中配置,必須的,以便在容器中可以根據尾碼名Service尋找到這個對象--> <object id="userService" type="AOPExample.UserService,AOPExample"/> <!--通過ObjectNameAutoProxyCreator自動建立AOP代理--> <object id="IServiceProxy" type="Spring.Aop.Framework.AutoProxy.ObjectNameAutoProxyCreator, Spring.Aop"> <property name="ObjectNames"> <list> <!--只要是對象的尾碼名為Service的,就會自動為它們建立代理--> <value>*Service</value> </list> </property> <property name="InterceptorNames"> <list> <value>beforeAdvice</value> </list> </property> </object> </objects> </spring> </configuration>
用戶端
class Program { static void Main(string[] args) { User enUser = new User() { Name ="Danny", Age=15 }; IApplicationContext context = ContextRegistry.GetContext(); IUserService userService = (IUserService)context.GetObject("userService"); userService.GetUserInfo(enUser); } }
總結
- 優點:在這個例子中Spring容器會為以名稱Service結尾的多個目標對象組建代理程式類。
- 優點:在設定檔中只需要配置一次,而不用為每個目標對象都配置一次。
- 優點:用戶端的代碼不用更改,調用的還是介面,而不是代理類。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
AOP系列(二)——為合格目標對象建立代理