Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
} }
like image 331
Aawan Avatar asked Sep 09 '16 09:09

Aawan


3 Answers

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.

like image 174
G. Ann - SonarSource Team Avatar answered Nov 16 '22 15:11

G. Ann - SonarSource Team


For what it's worth, and I'm probably going to get blacklisted by the Sonar community specifically and the Java Universe in general for saying this, adding @SuppressWarnings("squid:S2696") to the top of the offending method causes Sonar to ignore that warning completely.

like image 32
ccellist Avatar answered Nov 16 '22 16:11

ccellist


This worked for me.

@Setter
private static volatile ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
    setContext(ac);
}
like image 2
user16101992 Avatar answered Nov 16 '22 16:11

user16101992