Java – spring: how to ensure that a class is instantiated only by spring, not by new

Is it possible to ensure that only spring can instantiate a class instead of using the keyword new at compile time? (avoid accidental instantiation)

@H_ 502_ 8@

Thank you@ H_ 502_ 8@

Solution

If you want to detect it at compile time, the constructor must be non - public

@H_ 502_ 8@

Spring will call this non-public constructor without any problem (since spring 1.1, spr-174)@ H_ 502_ 8@

If this doesn't allow anything else to call your constructor, the idea of forcing each user of a class to use spring dependency injection (so the whole goal of this problem) is a good idea or not, although it's a completely different thing@ H_ 502_ 8@

If this is in a library / framework (usually only used with spring), it may not be a good idea to limit how it is used However, if you know that the class will only be used in closed projects that have forced the use of spring, it may really make sense@ H_ 502_ 8@

Alternatively, if your real goal is to avoid the possibility of someone creating an instance instead of initializing it with its dependencies, you can use constructor dependency injection@ H_ 502_ 8@

If your goal is to prevent accidental use of constructors (developers don't know that this class should be initialized by spring), but don't want to completely limit the possibilities, you can make it private, but you can also add static factory methods (using explicit names, such as createmanualyinitializedinstance or something like that)@ H_ 502_ 8@

Bad idea: another possible alternative is to make the constructor publicly available, but discard it In this way, it can still be used (without hackers like reflection), but any accidental use will be warned But it's not very clean: it doesn't mean devaluation@ H_ 502_ 8@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>