用于派生查询的Spring jpa拦截器

问题描述 投票:0回答:1

我想在执行之前拦截spring jpa派生的查询。我尝试使用EmptyInterceptor和StatementInspector,但是它们正在拦截以@query注释的查询。

java hibernate spring-boot jpa interceptor
1个回答
0
投票

我推荐net.ttddyy:datasource-proxy:

implementation 'net.ttddyy:datasource-proxy:1.5.1'

这里是后处理器和拦截器:

@Component
@Slf4j
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor {

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (bean instanceof DataSource && !(bean instanceof ProxyDataSource)) {
      log.info("DataSource bean has been found: " + bean);
      final ProxyFactory factory = new ProxyFactory(bean);
      factory.setProxyTargetClass(true);
      factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
      return factory.getProxy();
    }
    return bean;
  }

 @Override
 public Object postProcessBeforeInitialization(Object bean, String beanName) {
   return bean;
 }

 private static class ProxyDataSourceInterceptor implements MethodInterceptor {
   private final DataSource dataSource;

    public ProxyDataSourceInterceptor(final DataSource dataSource) {
     this.dataSource = ProxyDataSourceBuilder.create(dataSource)
      .name("MyServiceDS")
      .logQueryBySlf4j(SLF4JLogLevel.DEBUG)
      .multiline()
      .build();
    }

    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
      final Method proxyMethod = ReflectionUtils.findMethod(this.dataSource.getClass(),
          invocation.getMethod().getName());
      if (proxyMethod != null) {
        return proxyMethod.invoke(this.dataSource, invocation.getArguments());
      }
      return invocation.proceed();
    }

  }
}

有关更多信息:https://github.com/ttddyy/datasource-proxy

© www.soinside.com 2019 - 2024. All rights reserved.