在这个例子中:
public class ConnectionPool {
public java.sql.Connection getConnection() {
...
}
}
@Bean
@Scope("singleton")
public ConnectionPool connectionPool(...) throws Exception {
return new ConnectionPoolImpl(...);
}
我想监视从getConnection()返回的Connection对象上对java.sql.Connection.close()的调用。
我尝试将@Lookup
添加到getConnection()方法,但它没有效果。
如何让Spring代理java.sql.Connection对象?
答案 0 :(得分:0)
您可以为ConnectionPool创建代理并在bean创建方法中返回代理
@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;
}
和
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
}
}
答案 1 :(得分:-1)
@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
}