Java SonarQube“;关闭此ConfigurableApplicationContext“;在SpringBoot项目中
我在主方法中遇到了阻止程序问题“关闭此”ConfigurableApplicationContext“”Java SonarQube“;关闭此ConfigurableApplicationContext“;在SpringBoot项目中,java,spring,spring-boot,sonarqube,Java,Spring,Spring Boot,Sonarqube,我在主方法中遇到了阻止程序问题“关闭此”ConfigurableApplicationContext“” public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } 我试过SonarQube示例中的代码 public static void main(String[] args) { ConfigurableApplicationContext cont
public static void main(String[] args)
{
SpringApplication.run(MyApplication.class, args);
}
我试过SonarQube示例中的代码
public static void main(String[] args)
{
ConfigurableApplicationContext context = null;
try
{
context = SpringApplication.run(MyApplication.class, args);
}
finally
{
if (context != null) {
context.close();
}
}
}
但它一开始就关闭了上下文
如何解决此问题?SonarQube报告的问题为假阳性,应忽略。列出了一些用于删除误报的选项: 假阳性,无法修复 您可以将个别问题标记为假阳性,或通过问题界面无法修复。但是,此解决方案不能跨分支工作-您必须为分析中的每个分支重新标记问题假阳性。因此,如果一个项目的多个分支正在分析中,代码内方法可能更可取: //NOSONAR 您可以使用规则引擎(//NOPMD…)中嵌入的机制,也可以使用SonarQube中实现的通用机制:将//NOSONAR放在问题行的末尾。这将抑制该问题 关闭问题 您可以直接从用户界面查看问题,将其标记为假阳性
如果您有一个web应用程序,那么应用程序上下文将被破坏(我认为由
ContextLoaderListener
,不确定),不需要显式代码
对于命令行应用程序,必须手动销毁上下文,否则将无法正确销毁bean-@PreDestroy方法将不会被调用。例如:
@Bean
public ApplicationRunner applicationRunner() {
return new ApplicationRunner() {
public void run(ApplicationArguments args) throws Exception {
try {
doStuff();
} finally {
context.close();
}
}
当我的spring boot命令行应用程序完成后,Cassandra会话保持打开状态时,我注意到了这一点 我一直在想,这是错误的/肯定的 但是你可以用这几行来测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class YourApplicationTest {
@Test
public void shouldLoadApplicationContext() {
}
@Test
public void applicationTest() {
YourApplication.main(new String[] {});
}
}
现在声纳说,这是测试(值得称赞的是:Robert@)我们实际上是在寻找反馈:请随意加入,这样我们就可以改进规则。虽然//NOSONAR有效,但它会禁用所有声纳检查,尽管只针对该线路。另一种方法是专门禁用单个规则的检查;在本例中,您可以通过在主方法上添加
@SuppressWarnings(“squid:S2095”)
来实现。