跳到主要内容

程序化创建 @AspectJ 代理

ChatGPT-4o-mini 中英对照 Programmatic Creation of @AspectJ Proxies

除了通过使用 <aop:config><aop:aspectj-autoproxy> 在配置中声明切面外,还可以通过编程方式创建代理来建议目标对象。有关 Spring 的 AOP API 的完整细节,请参见 下一章。在这里,我们想要重点关注使用 @AspectJ 切面自动创建代理的能力。

您可以使用 org.springframework.aop.aspectj.annotation.AspectJProxyFactory 类为一个目标对象创建一个代理,该对象由一个或多个 @AspectJ 切面进行增强。这个类的基本用法非常简单,如以下示例所示:

// create a factory that can generate a proxy for the given target object
AspectJProxyFactory factory = new AspectJProxyFactory(targetObject);

// add an aspect, the class must be an @AspectJ aspect
// you can call this as many times as you need with different aspects
factory.addAspect(SecurityManager.class);

// you can also add existing aspect instances, the type of the object supplied
// must be an @AspectJ aspect
factory.addAspect(usageTracker);

// now get the proxy object...
MyInterfaceType proxy = factory.getProxy();
java

请参阅 javadoc 以获取更多信息。