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

后端 未结 2 674
温柔的废话
温柔的废话 2021-02-06 05:40

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

2条回答
  •  后悔当初
    2021-02-06 06:26

    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

提交回复
热议问题