Spring.Net之前建议不工作

时间:2010-09-22 12:39:40

标签: aop spring.net

我正在尝试使用Spring.Net实现一个非常基本的建议,它只是将一些信息输出到控制台。以下是spring配置的相关部分:

  <!-- Before Advice: Method Logging -->
  <object id="methodLoggingBeforeAdvice"
     type="Ch.Test.AddressBook.Common.Advice.MethodLoggingBeforeAdvice" />

  <!-- Program Proxy w/ Advice Applied -->
  <object id="programProxy"
     type="Spring.Aop.Framework.ProxyFactoryObject">
    <property name="target" ref="programProxyTarget" />
    <property name="interceptorNames">
      <list>
        <value>methodLoggingBeforeAdvice</value>
      </list>
    </property>
  </object>

  <!-- Target, which the advice is applied to -->
  <object id="programProxyTarget"
     type="Ch.Test.AddressBook.Ui.ConsoleUi.Program">
    <constructor-arg ref="repository"/>
  </object>

以下是建议:

public class MethodLoggingBeforeAdvice : IMethodBeforeAdvice
{

    public void Before(MethodInfo method, Object[] args, Object target)
    {
        // Log method start
        Console.Out.WriteLine(
           "MethodLoggingBeforeAdvice: Entering method '"
           + method.Name + "'");

        // Log method arguments
        for (int i = 0; i < args.Length; i++)
        {
            Console.Out.WriteLine("MethodLoggingBeforeAdvice: Argument " + (i + 1)
               + " - " + args[0].ToString());
        }
    }
}

一切都很好,应用程序正在运行,Program类被实例化并调用方法,但是没有来自通知的输出。我似乎无法弄明白为什么......提前谢谢!

2 个答案:

答案 0 :(得分:2)

我觉得自己很蠢。

我发布的代码没问题。问题是初始化对象。这是我用过的:

var program = (Program)ContextRegistry.GetContext().GetObject("program");
program.StartUp();

我实际上应该已经获取了使用该建议的programProxy-Object:

var program = (Program)ContextRegistry.GetContext().GetObject("programProxy");
program.StartUp();

答案 1 :(得分:2)

您还可以使用匿名内部对象,这样您就不会意外地获得未经修改的对象:

  <!-- Before Advice: Method Logging -->
  <object id="methodLoggingBeforeAdvice"
     type="Ch.Test.AddressBook.Common.Advice.MethodLoggingBeforeAdvice" />

  <!-- Program Proxy w/ Advice Applied using an anonymous inner object-->
  <object id="program"
     type="Spring.Aop.Framework.ProxyFactoryObject">
    <property name="target">
       <object type="Ch.Test.AddressBook.Ui.ConsoleUi.Program">
           <constructor-arg ref="repository"/>
        </object>
    </property>
    <property name="interceptorNames">
      <list>
        <value>methodLoggingBeforeAdvice</value>
      </list>
    </property>
  </object>