Spring Bean Autowire by Autodetect
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 ‘autodetect‘ mode.
Autowiring by autodetect uses either of two modes i.e. constructor or byType modes. First it will try to look for valid constructor with arguments, If found the constructor mode is chosen. If there is no constructor defined in bean, or explicit default no-args constructor is present, the autowire byType mode is chosen.
Sections in this post: Autowire dependency using autodetect Create no-args constructor in bean Test the dependency
Autowire dependency using autodetect
Autowiring by autodetect is enabled by using autowire=”autodetect” in bean definition in configuration file (i.e. application-context.xml).
A typical bean configuration file will look like this:
|
Create no-args constructor in bean
In above configuration, I have enabled the autowiring by autodetect for ’employee’ bean. To use the byType mode, I must define either default constructor or no constructor at all.
|
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 autodetect successfully.
post a comment