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.
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;
}
}
The best thing is that you didn't even need Spring AOP or AspectJ for that.