1

I am developing Spring MVC app, i need to implement singleton pattern for some kind of utilities, ex: imageuploader and others.

My question is: in what way to implement singleton for this utilities, to initialize beans for these classes and inject where i need like Controllers, Services, DAO?, or to use static field implementation of singleton to keep instance of this class?

Marco Ferrari
  • 4,914
  • 5
  • 33
  • 53
Placinta Alexandru
  • 463
  • 2
  • 7
  • 20

2 Answers2

2

Using a Spring bean as will allow you to easily inject a mock in unit tests. However, you will only be able to access it from other Spring beans (or objects created by Spring beans that pass in a reference to it).

Also see this discussion in this question: Difference between static class and singleton pattern?

Traditionally, you'd use PropertyPlaceholderConfigurer to inject config from properties files into a Spring web-app. This blog discusses a variety of newer ways to do this with Spring.

Community
  • 1
  • 1
whistling_marmot
  • 3,561
  • 3
  • 25
  • 39
2

First, try to avoid singleton as it's considered to be a bad practice. Also their interactions with other instances are difficult to test and validate, compared to non-singleton instances.

If you absolutely need it, I'd suggest you use a Spring bean so you can exploit the autowiring mechanism and Spring's bean lifecycle.

See the Beans section of the Spring reference doc for more info.

Community
  • 1
  • 1
Marco Ferrari
  • 4,914
  • 5
  • 33
  • 53