3.如何通过实体类中的有参构造器注入

实体类:

public class Person {
    private String name;
    private int age;
    private double type;
    public Person(){
        
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Person(String name,double type){
        this.name=name;
        this.type=type;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", type=" + type + "]";
    }
    
}

能够看到,Person这个类有两个有参构造器,不过不用慌,我们在xml中设置bean,使用constructor-arg标签

<bean id="p1" class="com.igeek.lesson3.Person" scope="prototype">
        <constructor-arg value="李四" index="0"></constructor-arg>
        <constructor-arg value="18" type="int"></constructor-arg>
    </bean>

constructor-arg:通过构造函数注入。

  • value 表示你要注入的属性的值
  • index 表示参数下标
  • type 指定类型
  • 通过scope属性 可以执行 spring IOC容器 创建对象的类型.prototype
    原型模式(多例模式) 每次调用IOC容器的getBean方法, 就会返回一个新的对象()
ApplicationContext ac = new ClassPathXmlApplicationContext("com/igeek/lesson3/beans.xml");
        Person p1 = (Person) ac.getBean("p1");
        System.out.println(p1);

输出结果

Person [name=汤姆, age=18]

另外,若想注入较为特殊的样式:

<bean id="p3" class="com.igeek.lesson3.Person">
        <constructor-arg index="0">
            <value><![CDATA[<小马>]]></value>
        </constructor-arg>
        <constructor-arg type="int">
            <value>13</value>
        </constructor-arg>
    </bean>

输出结果:

Person [name=<小马>, age=13, type=0.0]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容