Sonar 提出 - 对于 applicationContext.getBean() 方法,“更改此条件,使其不会始终评估为 false”

问题描述 投票:0回答:1

Spring 的 ApplicationContext.getBean() 方法可以返回 null。

一个例子:为什么 applicationContext.getBean(beanName) 返回 null,而它显然存在?

但根据声纳,它永远不会返回 null。 声纳抱怨 - 更改此条件,使其不会始终评估为 false。

这是示例代码。

        if (context.getBean(myClazz.class) != null) {   // Sonar warning here

是否是Sonar误报或者getBean方法永远不能返回null?

如果是误报,有什么办法可以绕过这个警告吗?

spring sonarqube
1个回答
0
投票

声纳标记空检查是正确的。因为如果没有找到给定类型的bean,

context.getBean(beanclass)
将会抛出
NoSuchBeanDefinitionException
。所以空检查没有用。

getBean(beanClass) 方法来自 BeanFactory,它记录了此行为。

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