简体   繁体   中英

Spring AOP - proxying object returned from method

In this example:

public class ConnectionPool {
  public java.sql.Connection getConnection() {
      ...
  }
}

@Bean
@Scope("singleton")
public ConnectionPool connectionPool(...) throws Exception {
    return new ConnectionPoolImpl(...);
}

I want to monitor calls to java.sql.Connection.close() on Connection objects returned from getConnection().

I tried adding @Lookup to the getConnection() method but it had no effect.

How do I get Spring to proxy the java.sql.Connection object?

You can create proxy for the ConnectionPool and return the proxy in the bean creation method

@Bean
@Scope("singleton")
public ConnectionPool connectionPool(...) throws Exception {
    ConnectionPoolImpl delegate = new ConnectionPoolImpl(...);
    ConnectionPoolCallHandler callHandler = new ConnectionPoolCallHandler(delegate);
    ConnectionPool proxy = Proxy.newProxyInstance(
                ConnectionPool.getClass().getClassLoader(),
                new Class[]{ConnectionPool.class},
                callHandler);

//    return new ConnectionPoolImpl(...);
    return proxy;
}

and

public class ConnectionPoolCallHandler implements InvocationHandler {
    private ConnectionPoolImpl delegate;
    public ConnectionPoolCallHandler(ConnectionPoolImpl delegate) {
        this.delegate=delegate;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
         //all invoked methods should call 
         //appropriate methods of delegate passing all parameters
         //plus your additional tracking logic here
    }
}
@Pointcut("within(java.sql.Connection.close(..)")
public void closeAspect() {}

@Around("closeAspect()")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable 
{
  joinPoint.getThis();//Will return the object on which it(close function) is called 
  //Do whatever you want to do here
   joinPoint.proceed();   
  //Do whatever you want to do here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM