In Spring and Spring Boot, @Autowired

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2024-01-13 09:32:55 Viewed : 166


In Spring and Spring Boot, @Autowired is an annotation used for automatic dependency injection. It can be applied to fields, methods, and constructors. When a Spring application starts, the Spring IoC (Inversion of Control) container automatically injects the dependencies marked with @Autowired.

In the context of Spring Boot, which is an extension of the Spring framework designed to simplify the development of production-ready applications, @Autowired is commonly used to inject dependencies into various components, such as controllers, services, repositories, and more.

Here is a brief overview of how @Autowired can be used in a Spring Boot application:

  1. Field Injection:

    java
    @RestController public class MyController { @Autowired private MyService myService; // Controller methods using myService... }
  2. Setter Injection:

    java
    @Service public class MyService { private AnotherService anotherService; @Autowired public void setAnotherService(AnotherService anotherService) { this.anotherService = anotherService; } // Service methods using anotherService... }
  3. Constructor Injection:

    java
    @Service public class MyService { private AnotherService anotherService; @Autowired public MyService(AnotherService anotherService) { this.anotherService = anotherService; } // Service methods using anotherService... }

In the examples above:

  • @Autowired is used to inject instances of the specified type (MyService, AnotherService, etc.) into the annotated fields, methods, or constructor parameters.
  • When @Autowired is used on a constructor, it indicates constructor injection. Spring automatically provides the required dependencies at the time of bean creation.
  • If there is only one bean of the required type in the context, it will be injected. If there are multiple beans of the same type, you may need to use @Qualifier to specify the bean name or use other methods to resolve the ambiguity.

It is worth noting that with modern versions of Spring and Spring Boot, @Autowired is not strictly required. You can use constructor injection without explicitly using @Autowired, as Spring will automatically detect and inject dependencies based on the constructor parameters.

java
@Service public class MyService { private AnotherService anotherService; public MyService(AnotherService anotherService) { this.anotherService = anotherService; } // Service methods using anotherService... }

This is known as constructor-based dependency injection and is considered a best practice.

Search
Sub-Categories
Related Articles

Leave a Comment: