@Autowired Annotation



 What is @Autowired?

@Autowired is an annotation in the Spring Framework that simplifies Dependency Injection. When we use @Autowired, Spring automatically injects the required objects or dependencies for a particular class. This helps keep our code cleaner and more modular, eliminating the need to manually create dependent objects.

Dependency Injection refers to the process where required objects for a class are provided directly by the Spring container. Using @Autowired, this process becomes simple and automated.


How @Autowired Works

When the Spring container encounters @Autowired in a class, it locates the field or method needing the dependency and injects the required object from the Spring container. This can be done by adding @Autowired to constructors, fields, or setter methods. Here’s an example to illustrate how it works.


Example

Annotations in Pets Class:

  • @Component: Tells Spring that Pets is a Spring Bean, so Spring will manage it.
  • @Autowired: Injects an instance of Dog into Pets automatically.
  • @Scope("prototype"): Means that every time we request a Pets bean, Spring will create a new instance of it.                                                                                           
Notes: By default in Spring, when you request an object (bean) of a class multiple times, it returns the same instance every time. So, if you change a value in that object, the change will reflect in all references to it because they all share the same single instance. This is called singleton scope.

But when we use @Scope("prototype"), Spring creates a new instance every time you ask for that object. So each instance can have different values without affecting others. For example, if you request a Pets object twice, @Scope("prototype") ensures each has its own unique instance, and any changes made to one won’t show up in the other. This is helpful when you need separate objects for different data or behaviors each time you use the class.

Dog Class


Main Class


Summary

  • @Autowired enables automatic dependency injection by allowing Spring to inject the required objects directly from the Spring container, simplifying the code and eliminating the need to manually create objects. This results in cleaner and more manageable code.
  •  @Autowired can be used on fields, constructors, or setter methods to automatically inject dependencies.
  •  Along with @Component, which registers the class as a bean in the Spring container, @Autowired links these beans together by injecting one into another where needed.


















Comments