wood burning stoves 2.0*
The moose likes Spring and the fly likes Using @Inject on static utility classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Using @Inject on static utility classes" Watch "Using @Inject on static utility classes" New topic
Author

Using @Inject on static utility classes

Rob Ivan
Greenhorn

Joined: Jan 07, 2010
Posts: 28

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

Joined: Aug 06, 2012
Posts: 122

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
Bartender

Joined: Jan 17, 2008
Posts: 2346
    
  28

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

Joined: Jan 07, 2010
Posts: 28

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

Joined: Mar 07, 2010
Posts: 1648
    
    7

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.


[How To Ask Questions][Read before you PM me]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using @Inject on static utility classes