Day7——DI依赖注入构造器方法

一. 回顾

前面Day6——DI依赖注入set方法讲到了IOC容器通过set方法给bean对象赋值。今天来讲通过构造器给bean对象赋值。

二. 原理

Person.java

public Person(String name, double salary) {
		System.out.println("调用了形参为String,double类型的构造器");
		this.name = name;
		this.salary = salary;
	    }

		public Person(String name, int salary) {
			System.out.println("调用了形参为String,int类型的构造器");
			this.name = name;
			this.salary = salary;
		}

applicationContext.xml

<bean id="person2" class="com.atguigu.spring.bean.Person">
         <constructor-arg value="老王" index=”0“></constructor-arg>
         <constructor-arg value="10000" type="int" index=”1“></constructor-arg>
    </bean>
    
    <bean id="person3" class="com.atguigu.spring.bean.Person">
         <constructor-arg value="老李" ></constructor-arg>
         <constructor-arg value="20000" type="double"></constructor-arg>
    </bean>

解释: 使用<constructor-arg>标签赋值,通过type属性指定形参的类型,spring就可以判断出应该使用哪个构造器去new这个Bean对象。通过index属性指定参数的位置,是第一个参数还是第二参数还是第三第四。。。

发布了177 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40634846/article/details/104099114