Improve Java S3749

Hi I find below rule is very helpful.
https://rules.sonarsource.com/java/RSPEC-3749

I have some suggestions.

  1. Some places we need to use spring prototype beans. So can we make this rule ignore classes with annotation @Scope(BeanDefinition.SCOPE_PROTOTYPE) or @Scope(“prototype”).
  2. Can we add a rule which detects the reference of Java classes( spring beans) marked as @Scope(BeanDefinition.SCOPE_PROTOTYPE) or @Scope(“prototype”) and warn the developers about the bean is being prototype and it should be accessed as prototype. Since in spring all beans are by default singleton and if somebody injects prototype in singleton it should be injected as prototype.

Thanks
Praveena

Hello,

  1. I agree, and in fact, we already improved the rule just recently, see SONARJAVA-3394.

  2. I’m not sure to understand what you mean here. Could you try to build an example of noncompliant/compliant code?

Thank you Quentin.!
For second point. Current Sonar rules don’t detect prototype injection into singleton. We want a way to detect when prototype is wired into singleton bean incorrectly.

@Service
@Scope(BeanDefinition.PROTOTYPE)
public class MyPrototypeBean {

    private String dateTimeString = LocalDateTime.now().toString();

    public String getDateTime() {
        return dateTimeString;
    }
@Service
public class MySingletonBean {

@Autowired // This bean is used as a singleton here which will cause prototypeBean.getDateTime() to show same time for all calls. 
    private MyPrototypeBean prototypeBean;

    public void showMessage(){
        System.out.println("Hi, the time is "+prototypeBean.getDateTime());
    }

Good to know SONARJAVA-3394 is introduced. Can we tweak this rule so that all prototype @Scope annotation to have proxyMode attribute.
proxyMode doc : https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-scopes-other-injection
Ex- https://www.logicbig.com/tutorials/spring-framework/spring-core/scoped-proxy.html

Thank you for the example, I understand what you mean now.

I think you have nice clues to build/improve rules, and we eventually plan to come back to Spring at one point, your input will definitely be taken into consideration. Not in the near future, and I can not give you any estimation for now though.

In the meantime, if you strongly believe these ideas would lead to great rules, feel free to propose them here, with examples and precise descriptions and motivation.

Also, keep in mind that we try to focus on rules that make sense for everyone. For example, if adding proxyMode is a requirement of your project, you might want to have a look at custom rules. If it turns out to be a common requirement (based on blog/articles/…), then it would make a great rule.