@Autowired In Spring Boot

pratik Raghuwanshi
Javarevisited
Published in
3 min readMay 30, 2020

Hello programmers,

There is no java developer is world who never listen word Spring, Spring is a Framework, open-source platform to provide comprehensive programming and configuration model. whenever I go to take Mock interview in my collages, my favorite question is what is Autowired Annotation in spring and how it works ?

I always get common answer that Autowired uses Dependency Injection, but whenever i ask can u elaborate your answer then there is silence, as per me in simple words Autowired provides us Object initialization. lets talk more about Autowired annotations.

Spring tells us that , “Hey developers don’t think about to create objects, I will provide objects to you, so you can focus more on core logic”. So here question arrives in our mind how spring get to know for which class’s object require to developer and in which class. so here another one Annotations comes in Picture i.e @Component . so lets discuss how it works

suppose I have a Controller class as CovidDataController and a helper class where I can write all my logic to call third party API to get data and do some sort of calculation on It.

so I will create a helper class as CovidDataHelper and annotate it with @Component , create a method in that class as getCovidData() and processCovideData() In getCovideData I will Hit third party API to get data and in processCovideData() I will process that Data.

Controller Class
Helper Class

All set up, now lets touch up how it works Internally,

So there is a Spring container which contains object and objects in spring container class are called as Beans, so when we annotated a class with @component , It will create a object (bean) for that class

so in our example when we written @component on helper class so at the time of application is in run mode it will create a bean for Helper class in spring container. and In our controller class there is dependency for Helper class, so how our controller class beans knows that there is helper class bean is present in container, we need to told controller class bean to find out helper class bean and use it, so here @Autowired comes in picture when we write @Autowired above the variable of type helper class It will start to find bean for helper class and Inject it into that variable so your variable in Initialized and ready to use.

Thanks For reading.

--

--