Spring frameworks provides autowiring feature, it enables you to inject the object dependency implicitly. It internally uses setter or constructor injection.
it helps cut down on the amount of XML configuration you write for a big Spring based application.
Types of Autowiring
There are couple of autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection. Some of them are
This is default setting which means no autowiring and you should use explicit bean reference for wiring.
Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file.
Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file.
Similar to byType, but type applies to constructor arguments.
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType
XML Based example
We have below two classes, CarInsurance and CarOrder and in CarOrder class we want to inject CarInsurance class,
Next, our goal is to inject CarInsurance bean to CarOrder bean..
The above configuration, the bean carOrder will get the CarInsurance bean reference via auto wiring by name as we declared the property name in CarOrder, the second bean carOrder1 bean will get the CarInsurance reference via constructor as we defined the Constructor in CarOrder.
Annotation based Autowiring example
Annotation based auto wiring is very easy and it helps to inject dependencies via @Autowired annotation., see this example
1. Do the component scan in our Spring configuration
2. Create Java components with @Component annotaions
The CustomerDetails class we are using the @Autowired annotation to inject Customer bean, let us execute this program
3. Test class
Download this complete example..