AOP的简单示例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Services;
using System.Runtime.Remoting.Activation;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            BusinessHandler handler = new BusinessHandler();
            handler.DoSomething();
        }
    }
}


//业务层的类和方法,让它继承自上下文绑定类的基类
[MyInterceptor]
public class BusinessHandler : ContextBoundObject
{
    [MyInterceptorMethod]
    public void DoSomething()
    {
        MessageBox.Show("执行了方法本身!");
    }
}


//贴在方法上的标签
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class MyInterceptorMethodAttribute : Attribute { }


//贴在类上的标签
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class MyInterceptorAttribute : ContextAttribute, IContributeObjectSink
{
    public MyInterceptorAttribute()
        : base("MyInterceptor")
    { }


    //实现IContributeObjectSink接口当中的消息接收器接口
    public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink next)
    {
        return new MyAopHandler(next);
    }
}


//AOP方法处理类,实现了IMessageSink接口,以便返回给IContributeObjectSink接口的GetObjectSink方法
public sealed class MyAopHandler : IMessageSink
{
    //下一个接收器
    private IMessageSink nextSink;
    public IMessageSink NextSink
    {
        get { return nextSink; }
    }
    public MyAopHandler(IMessageSink nextSink)
    {
        this.nextSink = nextSink;
    }


    //同步处理方法
    public IMessage SyncProcessMessage(IMessage msg)
    {
        IMessage retMsg = null;
        
        //方法调用消息接口
        IMethodCallMessage call = msg as IMethodCallMessage;


        //如果被调用的方法没打MyInterceptorMethodAttribute标签
        if (call == null || (Attribute.GetCustomAttribute(call.MethodBase, typeof(MyInterceptorMethodAttribute))) == null)
        {
            retMsg = nextSink.SyncProcessMessage(msg);
        }
        //如果打了MyInterceptorMethodAttribute标签
        else
        {
            MessageBox.Show("执行之前");
            retMsg = nextSink.SyncProcessMessage(msg);
            MessageBox.Show("执行之后");
        }


        return retMsg;
    }


    //异步处理方法(不需要)
    public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
    {
        return null;
    }
}
Spring AOP(面向切面编程)是Spring框架中的一个重要模块,它提供了一种在程序运行期间动态地将代码织入到现有代码中的方式。下面是一个简单的Spring AOP代码示例: 先,定义一个接口 `UserService`,其中包含了两个方法 `addUser` 和 `deleteUser`: ```java public interface UserService { void addUser(String username); void deleteUser(String username); } ``` 然后,创建一个实现该接口的类 `UserServiceImpl`: ```java public class UserServiceImpl implements UserService { @Override public void addUser(String username) { System.out.println("添加用户:" + username); } @Override public void deleteUser(String username) { System.out.println("删除用户:" + username); } } ``` 接下来,创建一个切面类 `LogAspect`,用于在方法执行前后打印日志: ```java @Aspect @Component public class LogAspect { @Before("execution(* com.example.UserService.*(..))") public void beforeMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("调用方法:" + methodName + ",参数:" + Arrays.toString(args)); } @AfterReturning("execution(* com.example.UserService.*(..))") public void afterMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); System.out.println("方法调用结束:" + methodName); } } ``` 最后,在Spring配置文件中配置相关的bean和切面: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="userService" class="com.example.UserServiceImpl"/> <bean id="logAspect" class="com.example.LogAspect"/> <aop:aspectj-autoproxy/> </beans> ``` 以上代码示例中,切面类 `LogAspect` 使用了 `@Aspect` 注解标识为一个切面,并通过 `@Before` 和 `@AfterReturning` 注解定义了前置通知和后置通知的逻辑。在Spring配置文件中,使用 `<aop:aspectj-autoproxy/>` 开启了自动代理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值