Injection by constructor is equivalent to passing values to constructor parameters.
SetThe disadvantage of injection is that it is impossible to clearly express which attributes are required and which are optional.
The advantage of constructor injection is that by constructing a forced dependency, it is impossible to instantiate
Completely or unusableBean.
MemberbeanDefine four variables,
PrivateStringName;
Private Double Salary;
PrivateDeptDept;
PrivateStringSex;
Add the constructor andTostringMethod: convenient test
Dept:
PrivateStringDname;
PrivateStringDeptno;
UseSetMethod Injection
Method 1: assign values based on the index.0Starting:
<Bean
Id = "memberbean" Class = "www. csdn. spring01.constructor. memberbean">
<Constructor-Arg Index = "0" value = "" "/>
<Constructor-Arg Index = "1" value = "3500"/>
<Constructor-Arg Index = "2"Ref ="Dept "/>
<Constructor-Arg Index = "3" value = "male"/>
The second method is to pass the value according to the type
This method is basically not very suitable, because a class can have several variables of the same basic type, it is easy to confuse which parameter the value is passed to, so do not use this method properly:
<Constructor-Arg type = "Java. Lang. String" value = "Liu Xiaogang"
<Constructor-Arg type = "Java. Lang. Double" value = "3500"/>
<Constructor-Arg type = "www. csdn. spring01.constructor. Dept"Ref ="Dept "/>
<Constructor-Arg type = "Java. Lang. String" value = "male"/>
Method 3: Pass values by parameter name: (recommended)
In these methods, I feel that this method is the most practical. It transfers values based on the name. Therefore, if the name is correct, the value can be obtained.
<Constructor-Arg name = "name" value = "" "/>
<Constructor-Arg name = "salary" value = "3500"/>
<Constructor-Arg name ="Dept"Ref ="Dept "/>
<Constructor-Arg name = "sex" value = "male"/>
Method 4: directly pass the value
Assign values directly to parameters. This method is also arranged in order, so once the positions are changedBugThis method is already very primitive.
<Constructor-Arg value = "" "/>
<Constructor-Arg value = "3500" type = "codeph" text = "codeph"/>
<Constructor-Arg ref = "Dept"/>
<Constructor-Arg value = "male "/>
</Bean>
<Bean id = "Dept" class = "www. csdn. spring01.constructor. Dept">
<Property name = "dname" value = "Beihang"/>
<Property name = "deptno" value = "00001"/>
</Bean>S