• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using @Inject on static utility classes

 
Rob Ivan
Greenhorn
Posts: 29
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, J and Ashish.

A colleague of mine was trying to use @Inject to inject a runtime String value (the name of the host where the application is running) into a class that had no constructor and only contains static utility methods. The value came up empty, of course. That started a discussion about how one could annotate this class (such as @Component) in order to ensure that Spring instantiated it, or if it should be added to the application context. But that begs the question, why would you want to do that?

So, the question for you guys is: are there any situations you have found where it made sense to have the Spring application context manage a bean that provided only static methods?

Thank you.
 
Kathleen Angeles
Ranch Hand
Posts: 123
Firefox Browser Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont see any reason why not.

You need it configurable. Having it in the Spring context allows you cleaner and clearer maintenance of that variable.

- k


--------------------------------------------------------------------------------------------------------
[SpringSource Certified Spring Professional - Practice Tests]
 
Jayesh A Lalwani
Rancher
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally I think it's not a good idea to have utility classes that have dependencies like his, because you are practically introducing a Singleton. Spring has better ways of creating singletons. Change the utility class to one without static methods, then wire the dependent class into it and then wire the utility class into places that need it
 
Rob Ivan
Greenhorn
Posts: 29
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the responses. I already had the second solution in place (Spring managed Singleton), and it got refactored. I was looking for some "independent validation" that it was not very Spring-like to inject into a class with static utilities.
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alternatively leave your static utility class alone if it makes sense and pass in the hostname as a parameter to the static utility methods that need it. In this case the caller (probably a spring bean service) could @Value this value in or get it from the Spring Environment assuming it was correctly set as a @PropertySource.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic