Spring三种注入方式(三)

本文介绍了一种通过接口方式实现依赖注入的方法。通过定义接口ISource并实现在Target类中,利用Spring框架进行bean的配置与管理,实现了Source类实例向Target类的注入。最后通过单元测试验证了依赖注入及功能调用的正确性。

通过接口方式注入

建议使用前两种方法

 

Source.java

package com.gary.test;

public class Source {
	
	public void helloWorld(){
		System.out.println("Hello World!");
	}
}

 

 

ISource.java

package com.gary.test;

public interface ISource {
	//方法名任意,方法参数是所依赖对象的类型
	public void injectSource(Source source);
}

 

 

Target.java

 

package com.gary.test;

public class Target implements ISource{
	
	private Source source;
	
	@Override
	public void injectSource(Source source) {
		this.source = source;
	}
	
	public void sayHelloWorld(){
		source.helloWorld();
	}
	
}

 

 

applicationContext.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-2.5.xsd"
	default-autowire="byType">

	<bean id="source" class="com.gary.test.Source" />
	<bean id="target" class="com.gary.test.Target" />
</beans>

 

 

TargetTest.java

package com.gary.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TargetTest {

	static BeanFactory factory = null;
	static Source source = null;
	static Target target = null;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try{
			factory = new ClassPathXmlApplicationContext("applicationContext.xml");
			target = (Target) factory.getBean("target");
			source = (Source) factory.getBean("source");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		
	}

	@Test
	public void testSayHelloWorld() {
		target.injectSource(source);
		target.sayHelloWorld();
	}

}

 

 

源码见附件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值