装配Bean(四)

本文介绍Spring框架中使用构造函数进行依赖注入的方法,并对比了set注入的不足之处。通过示例展示了如何配置XML来实现构造函数注入,确保了依赖关系的明确性和bean实例化的完整性。

思考: 目前我们都是通过set方式给bean注入值,spring还提供其它的方式注入值,比如通过构造函数注入值 !

通过构造函数注入值

beans.xml 关键代码:

<!-- 配置一个雇员对象 -->

<bean  id="employee"  class="com.hsp.constructor.Employee">

<!-- 通过构造函数来注入属性值 -->     

<constructor-arg index="0"  type="java.lang.String"   value="大明" />

</bean>

set注入的缺点是无法清晰表达哪些属性是必须的,哪些是可选的,

构造注入的优势是通过构造强制依赖关系,不可能实例化不完全的或无法使用的bean

例子:


package com.hsp.constructor;

public class Employee {

	private String name;
	private int age;
	
	
	public Employee(String name, int age) {
		
		System.out.println("Employee(String name, int age) 函数被调用..");
		this.name = name;
		this.age = age;
	}
	
	public Employee(String name) {
		System.out.println("Employee(String name) 函数被调用..");
		this.name = name;
	}

	public Employee(int age) {
		System.out.println("Employee(int age) 函数被调用..");
		this.age = age;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

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

	<!-- 配置一个雇员对象 -->
	<bean id="employee" class="com.hsp.constructor.Employee">
		<!-- 通过构造函数来注入属性值 -->
		<constructor-arg index="0" type="java.lang.String" value="大明" />
		<constructor-arg index="1" type="int" value="25" />
	</bean>

</beans>

package com.hsp.constructor;

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

public class App1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/constructor/beans.xml");
	
		Employee ee=(Employee) ac.getBean("employee");
		System.out.println(ee.getName()+" "+ee.getAge());
	
	}

}

Employee(String name, int age) 函数被调用..
大明 25

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZHOU_VIP

您的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值