Spring-Spring CoreNo Comments

As mentioned in previous post Auto Scanning bean, Today we will know more about Autowiring in Spring :

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>.

In Spring, 5 Auto-wiring modes are supported.

  • no – Default, no auto wiring, set it manually via “ref” attribute
  • byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.
  • byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.
  • constructor – byType mode in constructor argument.
  • autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.

Examples

A Car and Fuel object for auto wiring demonstration.

Car : 

Fuel :

1. Auto-Wiring ‘no’

This is the default mode, you need to wire your bean via ‘ref’ attribute.

2. Auto-Wiring ‘byName’

Auto-wire a bean by property name. In this case, since the name of “fuel” bean is same with the name of the “car” bean’s property (“fuel”), so, Spring will auto wired it via setter method – “

“.

See full example – Spring Autowiring by Name.

3. Auto-Wiring ‘byType’

Auto-wire a bean by property data type. In this case, since the data type of “fuel” bean is same as the data type of the “car” bean’s property (Fuel object), so, Spring will auto wired it via setter method – “

“.

See full example – Spring Autowiring by Type.

4. Auto-Wiring ‘constructor’

Auto-wire a bean by property data type in constructor argument. In this case, since the data type of “fuel” bean is same as the constructor argument data type in “car” bean’s property (Fuel object), so, Spring auto wired it via constructor method – “

“.

See full example – Spring Autowiring by Constructor.

5. Auto-Wiring ‘autodetect’

If a default constructor is found, uses “constructor”; Otherwise, uses “byType”. In this case, since there is a default constructor in “Car” class, so, Spring auto wired it via constructor method – “

“.

See full example – Spring Autowiring by AutoDetect.

Note
It’s always good to combine both ‘auto-wire’ and ‘dependency-check’ together, to make sure the property is always auto-wire successfully.

Conclusion

In my view, Spring ‘auto-wiring’ make development faster with great costs – it added complexity for the entire bean configuration file, and you don’t even know which bean will auto wired in which bean.

In practice, i rather wire it manually, it is always clean and work perfectly, or better uses @Autowired annotation, which is more flexible and recommended.

 

 

 


Be the first to post a comment.

Add a comment