刚刚完成了一个c#的spring aop简单例子,是在mac下用Xamarin Studio开发的。代码如下:
接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoptest
{
public interface ISay
{
void Say (string name);
}
}
实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoptest
{
class MySay : ISay
{
public void Say(string name)
{
Console.WriteLine("fuck off" + name);
}
}
}
通知 Advice
using System;
using AopAlliance.Intercept;
namespace aoptest
{
public class MyInterceptor :IMethodInterceptor
{
public MyInterceptor ()
{
}
public object Invoke(IMethodInvocation invocation)
{
Console.Out.WriteLine("zch before invoke method");
object result = invocation.Proceed();
Console.Out.WriteLine("zch after invoke method");
return result;
}
}
}
配置文件
<?xml version="1.0" encoding="utf-8" ?>
<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'
xmlns:db="http://www.springframework.net/database"
xmlns:tx="http://www.springframework.net/tx"
default-autowire="byName" default-lazy-init="true">
<object id="aroundAdvice" type="aoptest.MyInterceptor" />
<object id="isay" type="Spring.Aop.Framework.ProxyFactoryObject">
<property name="Target">
<object id = "isayTarget" type="aoptest.MySay" />
</property>
<property name="InterceptorNames">
<list>
<value>aroundAdvice</value>
</list>
</property>
</object>
</objects>
</spring>
</configuration>
调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spring.Context.Support;
using Spring.Context;
using Spring.Aop.Framework;
namespace aoptest
{
class Program
{
static void Main (string[] args)
{
IApplicationContext ctx = ContextRegistry.GetContext();
ISay command = (ISay)ctx["isay"];
command.Say ("zch");
}
}
}
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/20965.html