How Autowiring Works in Spring


In this tutorial, We will see how autowiring works in spring and this is also one of most common interview questions in spring framework.

In Spring, All beans are managed inside a container, which is Application Context.

For Web Applications, Application Context is bootstrapped from startup listener and all beans will be loaded into Application with below criteria:

  • Classes marked with Annotations : @Component, @Service, @Controller, @RestController @Repository etc
  • Methods marked with @Bean annotations under Configuration classes

Autowiring Process

  • Autowiring is a feature of the Spring framework that allows the framework to automatically inject dependencies into a class.
  • In Spring, Beans are created or managed by Application Context, not by programmer
  • Autowiring works by placing an instance of object bean into the desired field in an instance of another bean through constructor or setter.
  • These classes should be beans and they should be defined to live in the application context.
  • What is “living” in the application context? This means that the context instantiates the objects, not you. I.e. – you never make new UserServiceImpl() – the container finds each injection point and sets an instance there.

Spring supports below Annotations to autowire objects:

  1. @Autowired annotation: This annotation can be used on fields, setter methods, and constructors. When used on a field, Spring will automatically set the value of the field to the bean of the required type. When used on a setter method, Spring will call the method and pass in the bean of the required type. When used on a constructor, Spring will pass in the bean of the required type when creating an instance of the class.
  2. @Inject annotation: This annotation is similar to @Autowired and can also be used on fields, setter methods, and constructors. It serves the same purpose and it’s a JSR-330 standard annotation
  3. @Resource annotation: This annotation can be used on fields and setter methods and it’s similar to @Autowired. But it also allows to specify the name of the bean to be injected, in case there are multiple beans of the same type in the context.
  4. @Value annotation: This annotation can be used to inject a specific value, coming from properties file for example, into a field.

When a class is annotated with @Autowired, Spring will search for a bean of the required type in the application context, and if it finds one, it will inject it into the class. If there are multiple beans of the same type, Spring will choose one based on its configuration. If no bean of the required type is found, Spring will throw an exception.

It’s important to note that autowiring is not limited to classes annotated with @Autowired. It can also be used with other Spring annotations such as @Service, @Repository, and @Controller.

Thanks for Reading..