Automatic Assembly in Spring
Automatic Assembly
We have learned that in constructor-arg and property assembly, you must configure the corresponding attributes and values or references. If you are in a complicated project, the XML configuration will become complicated, automatic Assembly can be implemented with fewer configurations. The autowire attribute is mainly controlled by bean autowire. The value of autowire can be:
ByName: indicates the bean with the same name as the automatic assembly id of the property.
For example, there is a dog class in People.
ByType: different from byName, the type is used to select the Assembly attributes.
<Beanid = "dog1" class = "Dog">
If we have multiple Dog beans, byType will not be assembled at this time, but an exception will be thrown. For this reason, we can set the bean first assembled, set the primary attribute of the Dog bean to false (true by default), and set autowrie-candidate to false to exclude the bean from the Assembly.
Constructor: constructor-arg assembly is no longer required by the constructor assembly. When we assemble a bean, use constructor, then the bean will look for the parameters that can be used in the constructor. If there are multiple parameters, an exception will be thrown. Note: constructor-arg cannot be used at this time.
Autodetect: automatic assembly. The constructor is selected first. If not, select byType.
If you need to select the same default assembly method for all beans, you can use the default-autowire attribute in the beans element to specify
We usually use a hybrid mode of manual assembly and automatic assembly.