java - How to ensure a class can only be instantiated by Spring? -


i re-factoring legacy java application use spring.

this involves declaring application classes spring beans , replacing occurrences of new context.getbean or di.

i'm re-writing application logic in way classes become singletons. since being instantiated using new in other locations, multiple copies exist mess business logic. i'd ensure application explicitly fails whenever tries instantiate object itself, instead of running , misbehaving in unpredictable ways. (i'm not sure re-factoring has covered 100% of application there still might new lurked in corner)

what best way of ensuring class can instantiated spring container? (i'm hoping avoid writing factory each class)

as question

in particular scenario 1 copy of object should exist fetched context, multiple copies mess business logic.

you can create classic singleton , use getinstance() method factory method in bean definition in spring's xml file:

<bean id="mybean" class="myclass" factory-method="getinstance"/> 

make constructor private, , no 1 can call it. additionally see errors in compile time, if parts of old code uses new instantiate class.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -