SONAR complaining about Make the enclosing method "static" or remove this set

Awa :

I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.

However, Sonar is asking to Make the enclosing method "static" or remove this set. the method is setApplicationContext.

How to remove this error? Why this error is coming?

public class SharedContext implements ApplicationContextAware {
public static final String REPORT_ENGINE_FACTORY = "reportEngineFactory";
private static ApplicationContext applicationContext;

public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
    SharedContext.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
    return applicationContext;
}

public Object getBean(String name) {
    return applicationContext.getBean(name);
} }
G. Ann - SonarSource Team :

To be specific, you appear to be asking about rule S2696, 'Instance methods should not write to "static" fields'

As the rule description details:

Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally, static fields are only updated from synchronized static methods.

Thus, the issue is telling you to make the method on which it was raised (presumably setApplicationContext) static, so that across all class instances there is only one copy of that method making updates to the static (i.e. shared across all class instances) field applicationContext. It additionally recommends making the method synchronized so that only one instance at a time can call the method.

Late edit: To see the rule description click either the "See Rule" or the "..." (depending on your version of SonarQube) shown after the issue message.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=451952&siteId=1