1

我想将我创建的动态代理应用到属于我的应用程序的所有类。但是,我也希望能够使用依赖注入(Spring)而不是编写类似 MyDynamicProxy.newInstance(new Account()); 的东西。

newInstance 在哪里:

public static Object newInstance(Object object) {             
return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),new LoggingProxy(object));        
}  

如何将依赖注入和动态代理应用于我的应用程序中的所有类?

4

2 回答 2

1

不要手动创建代理,使用Spring AOP创建日志代理。

创建一个简单的方面:

@Aspect
public class LoggingAspect{

    private static final Logger log = Logger.getLogger(LoggingAspect.class);

    @Pointcut("execution(* *.*(..))")
    public void methodExecution(){
    }

    @Before("methodExecution()")
    public void logBeforeMethod(final JoinPoint joinPoint){
        log.trace("Entering method " + joinPoint.getSignature() + " with args "
            + Arrays.toString(joinPoint.getArgs()));
    }

}

现在在 Spring 中连接方面:

<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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


    <bean class="aspects.LoggingAspect" />
    <aop:aspectj-autoproxy />

</beans>

现在,您所有的 Spring Bean 都将成为代理,并且它们的所有方法执行(至少由接口支持的方法执行)都将被记录下来。

顺便说一句: Ramnivas Laddad在AspectJ in Action的免费第 10 章中介绍了跟踪方面

于 2011-05-04T09:14:43.853 回答
1

您可以尝试使用org.springframework.beans.factory.config.BeanPostProcessor.postProcessAfterInitialization(Object, String)并返回您的代理实例而不是原始 bean。

注意,如果它只是记录您所追求的,那么使用 Spring 的 AOP 支持可能会更简单,这将允许您在所有 Spring 托管 bean 上定义一个简单的日志记录方面。

于 2011-05-04T09:07:31.787 回答