Constructor injection of study notes

Constructor injected bean

I used to use the method of calling setxxx to inject, and today I learned the method of injecting through the constructor

Explain by comparing the code of the two injection methods of set and constructor (the following code id value and other names are not rigorous , just to achieve an explanation)

xml file:

set:

<bean id="setmethod" class="XXXXXXX">

<property name="name">
<value>余飞</value>

</property>

Constructor method:

                <bean id="construct" class="it.construct.ConstructBean">
<!-- index starts from zero and determines its parameter position , type is its parameter type -->
          <constructor-arg index="0" type="java.lang.String" value="Yu Fei"></constructor-arg>
          <constructor-arg index="1" type="int" value="04152015"/> <!--Select constructor It sets several construction parameters according to its parameters, which is the <constructor-arg /> statement -->
         

</bean>

When there are multiple constructors, the xml file will match the response parameter constructor according to the number of <constructor-arg xxxxx /> statements in <bean></bean>

In the bean class:

set:

The set method does not change, there is no constructor requirement

Constructor :

If you want to inject with the constructor, you need to change the constructor method in the bean class

If there is a constructor with two parameters, you need to write two constructor parameters

Class ConstructBean{
 public ConstructBean(String name,int id) {// This constructor has two parameters, if the bean configured in the xml file has two parameters, this constructor will be called to inject this.name=name;// There is an additional assignment statement here, because injected through the constructor, you need to assign this.id=id in the constructor;



  }

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325602174&siteId=291194637