build failed Error: java: USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES how to fix spot bug reported issue

build failed Error: java: USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES how to fix spot bug reported issue

我面临 Error: java: USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES 并且 setter 方法构建失败。它是由 spotbugs 报告的。如何解决这个问题,请帮助,因为没有得到解决方案。 下面是 class MySuperServiceConfig。

@Component
@ConfigurationProperties("mysuperservice")
@PropertySource("classpath:data.properties")
public class MySuperServiceConfig {
  private String username;
  private String password;
  private List<String> schemadata;

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public List<String> getSchemadata() {
    return schemadata;
  }

  public void setSchemadata(List<String> schemadata) {
    this.schemadata = schemadata;
  }
}

下面是日志

[INFO] --- spotbugs-maven-plugin:3.1.12.2:check (default) @ aif-handler ---
[INFO] BugInstance size is 3
[INFO] Error size is 0
[INFO] Total bugs: 3
[ERROR] Method com.test.service.fileparser.MySuperServiceConfig.setPassword(String) of Singleton class writes to a field in an unsynchronized manner [com.amex.scs.aif.service.fileparser.MySuperServiceConfig] At MySuperServiceConfig.java:[line 29] USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES
[ERROR] Method com.test.service.fileparser.MySuperServiceConfig.setSchemadata(List) of Singleton class writes to a field in an unsynchronized manner [com.amex.scs.aif.service.fileparser.MySuperServiceConfig] At MySuperServiceConfig.java:[line 37] USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES
[ERROR] Method com.test.service.fileparser.MySuperServiceConfig.setUsername(String) of Singleton class writes to a field in an unsynchronized manner [com.amex.scs.aif.service.fileparser.MySuperServiceConfig] At MySuperServiceConfig.java:[line 21] USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES

spotbug 文档有一些关于此错误的信息

http://fb-contrib.sourceforge.net/bugdescriptions.html

USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES

This method writes to a field of this class. Since this class is seen as a Singleton this can produce race conditions, or cause non-visible changes to other threads, because the field isn't accessed synchronously.

由于Configuration 属性 class 标有Component 注释,Spotbug 会知道这是一个Singleton Bean。 Configuration bean 不会自动装配任何字段 - username / password / schemaData,但它有一个 getter 和 setter 方法。因此,代码似乎可以多次更改 bean 的这些实例属性或依赖项。在这种情况下,由于方法不同步,可能会出现竞争条件。 因此,修复应该是删除此组件注释,因为这是一个配置 属性 映射器 class.

要自动装配,您可以 -

  1. 在 SpringBootApplication class 或其他配置 class
  2. 上使用 @EnableConfigurationProperties(MySuperServiceConfig.class)
  3. 将其标记为@Configuration class