This question might seem a little odd. Suppose I have a Service which I want to use in a Utility class that has some static methods. The Service is a Spring bean, so naturally I will for example use a setter and (@Autowired) to inject it into my utility class. As it is mentioned in Spring's documentation, all beans are static in the bean context. So when you want to inject a bean in a class you don't have to use "static" modifier. See below:
public class JustAClass{
private Service service;
public void aMethod(){
service.doSomething(....);
}
@Autowired
public void setService(Service service){
this.service = service;
}
}
Now going back to what I mentioned first (Using Service in a static Method):
public class JustAClass{
private static Service service;
public static void aMethod(){
service.doSomething(....);
}
@Autowired
public void setService(Service service){
this.service = service;
}
}
Although Service is static, I am forced to put static behind its definition. This is a bit counter-intuitive to me. is this wrong? or is it a better way? Thanks
If we want to use spring bean ref in static methods we need to use ApplicationContextAware interface and override setApplicationContext() and make context object as static.
You have no choice. If you want to initialize a static field of a class, you will have to let Spring create an instance of that class and inject the value.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
Solution First, PropertyController, which is a RestController, is being initialized by Spring. Afterward, Spring searches for the Value annotated fields and methods. Spring uses dependency injection to populate the specific value when it finds the @Value annotation.
You can't autowire static field.
But you can make a little workaround:
@Component
public class JustAClass{
private static Service service;
@Autowired
private Service tmpService;
@PostConstruct
public void init() {
service = tmpService;
}
}
Note, that you have to declare this class as "Component" to inject tmpService
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With