I want to intercept spring jpa derived queries before execution. i tried with EmptyInterceptor and StatementInspector, but they are intercepting queries annotated with @query.
I reccommend the net.ttddyy:datasource-proxy:
implementation 'net.ttddyy:datasource-proxy:1.5.1'
Here is the PostProcessor & Interceptor:
@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();
}
}
}
For more Informations: https://github.com/ttddyy/datasource-proxy
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.