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

2020-05-27 08:26发布

问题:

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

回答1:

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



回答2:

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 little advice. There really isn't any reason for you to be using static methods in this case. If you want a singleton utility, just make your bean have singleton scope.