为什么我们不能在 spring 中自动装配静态字段? [英] Why can't we autowire static fields in spring?

查看:59
本文介绍了为什么我们不能在 spring 中自动装配静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如

@Autowired
public static Test test;

推荐答案

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

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).

这篇关于为什么我们不能在 spring 中自动装配静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆