首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring AOP -从方法返回的代理对象

Spring AOP -从方法返回的代理对象
EN

Stack Overflow用户
提问于 2017-05-15 23:33:03
回答 2查看 327关注 0票数 1

在此示例中:

代码语言:javascript
复制
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对象?

EN

回答 2

Stack Overflow用户

发布于 2017-05-16 14:37:53

可以为ConnectionPool创建代理,并在bean创建方法中返回该代理

代码语言:javascript
复制
@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;
}

代码语言:javascript
复制
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
    }
}
票数 0
EN

Stack Overflow用户

发布于 2017-05-16 00:01:10

代码语言:javascript
复制
@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
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43983439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档