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

后端 未结 2 672
温柔的废话
温柔的废话 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:25

    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.

提交回复
热议问题