Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to use an injected bean in a static method?

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

like image 345
Hossein Avatar asked Oct 27 '13 14:10

Hossein


People also ask

How Spring bean is used in static method?

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.

Can we inject a Spring bean 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.

What is the correct way to call a static method?

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.

How do you inject a value to a static field?

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.


1 Answers

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

like image 184
yname Avatar answered Sep 23 '22 19:09

yname