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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

packagecom.javabycode.spring.core.autowired;

publicclassFruit{

privateStringname;

privateCountry country;

publicvoidsetName(Stringname){

this.name=name;

}

publicvoidsetCountry(Country country){

this.country=country;

}

@Override

publicStringtoString(){

return"Fruit{"+

"name='"+name+'\''+

", country="+country+

'}';

}

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

packagecom.javabycode.spring.core.autowired;

publicclassCountry{

privateStringname;

publicvoidsetName(Stringname){

this.name=name;

}

@Override

publicStringtoString(){

return"Country{"+

"name='"+name+'\''+

'}';

}

}

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.