为什么我们不能在 spring 中自动装配静态字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10938529/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:09:32  来源:igfitidea点击:

Why can't we autowire static fields in spring?

springautowired

提问by Ashu

Why can't we autowire the static instance variable in the Spring bean. I know there is another way to achieve this but just want to know why cant we do it in below way.

为什么我们不能在 Spring bean 中自动装配静态实例变量。我知道还有另一种方法可以实现这一点,但只是想知道为什么我们不能以下面的方式做到这一点。

e.g.

例如

@Autowired
public static Test test;

采纳答案by Tomasz Nurkiewicz

Because using static fields encourages the usage of static methods. And static methods are evil. The main purpose of dependency injection is to let the container create objects for you and wire them. Also it makes testing easier.

因为使用静态字段鼓励使用静态方法。静态方法是邪恶的。依赖注入的主要目的是让容器为你创建对象并连接它们。它还使测试更容易。

Once you start to use static methods, you no longer need to create an instance of object and testing is much harder. Also you cannot create several instances of a given class, each with a different dependency being injected (because the field is implicitly shared and creates global state - also evil).

一旦你开始使用静态方法,你就不再需要创建对象的实例并且测试变得更加困难。此外,您不能创建给定类的多个实例,每个实例都注入不同的依赖项(因为该字段是隐式共享的并创建全局状态 - 也是邪恶的)。

回答by Andrea T

Because when the class loader loads the static values, the Spring context is not yet necessarily loaded. So the class loader won't properly inject the static fields in the bean and will fail.

因为当类加载器加载静态值时,Spring 上下文还不一定加载。所以类加载器不会正确地在 bean 中注入静态字段并且会失败。

回答by Subin Sebastian

According to OOP concept, it will be bad design if static variables are autowired.

根据 OOP 的概念,如果静态变量是自动装配的,那将是糟糕的设计。

Static variable is not a property of Object, but it is a property of a Class. Spring auto wiring is done on objects, and that makes the design clean in my opinion. You can deploy the auto wired bean object as singleton, and achieve the same as defining it static.

静态变量不是对象的属性,而是类的属性。Spring 自动布线是在对象上完成的,在我看来,这使设计变得干净。您可以将自动连接的 bean 对象部署为单例,并实现与定义静态相同的效果。

回答by Parth Solanki

By this solution you can autowired static fields in spring.

通过此解决方案,您可以在 spring 中自动装配静态字段。

@Component
public class TestClass {

    private static Test test;

    @Autowired
    public void setTest(Test test) {
        TestClass.test = test;
    }
}