Thursday 28 March 2019

Spring | Why can't we autowire static fields in 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 a global state - also evil).

How can we achieve it?
We can achieve it by assigning the value in the static field using setters. See code snapshot below. However, it should be avoided as mentioned earlier.

    @Component("NewClass")
    public class NewClass{
        private static SomeThing someThing;

        @Autowired
        public void setSomeThing(SomeThing someThing){
            NewClass.someThing = someThing;
        }
    }


Related Posts Plugin for WordPress, Blogger...