Spring Bean Autowire byType
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 ‘byType‘ mode.
Autowiring by type allows a property to be autowired if there is exactly one bean of the property type in the container. If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean.
If there are no matching beans, nothing happens; the property is not set. If this is not desirable, setting the dependency-check="objects"
attribute value specifies that an error should be thrown in this case.
Sections in this post: Define Beans in context file Bean classes Test the dependency
Define Beans in context file
A typical bean configuration file (e.g. applicationContext.xml) will look like this:
|
Bean classes
In above configuration, I have enabled the autowiring by type for ’employee’ bean. It has been done using:
autowire="byType"
Now lets see the code of these beans.
|
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 type successfully.
post a comment