Make sure spring component is stateless
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 Mutability 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.