
Originally Posted by
Dan Washusen
Someone from the mailing list came up with an alternate solution to my problem. Instead of accessing the application context staticly change the code to something like this:
Code:
public class Foo {
private static Foo instance = new Foo();
public static Foo getInstance() {
return instance;
}
publis static void setInstacne(Foo newInstance) {
instance = newInstance;
}
public Foo() {
Foo.setInstance(this);
}
}
Hi Dan,
I'm going through a similar conversion of an existing app (mine's a Swing app...how about yours?). I have the same problem of how to convert existing singletons to use DI. My first stage of the conversion involved converting my singletons to look very similar to your Foo example. So you should get some reassurance from that. Note that your example is also somewhat similar to Spring Rich Client's Application class, in that it allows singleton-style access while also supporting IOC instantiation.
In the second stage of the conversion, I instantiated my singletons in the IOC. That is, I declared them as beans in my app context. So far so good. At this point, I now have the potential to make any class that formerly depended on a specific singleton class depend on its interface(s) instead. I can also configure the singletons in the app context config file. An improvement, I think.
In the third stage of the conversion, which I am starting now, I plan to change all singleton references from a specific singleton to a single singleton, namely Spring Rich's Application class. For example:
Instead of this:
MyServiceImpl.getInstance().someMethod()
I will do this:
(MyService) Application.services().getBean("MyService")
Or perhaps even this:
(MyService) Application.services().getBean("MyService", MyService.class)
While this will still be singleton access, at least I'll be down to one singleton instead of several and it will also be easier to make the dependent classes depend on each singleton's interface instead of its implementation.
In the fourth stage of the conversion, I'll remove each singleton's static fields and methods that are used for instance management; essentially this will convert the singletons to non-singletons.
In the fifth stage, I will convert as many dependent classes as possible to use DI instead of Application.services().getBean(). I'm not sure if 100% conversion is feasible here.
I hope this helps.
Cheers,
Joe
"All your bean are belong to us" - Spring Framework's IOC Container