• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Spring Injected Singletons

 
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Dhanji,

Nice to have you here. I've recently gotten in the habit of using Spring to manage my singletons because it's easier to test. It can be difficult to test class that uses a singleton with MySingleton.getInstance() since you end up with this global state that can persist throughout tests. I recently wrote a blog entry about it http://jeffastorey.blogspot.com/2009/08/spring-managed-singletons-for.html (though what I'm saying now is the gist of it).

What are your thoughts on using spring to inject singletons vs traditional getInstance() (other than that a spring managed singleton is only a singleton within a particular context).

thanks,
Jeff
 
author
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jeff

Yes it's much preferable to use dependency injection to do this, since you can replace it in a mock without exposing special setter methods or worrying about concurrently executable tests. There are also problems with modularity that are introduced when using static factories that are solved by using DI instead.

My colleague and I present this in some detail in this video talk:
http://www.youtube.com/watch?v=hBVJbzAagfs

Dhanji.
 
Jeff Storey
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the quick reply. I agree with you and I'll be sure to watch the presentation.
 
Ranch Hand
Posts: 686
Netbeans IDE Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nice talk!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic