Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we autowire static fields in spring?

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; 
like image 846
Ashu Avatar asked Jun 07 '12 19:06

Ashu


People also ask

How do you Autowire a static method?

What you can do is @Autowired a setter method and have it set a new static field. When the bean gets processed, Spring will inject a Foo implementation instance into the instance field foo . It will then also inject the same Foo instance into the setStaticFoo() argument list, which will be used to set the static field.

Can a Spring Bean have static methods?

Yes, A spring bean may have static methods too.

Can we Autowire private fields?

The Spring Framework does allow you to autowire private fields. You do see people doing this. And Spring will perform some reflection magic to perform dependency injection.


2 Answers

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.

like image 55
Andrea T Avatar answered Oct 22 '22 07:10

Andrea T


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

like image 31
Tomasz Nurkiewicz Avatar answered Oct 22 '22 07:10

Tomasz Nurkiewicz