Autowiring

In Spring, there are several types of Autowiring modes available to use, including byName, byType, and byConstructor.

* ByName Autowiring:

With this mode of Autowiring, Spring matches beans based on the name of the bean. The name of the bean being injected should match the name of the setter method or the constructor parameter. Here's an example:

                
    @Component
    public class MyService {
        @Autowired
        private MyRepository myRepository;
    }
                
            

In this example, ByName Autowiring is used to inject the MyRepository bean into the MyService class based on by name. Spring looks for a bean with the name myRepository and injects it into the field.

* ByType Autowiring:

With this mode of Autowiring, Spring matches beans based on their type. If there is only one bean of the required type, it will be injected. If there are multiple beans of the required type, Spring will throw an exception. Here's an example:

                
    @Component
    public class MyService {

        @Autowired
        private AddressRepository homeAddress;

        @Autowired
        private AddressRepository officeAddress;
}
                
            

In this example, byType Autowiring is used to inject the AddressRepository bean into the MyService class based on its type. Spring looks for a bean of type AddressRepository and injects it into the field.

* ByConstructor Autowiring:

With this mode of Autowiring, Spring matches beans based on the types of the constructor arguments. Here's an example:

                
    @Component
    public class MyService {

    private final MyRepository myRepository;
    private final OtherDependency otherDependency;

        @Autowired
        public MyService(MyRepository myRepository, OtherDependency otherDependency) {
            this.myRepository = myRepository;
            this.otherDependency = otherDependency;
        }
    }
                
            

In this example, byConstructor Autowiring is used to inject the MyRepository and OtherDependency beans into the MyService class based on the types of the constructor arguments. Spring looks for beans of type MyRepository and OtherDependency and injects them into the constructor.

Note: The @Autowired annotation can be applied to either the setter method, field or constructor, depending on the Autowiring mode that you want to use.

Overall, Autowiring is a powerful feature of the Spring Framework that can simplify the process of injecting dependencies into your objects. It can make your code more concise and readable, but it's important to use it judiciously to ensure that your code remains easy to understand and maintain.