FP on java S3749 when using prototypes

When using a prototype @Component, the bean is instanciated at each call of BeanFactory#getBean and using fields is a common way to use prototypes.

Reproduction code:

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Fp3749 {
  private String someField;

  public void setSomeField(final String someField) {
    this.someField = someField;
  }

  public String toString() {
    return "Fp3749 > " + someField;
  }
}

java:S3749 should ignore components annoted with @Scope("prototype")

Hello @alec, thanks for the feeback.

I agree with you, the documentation itself states that prototype scope should be used for stateful components. I created a ticket to track this issue (SONARJAVA-3394).

Then, what about other scopes? Indeed, they may not behave as a singleton, but excluding them from the rule seems more discussable.

Do you have an opinion on it?

Maybe having this rule configurable with a whitelist of scopes with the default being “prototype”.

It is possible to enhance Spring by creating custom lifecycles for beans (spring-cloud adds refresh for example) but I never looked into it.

If an user wants his custom scope to not raise an issue he can then modify the rule configuration accordingly.

I see, I updated the ticket to state the possibility of custom lifecycles. For now, the rule will support this situation “at best”, avoiding possible false positives and still reporting interesting issues with common scopes.

We eventually plan to come back to rules specific to Spring in the future, if there is something better to do for this rule, we will definitely think about it, and take your input into account.

Best,
Quentin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.