Spring中Bean的注入方式详解(2)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->

<!-- 配置对象 -->
    <bean>
        <constructor-arg type="String">
            <value>Kevin</value>
        </constructor-arg>
        <constructor-arg type="Integer">
            <value>20</value>
        </constructor-arg>
    </bean>
   
</beans>

  Spring的配置文件采用和元素标签顺序无关的配置策略,因此可以在一定程度上保证配置信息的确定性。

  那么当bean中的构造函数的多个类型参数一样时,按照类型匹配入参的这种方式容易产生混淆,此时就需要使用另一种方式:按照索引匹配入参。

【按照索引匹配入参】

编写bean代码:

package com.Kevin.bean;
/**
 * 编写bean测试按照索引方式入参
 * @author Kevin
 *
 */

public class Student {
    private String name;
    private String gender;
    private Double score;
    public Student(String name, String gender, Double score) {
        super();
        this.name = name;
        this.gender = gender;
        this.score = score;
    }
   

}

配置文件编写如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->

<!-- 配置对象 -->
    <bean>
        <constructor-arg index="0" value="Kevin"></constructor-arg>
        <constructor-arg index="1" value="Male"></constructor-arg>
        <constructor-arg index="2" value="66"></constructor-arg>
    </bean>
   
</beans>


Tips:在属性注入时,Spring按java bean的规范确定配置属性和对应的setter方法,并使用java反射机制调用属性的setter方法完成属性注入。但java反射机制并不会记住构造函数的入参名,因此我们不能通过制定构造函数的入参名称来进行构造函数的配置,所以我们只能通过入参的类型及索引来间接完成构造函数的属性注入。

【联合使用类型和索引匹配入参】

  在某些复杂的配置文件当中,需要使用type和index同时出马才能完成构造函数的参数注入。下面使用一个实例来演示。

编写bean:

package com.Kevin.bean;
/**
 * 编写bean测试联合使用类型和索引匹配入参
 * @author Kevin
 *
 */

public class Teacher {
    private String name;
    private String address;
    private double salary;
    private int age;
    public Teacher(String name, String address, double salary) {
        super();
        this.name = name;
        this.address = address;
        this.salary = salary;
    }
    public Teacher(String name, String address, int age) {
        super();
        this.name = name;
        this.address = address;
        this.age = age;
    }
   

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/4f30f7ef1566725949f1f3149da0318c.html