Spring has four kinds of automatic assembly
Bytype
Set autowire= "Bytype", the spring container will automatically find the bean's set method, and then assemble the bean in the bean configuration to the computer of the CPU type. If you find multiple bean,spring of the same type, the exception is reported.
package com.ydoing.demo;publicclass Computer { private CPU cpu; publicvoidsetCpu(CPU cpu) { this.cpu = cpu; } publicvoidstart() { System.out.println("CPU name is: " + cpu.getName()); }}
Bean configuration
<bean id="computer" class="com.ydoing.demo.Computer" autowire="byType" /> <bean id="cpu" class="com.ydoing.demo.CPU"> <constructor-arg value="Intel" /> </bean>
ByName
Set autowire= "ByName", the spring container automatically finds the Bean's set method, sets the post name as the Bean's ID (this refers to the ID of the CPU). Then go to the bean configuration and look for the bean with the CPU ID, and assemble it into computer.
<bean id="computer" class="com.ydoing.demo.Computer" autowire="byName" /> <bean id="cpu" class="com.ydoing.demo.CPU"> <constructor-arg value="Intel" /> </bean>
Constructor
Set autowire= "Constructor", the spring container will automatically find the Bean's constructor, and the appropriate bean Assembly will be found in Bytype way.
package com.ydoing.demo;publicclass Computer { private CPU cpu; publicvoidsetCpu(CPU cpu) { this.cpu = cpu; } publicComputer(CPU cpu) { this.cpu = cpu; } publicvoidstart() { System.out.println("CPU name is: " + cpu.getName());
Bean configuration:
<bean id="computer" class="com.ydoing.demo.Computer" autowire="constructor" /> <bean id="cpu" class="com.ydoing.demo.CPU"> <constructor-arg value="Intel" /> </bean>
AutoDetect
If the object does not have a parameterless construction method, the automatic assembly method of constructor is automatically selected for construction injection. If the object contains a parameterless construction method, the automatic assembly method of Bytype is automatically selected for setter injection.
No
Automatic assembly feature not supported
Default
Represents the default value for automatic assembly with the upper-level label. If there are multiple profiles, the automatic assembly of each configuration file is independent.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Spring Automatic Assembly