Why can't we autowire static fields in spring?

SpringAutowired

Spring Problem Overview


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.

e.g.

@Autowired
public static Test test;

Spring Solutions


Solution 1 - Spring

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.

Solution 2 - Spring

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

Solution 3 - Spring

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.

Solution 4 - Spring

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;
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshuView Question on Stackoverflow
Solution 1 - SpringAndrea TView Answer on Stackoverflow
Solution 2 - SpringTomasz NurkiewiczView Answer on Stackoverflow
Solution 3 - SpringSubin SebastianView Answer on Stackoverflow
Solution 4 - SpringParth SolankiView Answer on Stackoverflow