AOP系列(二)——為合格目標對象建立代理

來源:互聯網
上載者:User

標籤: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系列(二)——為合格目標對象建立代理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.