深入学习Spring框架之六属性注入

本文介绍Spring框架中的依赖注入概念,并通过实例演示如何使用setter方法进行属性注入,包括基本类型及对象类型的注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们以及知道怎么通过spring创建Bean对象了,但是我们清楚,一个类它不仅有属性还有一些特定的行为。那么专属于这些类的属性,在Sprin中我们将通过何种方式注入呢?

通常,JavaBean的属性是私有的,同时拥有一套存取器的方法,set和get方法。Spring就是借助属性的set方法来配置属性的值,这就是setter方式注入。

/**
 * 运动员类,他有一个特殊的属性,该属性是对象
 * @author liuyc
 *
 */
public class Player {
	private String name;
	private String age;
	private String subject;
	private Trainer trainer;
	public Player() {
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public Trainer getTrainer() {
		return trainer;
	}
	public void setTrainer(Trainer trainer) {
		this.trainer = trainer;
	}
}
/**
 * 教练类
 * @author liuyc
 *
 */
public class Trainer {
	private String name;
	private String age;
	private String subject;
	public Trainer() {
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
}

配置好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" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="player" class="com.cm2easy.miki.example.chapter1.Player">
		<property name="name" value="林丹" />
		<property name="age"  value="33" />
		<property name="subject" value="羽毛球" />
		<property name="trainer" ref="trainer" />
	</bean>
	<bean id="trainer" class="com.cm2easy.miki.example.chapter1.Trainer">
		<property name="name" value="李永波"/>
		<property name="age" value="54"/>
		<property name="subject" value="羽毛球"/>
	</bean>
</beans>

    上述配置涉及了属性值是普通值和对象的属性注入。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

L小芸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值