[Spring.Net]Aop with IMethodBeforeAdvice Sample

[Spring.Net]Aop with IMethodBeforeAdvice Sample

前言
前面兩篇分別介紹了Aop的原理,以及實驗性質的Nested AroundAdvice(請參考
[Spring.Net]Aop introduction–以performance log為例[Spring.Net]Aop with Nested AroundAdvice),這邊快速的紀錄一下BeforeAdvice該怎麼使用,因為與AroundAdvice有點不太一樣,在IMethodBeforeAdvice裡面,並沒有invocation.Proceed(),而是透過介面來決定Aop的時間點。

實作

  1. 實作Spring.Aop.IMethodBeforeAdvice這個介面;
  2. 在Before的方法裡面,處理自己想要作的事,以這邊的例子來說,用來記錄呼叫target的method時,傳入了哪些參數,參數的值與type分別為何。(也可以拿來當作Unit Test額外的Test Case來源)


參考程式碼

	public class BeforeAdviceForUnitTestCase : IMethodBeforeAdvice 
    {

        public void Before(System.Reflection.MethodInfo method, object[] args, object target)
        {
            StringBuilder logMessage = new StringBuilder();
            logMessage.Append("Target class : " + target.ToString() + Environment.NewLine);
            logMessage.Append("Method Name: " + method.Name + Environment.NewLine);

            if (args != null)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    logMessage.Append("parameter" + i.ToString() + " type:" + args[i].GetType().ToString() + Environment.NewLine);
                    logMessage.Append("parameter" + i.ToString() + @": " + args[i].ToString() + Environment.NewLine);
                }
            }
            else
            {
                logMessage.Append("no parameters" + Environment.NewLine);
            }
                
            
            GetLogger().Info(logMessage.ToString());
        }
        protected ILog GetLogger()
        {           
            ILog logger = LogManager.GetLogger("RollingFileAppender");
            return logger;
        }
    }

接著與前兩篇文章介紹的例子一樣,將此Aop module class,加入要使用的ProxyFactoryObject區塊的interceptorNames裡面:

	<!--該AOP用到哪一些Service,要加進去Property裡面,該Property是ref到哪一個Service object-->
    <object id="JoeyServiceWithAOP" type="Spring.Aop.Framework.ProxyFactoryObject" >
        <property name="target" ref="JoeyService" />
        <property name="interceptorNames">
            <list>                
                <value>beforeAdviceForUnitTestCase</value>                                
                <value>performanceLoggingAroundAdvice</value>                
            </list>
        </property>
    </object>


實際輸出的結果

2011-01-11 17:31:27,679 INFO Core.Aop.BeforeAdviceForUnitTestCase.Before(D:\Article Sample project\SpringWithAop\Core\Aop\BeforeAdviceForUnitTestCase.cs:30)
  Target class : Core.Service.JoeyService
Method Name: GetSomething
parameter0 type:System.DateTime
parameter0: 2011/1/11 下午 05:31:27
parameter1 type:System.Int32
parameter1: 9191

2011-01-11 17:31:27,740 INFO Core.Aop.PerformanceLoggingAroundAdvice.Invoke(D:\Article Sample project\SpringWithAop\Core\Aop\PerformanceLoggingAroundAdvice.cs:38)
  Target Type:Core.Service.JoeyService,Request Name: 'GetSomething',執行花費: 31 milliseconds .

 

結論
應該有許多其他的變化可以透過Aop的方式去達成,就待各位自行去發揮創意了。


blog 與課程更新內容,請前往新站位置:http://tdd.best/