为什么我们不能在春季自动为静态场接线? [英] Why can't we autowire static fields in spring?

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

问题描述

为什么不能在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).

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

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