Spring Autowiring Types

Spring Autowiring Types

In Spring framework, you can wire beans automatically. To enable it, just define the “autowire” attribute inside tag, also you can define autowire through annotation.

<bean id=”userController” autowire=”byType” />

auto-wire

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”.

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 “userService” bean is same with the name of the “userController” bean’s property (“userService”), so, Spring will auto wired it via setter method – “setUserService(UserService userService)“.

3. Auto-Wiring ‘byType’

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

4. Auto-Wiring ‘constructor’

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

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 “userController” class, so, Spring auto wired it via constructor method – “public UserController(UserService userService)”.

 

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

Your email address will not be published. Required fields are marked *