SonarQube "Close this ConfigurableApplicationContext" in Spring Boot project
I was always thinking, that it is false/positive.
But you can test this with a this few lines.
@RunWith(SpringRunner.class)
@SpringBootTest
public class YourApplicationTest {
@Test
public void shouldLoadApplicationContext() {
}
@Test
public void applicationTest() {
YourApplication.main(new String[] {});
}
}
Now Sonar is saying, this is tested!
(Kudos goes out to: Robert @ https://stackoverflow.com/a/41775613/863403)
If you have a web application, the application context will be destroyed (I think by ContextLoaderListener
, not sure), no explicit code is needed.
In the case of a command line application, the context must be destroyed manually, otherwise beans will not be destroyed properly - @PreDestroy methods will not be called. E.g:
@Bean
public ApplicationRunner applicationRunner() {
return new ApplicationRunner() {
public void run(ApplicationArguments args) throws Exception {
try {
doStuff();
} finally {
context.close();
}
}
I noticed this when a Cassandra session stayed open after my spring boot command line application has finished.
The issue that SonarQube is reporting is a false positive and should be ignored. SonarQube's FAQ lists some options for removing false positives:
False-Positive and Won't Fix
You can mark individual issues as False Positive or Won't Fix through the issues interface. However, this solution doesn't work across branches - you'll have to re-mark the issue False Positive for each branch under analysis. So an in-code approach may be preferable if multiple branches of a project are under analysis:
//NOSONAR
You can use the mechanism embedded in rules engine (//NOPMD...) or the generic mechanism implemented in SonarQube: put //NOSONAR at the end of the line of the issue. This will suppress the issue.
Switch Off Issues
You can review an issue to flag it as false positive directly from the user interface.