将动态代理应用于应用程序中的所有类

时间:2011-05-04 08:33:33

标签: java spring dependency-injection proxy dynamic-proxy

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

newInstance是:

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

请勿手动创建代理,使用Spring AOP创建日志代理。

创建一个简单的Aspect:

@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都将成为代理,并且将记录所有方法执行(至少是由接口支持的方法)。

  

BTW:跟踪方面包含在内   Ramnivas Laddad的 the free Chapter 10 AspectJ in Action