Spring属性注入之set方法注入对象

本文通过一个具体的示例展示了如何在Service类中调用Dao类的方法,并使用Spring框架进行依赖注入的过程。首先定义了Dao类及其show方法,接着在Service类中通过set方法注入Dao实例并调用其show方法,最后通过测试类加载Spring配置文件,获取Service实例并执行测试。

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

应用场景:需要在Service中调用Dao的show方法

1.编写Service和Dao类

Dao类
package com.maty.property; 
/** 
* @author maty  e-mail:512181558@qq.com
* @version 创建时间:2018年5月16日 下午3:37:12 
* 类说明
*/
public class Dao
{
	public void show()
	{
		System.out.println("Dao类中的show方法执行了");
	}
}

Service类

package com.maty.property;import org.junit.Test;/** * @author maty  e-mail:512181558@qq.com* @version 创建时间:2018年5月16日 下午3:36:57 * 类说明 */public class Service{ private Dao dao; //编写的set方法 public void setDao(Dao dao) { this.dao = dao; } //在Service类中引用Dao类中的show方法 @Test public void test() { dao.show(); }}

2.applicationContext.xml编写

<!-- 将Dao类注入到Spring中 -->
	<bean id="dao" class="com.maty.property.Dao"></bean>
	
	<!-- 将Service类注入到Spring -->
	<bean id="service" class="com.maty.property.Service">
		<!-- 将Dao注入到Service中
			name属性值为需要被注入的Dao的实例名称
			ref属性值为对应的bean的id值
		 -->
		<property name="dao" ref="dao"></property>
	</bean>

3.测试类的编写

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

import com.maty.property.PropertyConstructor;
import com.maty.property.Service;
import com.maty.property.User;

/** 
* @author maty  e-mail:512181558@qq.com
* @version 创建时间:2018年5月16日 下午12:23:01 
* 类说明 
*/
public class MyTest
{
	public static void main(String[] args)
	{		
		//第一步:加载xml文件
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Service service = (Service) context.getBean("service");
		service.test();
	}
}

4.执行结果

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Dao类中的show方法执行了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值