SonarQube在Spring Boot项目中“关闭此ConfigurableApplicationContext”

问题描述 投票:20回答:3

我在main方法中有阻塞问题“关闭此”ConfigurableApplicationContext“”

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();
        }
    }
}

但它在开始后就关闭了上下文。

如何解决这个问题?

java spring spring-boot sonarqube
3个回答
24
投票

SonarQube报告的问题是误报,应该被忽略。 SonarQube's FAQ列出了一些消除误报的方法:

False-Positive and Won't Fix

您可以通过问题界面将个别问题标记为误报或不会修复。但是,此解决方案不适用于分支 - 您必须为正在分析的每个分支重新标记问题False Positive。因此,如果正在分析项目的多个分支,则可能更喜欢使用代码内方法:

//NOSONAR

您可以使用规则引擎中嵌入的机制(// NOPMD ...)或SonarQube中实现的通用机制:将// NOSONAR放在问题行的末尾。这将抑制这个问题。

Switch Off Issues

您可以查看问题,直接从用户界面将其标记为误报。


1
投票

如果你有一个Web应用程序,应用程序上下文将被销毁(我认为ContextLoaderListener,不确定),不需要显式代码。

对于命令行应用程序,必须手动销毁上下文,否则将无法正确销毁bean - 不会调用@PreDestroy方法。例如:

@Bean
public ApplicationRunner applicationRunner() {
    return new ApplicationRunner() {
        public void run(ApplicationArguments args) throws Exception {

            try {
                doStuff();
            } finally {
                context.close();
            }
        }

我的春天启动命令行应用程序完成后,当Cassandra会话保持打开时,我注意到了这一点。


1
投票

我一直在想,这是假的/积极的。

但是你可以用这几行来测试它。

@RunWith(SpringRunner.class)
@SpringBootTest
public class YourApplicationTest {

    @Test
    public void shouldLoadApplicationContext() {
    }

    @Test
    public void applicationTest() {
        YourApplication.main(new String[] {});
    }

}

现在声纳说,这是经过测试的! (Kudos出去:Robert @ https://stackoverflow.com/a/41775613/863403

© www.soinside.com 2019 - 2024. All rights reserved.