0

I have a class which has few static utility function.

I want to inject a property value << which is a static field>> without creating its bean.

@Component
class TestUtils {

 @Value("${toke.value}")
 public static String token;

 public static String doOperation(String value) {
   .... do some operation using toke
   return result;
 }

 public static void setToken(String token ) {
  TestUtils.token = token;
 }
}

I am never creating object of this class. The method is called

TestUtils.doOperation(parms);

Just want to know is there is any way in which i set the property of this value , when application starts.

Thanks.

Zuned Ahmed
  • 1,357
  • 6
  • 29
  • 56

1 Answers1

1

Just don't. Make your methods instance methods instead of static methods. Make your fields private instance fields instead of public static fields, and inject an instance of the bean where you need access to call the method. That's the whole point of dependency injection.

Spring beans are singletons by default, so there won't be more than one such field in the JVM anyway. And making it an instance method and an injectable component will make the code using it testable, which is not the case with a static method.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I agree we should not, i am doing that. But just to knowledge purpose if still some other place i need to do then how to achieve same. – Zuned Ahmed Dec 15 '12 at 13:32
  • http://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field – JB Nizet Dec 15 '12 at 13:35
  • But the issue is @PostConstruct is call after bean creation and what if we are never creating bean of that Class , then how to give value of the static property of the class. Thanks in advance for response. – Zuned Ahmed Dec 15 '12 at 14:11
  • 1
    Don't read the question. Read the answers, and the links in the answers. Basically, they all say that it's not supported, but that there are nasty tricks to work around it. I still think you simply shouldn't do it. – JB Nizet Dec 15 '12 at 14:15