确保弹簧组件是无状态的 [英] Make sure spring component is stateless
问题描述
当开发人员向Spring组件引入可变性时,我们遇到了多线程问题。这样的事情:
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;
}
}
导致多线程的错误 - 字段intermediateResults有从不同的线程访问过。
which led to bug with multithreading - the field intermediateResults has been accessed from different threads.
是否有办法防止向Spring Singleton添加状态,例如通过某种静态分析仪?
SonarQube插件? Eclipse插件?
感谢您的建议。
Is there are a way to prevent adding state to a Spring Singleton e.g. by some kind of static analyzer? SonarQube plugins? Eclipse plugins? Thanks for suggestions.
推荐答案
Google的 MutabilityDetector 似乎能够完全满足您的需求:
Google's MutabilityDetector seems able to do exactly what you need:
Mutability Detector旨在分析Java类并报告给定类的实例是否是不可变的。它可以使用:
Mutability Detector is designed to analyse Java classes and report on whether instances of a given class are immutable. It can be used:
- 在单元测试中,使用断言如assertImmutable(MyClass.class)。你的班级实际上是不可变的吗?你刚刚做出改变后怎么办?
- 作为一个FindBugs插件。你用@Immutable注释的那些类实际上是吗?
在运行时。您的API是否需要被赋予不可变对象?
从命令行。你想在整个代码库中快速运行Mutability Detector吗?
我会建议你添加一个明确的合同,声明该类应该是不可变的,可以通过 javadoc
或通过 @Immutable
类注释本身,允许(明智的)开发人员维护类的必需品。 (如果Google的检测器未能检测到特定类型的不变性,例如:字符串,日期真的不可变吗?)
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?)
这篇关于确保弹簧组件是无状态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!