为什么我们不能在春天自动连接静电场?

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

例如:。

@Autowired
public static Test test;
64838 次浏览

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

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

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.

We can't autowire static fields in spring because the Spring context might not be loaded when the java class loader loads the static values. In that case the class loader won't properly inject the static fields in the bean and will fail.

By this solution you can autowired static fields in spring.

@Component
public class TestClass {


private static Test test;


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