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. 创建运行类

 

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配制文件中不同的属性指定选择相应的构造方法。

         

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值