Spring autowire by constructor xml example

The Spring autowire by constructor xml example shows you how to use autowire constructor xml configuration. If we enable the autowire constructor, Spring will look up exactly one bean of property in the container then autowire a property using constructor with arguments. If there are multiple beans of the same type, Spring will throw NoUniqueBeanDefinitionException exception. Whereas the property will not be initialized if there are no matching beans. The autowiring constructor is enquivalent with the autowiring byType.

Let’s begin:

Create beans for autowiring
We create two beans Fruit and Country. The Fruit bean has a property of Country and a constructor with arguments.

Notice: Don’t forget the constructor because we are using constructor 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 Constructor
Here, we must enable the spring autowire by constructor. The wiring is done by constructor, 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 by constructor xml example

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

That’s all on the Spring autowire by constructor xml example

Spring Autowire Doc

Download complete source code, click link below

spring-autowire-by-constructor-xml-example.zip (265 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons