I have a data source that is setup & then, used by a third party software to execute sql. After the sql is run I have another bean that executes & closes the connection.
@Bean
public DataSource datasource() {
HikariConfig myconfig = new HikariConfig();
...
return new HikariDataSource(myconfig);
}
@Bean
@DependsOn("sqlproject")
public void closeConnection() throws SQLException {
Connection c = datasource().getConnection();
try {
c.close();
}
finally {
System.out.println(c.isClosed());
}
}
However, I can clearly still make local calls using that datasource connection to particular data. Should I not be calling datasource()
because this creates a new instance ? What am I doing wrong ?
CodePudding user response:
You're right, when you're calling datasource
from configuration class, new instance is created because Spring AOP doesn't support self invocation via this
.
Moreover, even if you have used this AOP correctly, this wouldn't have closed DataSource
, since you're creating new connection (via getConnection()
and then closing it.
If you want to close HikariDataSource
, then you need to call HikariDataSource#close
.
Also, you don't need @Bean
annotation on your void
method since it makes no sense.