【问题标题】:How to avoid SonarLint UnusedPrivateMethod when instantiating Spring components?实例化Spring组件时如何避免SonarLint UnusedPrivateMethod?
【发布时间】:2019-09-09 09:43:33
【问题描述】:

在一个基本的 Spring Boot 应用程序中,我有这个组件:

@Component
public class TheComponent {
    public String getKey() {return "value";}
}

由服务使用。如果我这样设计我的服务:

@Service
public class TheService { 

    @Autowired
    private TheComponent theComponent;

    private final String keyValue = theComponent.getKey();

    private TheService() {}
}

然后 Spring Boot 不会构建,因为 theComponent 触发了 NullPointerException

如果我这样设计:

@Service
public class TheService {

    private String keyValue;

    private TheService(TheComponent theComponent) {
        keyValue = theComponent.getKey();
    }
}

然后 SonarLint 告诉我应该删除这个未使用的私有“TheService”构造函数

是否有一个解决方案既适合 Spring 又适合 SonarLint,使用私有构造函数?

【问题讨论】:

  • 问题是为什么TheComponent不能自动连线,你是使用组件扫描还是如何将它设置为bean?
  • 抱歉,我无法回答您的问题。我只能说我在没有更改任何配置的情况下使用了 Spring initializr。我认为它不能自动装配,因为keyValue 初始化发生在自动装配之前(source)。

标签: java spring reflection jvm sonarlint


【解决方案1】:

用:注释你的构造函数:

@SuppressWarnings("unused")

您也可以在类级别使用它来抑制所有警告。

【讨论】:

  • 这意味着 SonarLint 不够聪明,无法看到实际使用了此方法。是这样吗?
  • 有时不能责怪 linting 工具。例如 hibernate 通过反射不使用 args 构造函数。从外面可能看不到。
猜你喜欢
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 2015-04-23
  • 1970-01-01
  • 2013-02-13
  • 2015-12-09
相关资源
最近更新 更多