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);
} }
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 fromsynchronized 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.
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.
This worked for me.
@Setter
private static volatile ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
setContext(ac);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With