Spring autowire byName xml example

The Spring autowire byName xml example shows you how to use Spring autowire by name. When the autowire by name mode is enabled, Spring attempts to find out a bean in the spring bean configuration file with the same name as the property that needs to be autowired. If a bean found with with id as property name then that class object will be injected into that property by calling setter injection. For example, suppose we have a Fruit bean that exposes a Country property. Spring container will look for the Country bean, if one exists and wire it automatically. If no matching bean is found the that property remains un-wired, but never throws any exception.

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 By Name
Here, we must enable the spring autowire by name. The wiring is done by name, so that if there is a bean with the same name as the property in the class, it is wired automatically.

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

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

That’s all on the Spring autowire byName xml example

Spring Autowire Doc

Download complete source code, click link below

spring-autowire-byname-xml-example-1.zip (267 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons