spring.net aop 讲解

时间:2023-03-09 15:26:06
spring.net aop 讲解

spring.net aop几个术语:

切面:针对类

切点:针对方法

object.xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net" xmlns:aop="http://www.springframework.net/aop"> <object id="user" type="TestAop.User" ></object> <object id="newUser" type="TestAop.NewUser" ></object> <object id="advisor" type="TestAop.Advisor"></object> <aop:config>
<aop:advisor pointcut-ref="pointcut" advice-ref="advisor"/>
</aop:config> <object id="pointcut" type="Spring.Aop.Support.SdkRegularExpressionMethodPointcut, Spring.Aop">
<property name="pattern" value="TestAop.User.Whoami"/>
</object>
</objects>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TestAop
{
public class Advisor : AopAlliance.Intercept.IMethodInterceptor
{ public object Invoke(AopAlliance.Intercept.IMethodInvocation invocation)
{
NewUser newUser = new NewUser();
newUser.BeforeWhoami();
var result = invocation.Proceed();
newUser.AfterWhoami();
return result;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TestAop
{
public class NewUser
{
public void BeforeWhoami()
{
Console.WriteLine("I am before");
} public void AfterWhoami()
{
Console.WriteLine("I am after");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TestAop
{ public interface IUser
{
void Whoami();
}
public class User:IUser
{
public void Whoami()
{
Console.WriteLine("I am zhangwei");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TestAop
{
class Program
{
static void Main(string[] args)
{
Spring.Context.IApplicationContext context
= new Spring.Context.Support.XmlApplicationContext("objects.xml");
IUser user = context.GetObject("user") as IUser;
user.Whoami();
Console.ReadKey();
}
}
}

运行:

spring.net aop 讲解