Spring依赖注入方式---- 构造方法注入

Spring通过构造方法依赖注入

1.  创建一个Person

package com.spring.bean;
public class Person {
	private String name;
	private String address;
	private double height;
	private int weight;
	
	public Person(String name, String address, double height) {
		super();
		this.name = name;
		this.address = address;
		this.height = height;
	}
	
	public Person(String name, String address, int weight) {
		super();
		this.name = name;
		this.address = address;
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", address=" + address + ", height=" + height + ", weight=" + weight + "]";
	}
	
	
}

2. 创建spring 配制xml

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

	
	<!-- 通过构造器注入属性-->
	<!-- 1. 通过index属性指定要注入的属性值,默认会选择靠前的构造器注入 -->
	<bean id="person1" name="person" class="com.spring.bean.Person">
		<constructor-arg value="matt" index="0"></constructor-arg>
		<constructor-arg value="上海" index="1"></constructor-arg>
		<constructor-arg value="172" index="2"></constructor-arg>
	</bean>
	<!-- 2. 通过name属性指定要注入的属性值-->
	<bean id="person2" class="com.spring.bean.Person">
		<constructor-arg value="joy" index="0"></constructor-arg>
		<constructor-arg value="上海" index="1"></constructor-arg>
		<constructor-arg value="59" name="weight"></constructor-arg>
	</bean>
	
	<!-- 2. 通过type属性指定要注入的属性值-->
	<bean id="person3" class="com.spring.bean.Person">
		<constructor-arg value="joy" index="0"></constructor-arg>
		<constructor-arg value="上海" index="1"></constructor-arg>
		<constructor-arg value="59" type="int"></constructor-arg>
	</bean>
</beans>

3. 创建运行类

扫描二维码关注公众号,回复: 710171 查看本文章
package com.spring.bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonMain {

	public static void main(String[] args) {
		ApplicationContext ctx  = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		Person person1 = (Person) ctx.getBean("person1");
		System.out.println(person1);
		
		Person person2 = (Person) ctx.getBean("person2");
		System.out.println(person2);
		
		Person person3 = (Person) ctx.getBean("person3");
		System.out.println(person3);

	}

}

运行结果:

Person [name=matt, address=上海, height=172.0, weight=0]
Person [name=joy, address=上海, height=0.0, weight=59]
Person [name=joy, address=上海, height=0.0, weight=59]

注, 可以通过spring配制文件中不同的属性指定选择相应的构造方法。

         

猜你喜欢

转载自jarvi.iteye.com/blog/2266745