Spring Bean Autowire by byName
Practically bean dependencies are explicitly set in bean configuration files and it is really is a good practice to follow. But Spring is capable of automatically resolving dependencies at runtime. This automatic resolution of bean dependencies is also called autowiring. This type of bean dependencies can also be referred to as collaborating beans or just as collaborators.
There are 5 different types of autowiring modes which are ‘no’, ‘byName’, ‘byType’, ‘constructor’, and ‘autodetect’. In this post, I am taking down ‘byName‘ mode.
Autowiring by name allows a property to be autowired such that it will inspect the container and look for a bean named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire by name, and it contains a “departmentBean” property (i.e. it has a setDepartmentBean(..) method), container will look for a bean definition named departmentBean, and if found, use it to set the property.
Sections in this post: Bean definitions Autowire dependency using autowire="byName" Test the dependency
Bean definitions
A typical bean configuration file (e.g. applicationContext.xml) will look like this:
|
Autowire dependency using autowire=”byName”
In above configuration, I have enabled the autowiring by name for ’employee’ bean. It has been done using:
autowire="byName"
Let’s see the code.
|
And DepartmentBean looks like this which has been set:
|
Test the dependency
To test that bean has been set properly, run following code:
|
Clearly, dependency was injected by name successfully.
post a comment