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;
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;
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).
@BeforeClass
in a SpringJUnit4ClassRunner, and have that method access beans @Autowired
in the test.. you basically can't. Which is annoying. –
Hermit 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.
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).
@BeforeClass
in a SpringJUnit4ClassRunner, and have that method access beans @Autowired
in the test.. you basically can't. Which is annoying. –
Hermit 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.
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;
}
}
© 2022 - 2024 — McMap. All rights reserved.