6.7. 以编程方式创建@AspectJ代理

Spring Framework

6.7. 以编程方式创建@AspectJ代理

除了在配置文件中使用<aop:config>或者<aop:aspectj-autoproxy>来声明切面。 同样可以通过编程方式来创建代理来通知目标对象。关于Spring AOP API的详细介绍, 请参看下一章。这里我们重点介绍自动创建代理。

org.springframework.aop.aspectj.annotation.AspectJProxyFactory可以为一个或多个 @AspectJ切面通知的目标对象创建一个代理。该类的基本用法非常简单,示例如下。请参阅Javadoc获取更详细的信息。

// 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();