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

白昼怎懂夜的黑 提交于 2019-12-03 12:45:34

问题


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.



来源:https://stackoverflow.com/questions/19619118/what-is-the-right-way-to-use-an-injected-bean-in-a-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!