美文网首页
3.如何通过实体类中的有参构造器注入

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

作者: 小竹猫 | 来源:发表于2018-12-21 11:22 被阅读0次

    实体类:

    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]

    相关文章

      网友评论

          本文标题:3.如何通过实体类中的有参构造器注入

          本文链接:https://www.haomeiwen.com/subject/erkmkqtx.html