Make sure spring component is stateless

We faced a multi-threading problem when a developer introduced mutability to a Spring Component. Something like this:

@Component //singleton
public class MyComponent {
...
private String intermediateResults;
public String businessMethod() {
 ... fills in intermediateResults;
}

public String thisGetterShouldNotBeHere() {
    return intermediateResults;
 }
}

which led to bug with multithreading - the field intermediateResults has been accessed from different threads.

Is there are a way to prevent adding state to a Spring Singleton eg by some kind of static analyzer? SonarQube plugins? Eclipse plugins? Thanks for suggestions.


Google's MutabilityDetector seems able to do exactly what you need:

Mutability Detector is designed to analyse Java classes and report on whether instances of a given class are immutable. It can be used:

  • In a unit test, with an assertion like assertImmutable(MyClass.class). Is your class actually immutable? What about after that change you just made?
  • As a FindBugs plugin. Those classes you annotated with @Immutable, are they actually? At runtime. Does your API require being given immutable objects? From the command line. Do you want to quickly run Mutability Detector over an entire code base?
  • I would anyway advise to add a clear contract stating that the class is supposed to be immutable either via javadoc or via @Immutable annotation on the class itself, to allow (sensible) developers to maintain the class requisites. (In case Google's detector fails to detect specific types of immutability eg: Are String, Date really immutable?)


    You could implement your own rules with any static analyzer (Like FindBugs, PMD and Checkstyle) to check that your class:

  • Only allows final properties
  • Extends a given class
  • Is final
  • Uses constructor dependency injection
  • However, as far as I know, there's no tool specifically configured out of the box for that.

    Alternatively you could create an @Immutable annotation and implement the checks there.

    链接地址: http://www.djcxy.com/p/38174.html

    上一篇: 当调用IntPtr构造函数时,Xamarin Android会执行OnCreateView吗?

    下一篇: 确保弹簧组件是无状态的