Java 在静态方法中使用注入 bean 的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19619118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the right way to use an injected bean in a static method?
提问by Hossein
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:
这个问题可能看起来有点奇怪。假设我有一个服务,我想在具有一些静态方法的实用程序类中使用它。Service 是一个 Spring bean,所以很自然地,我将使用一个 setter 和 (@Autowired) 将它注入到我的实用程序类中。正如 Spring 文档中提到的,所有 bean 在 bean 上下文中都是静态的。因此,当您想在类中注入 bean 时,您不必使用“静态”修饰符。见下文:
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
尽管 Service 是静态的,但我不得不将静态置于其定义之后。这对我来说有点违反直觉。这是错误的吗?还是更好的方法?谢谢
采纳答案by yname
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
请注意,您必须将此类声明为“组件”才能注入 tmpService
回答by Sotirios Delimanolis
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.
你没有选择。如果要初始化static
类的字段,则必须让 Spring 创建该类的实例并注入该值。
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.
一点建议。static
在这种情况下,您真的没有任何理由使用方法。如果您想要一个单例实用程序,只需让您的 bean 具有singleton
作用域即可。