Spring autowire byType xml example

This spring autowire byType xml example shows you how to use Spring autowire byType. If we enable the autowire byType, Spring will attempts to find out exactly a bean which is matching with the property and autowire that property automatically. Whereas Spring will throw a NoUniqueBeanDefinitionException exception if there are multiple beans of the same type.

Create beans for autowiring
We create two beans Fruit and Country. The Fruit bean has a property of Country and this property has a setter method.

Notice: Don’t forget the setter method because we are using setter based DI otherwise the injection will not work

Next, we create Country bean which is autowired into the Fruit bean.

Spring bean Explicitly wiring Configuration

Now, we can declare the bean explicitly wiring using the element which has a same name as name of the property and a ref attribute that references the bean to be wired.

Spring bean Autowire ByType
Here, we must enable the spring autowire by type. The wiring is done by type, so that if there is a bean with the same type as the property in the class, it is wired automatically.

Demo Spring application
Create the main class to test the Spring autowire byType xml example

Run the main above, the console will print the following message

That’s all on the Spring autowire byType xml example

References
Spring Autowire Doc

Download complete source code, click link below

spring-autowire-byType-xml-example.zip (9 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons