spring 基础回想 tips01

本文详细介绍了Spring框架中依赖注入的两种方式:属性注入和构造方法注入。解释了何时使用setter和getter方法,以及如何利用构造器进行依赖项的传递。同时,还提供了具体的Java代码示例和Spring配置文件示例,帮助读者理解依赖注入的具体实现。

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

spring 属性注入时,类中必须有setter 和 getter方法。

spring配置文件里:

java业务类中注入DAO:

	private StudentDao studentDao;
	// 通过属性注入
	public StudentDao getStudentDao() {
		return studentDao;
	}

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

 

spring 构造方法注入时,要注明属性,类中不须要setter 和 getter方法,可是须要构造器对其进行赋值。

<!-- 定义studentService的bean实例 ,并注入studentDao -->
	<bean id="studentService" class="com.michael.spring.business.student.StudentServiceImpl">		
		<constructor-arg ref="studentDao"></constructor-arg>
	</bean>

java业务类中注入DAO:

private StudentDao studentDao;

	// 通过属性注入

	public StudentDao getStudentDao() {
		return studentDao;
	}

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

 

属性注入时,能够对其进行赋值,而且返回值由定义的属性值确定。

Java类中定义:

private long youknow;

	public long getYouknow() {
		return youknow;
	}

	public void setYouknow(long youknow) {
		this.youknow = youknow;
	}


 

<property name="youknow">
	<value>245</value>
</property>

或者直接这样写:

<property name="youknow" value="245"></property>


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值