What is auto wiring?

Auto wiring is method of creating an instance of an object and "by concept" injecting that instance on a specific class that uses it. We need not to inject manually in xml as we did in address in student in xml automatically it detects where to get injected.

Now we will see examples with auto wiring. This can be achieved in below ways.

  • By using autowire attribute in xml

    • autowire byName – For this type of autowiring, setter method is used for dependency injection. Also the variable name should be same in the class where we will inject the dependency and in the spring bean configuration file.

    • autowire byType – For this type of autowiring, class type is used. So there should be only one bean configured for this type in the spring bean configuration file

    • autowire by constructor – This is almost similar to autowire byType, the only difference is that constructor is used to inject the dependency.

Try below changes to understand this:

  • Remove address injection from Student bean in xml file.Code should look like this.

ByName means address from student is matching with address bean id from xml so it will be injected. In our case to address and address1 both matching but exact matching name will be injected (address not address1).

Now try byType for this change xml like this we may see errors due to this. As Types are matching for both beans address and address1 so remove one it will start working.