问题描述
我试图在 spring 3.2.3 中拦截 getConnection 调用
I am trying to intercept the getConnection call in spring 3.2.3
@Component
@Aspect
@Order(value = 1)
public class ConnectionAspect {
//@AfterReturning(pointcut = "execution(java.sql.Connection javax.sql.DataSource.getConnection(..))", returning = "connection")
@Around("execution(java.sql.Connection javax.sql.DataSource.getConnection(..))")
public Connection prepare(ProceedingJoinPoint pjp) throws Throwable {
return MyConnectionProxy.newInstance((Connection) pjp.proceed(pjp.getArgs()));
}
}
调用 getConnection 时不会调用此方面.切入点定义是否有错误execution(java.sql.Connection javax.sql.DataSource.getConnection(..))
This aspect does not invoked on calling getConnection .Is there any mistake in the point cut definition execution(java.sql.Connection javax.sql.DataSource.getConnection(..))
推荐答案
Spring AOP 只能建议 spring 管理的 bean.如果您的 DataSource
实例不是 Spring 管理的 bean,那么您将无法使用 Spring AOP 实现您的目标.
Spring AOP can only advise spring managed beans. If your DataSource
instances are not spring managed beans, you won't be able to achieve your goal with Spring AOP.
我会尝试通过围绕容器提供的数据源创建某种委托代理来解决这个问题,并使其成为由 spring 管理的 bean.事实证明,在 Spring 中实际上有一个专门用于此目的的类.它被称为 委托数据源
.您只需要继承这个类,覆盖 getConnection()
方法(或您需要影响的任何其他方法的行为),将其设置为委托给提供的容器 DataSource
,并使其成为春季管理的豆类,您就可以开始了.
I would try to solve this issue by creating some kind of delegating proxy around the container provided DataSource, and make it a bean managed by spring. It turns out there's actually a class intended in Spring specifically for this purpose. It's called DelegatingDataSource
. You only need to subclass this class, ovverride the getConnection()
method (or whichever other method's behavior you need to affect), set it up for delegating to the container provided DataSource
, and making it a spring managed bean and you're good to go.
这个例子应该可以做到:
Someting along this example should do it:
@Configuration
public class DataSourceConfiguration {
public static class MySpecialDataSource extends DelegatingDataSource {
public MySpecialDataSource(DataSource delegate) {
super(delegate);
}
@Override
public Connection getConnection() throws SQLException {
return super.getConnection();
}
}
@Bean
public DataSource dataSource(@Autowired DataSource containerDataSource) {
return new MySpecialDataSource(containerDataSource);
}
@Bean(name="containerDataSource")
public JndiObjectFactoryBean containerDataSource() {
JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
factoryBean.setJndiName("jdbc/MyDataSource");
return factoryBean;
}
}
最好的事情是,您甚至不需要 Spring AOP 或 AspectJ.
The best thing is that you didn't even need Spring AOP or AspectJ for that.
这篇关于spring 方面没有在 getConnection 上被触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!