首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring三种流入方式(三)

2012-09-04 
Spring三种注入方式(三)通过接口方式注入建议使用前两种方法?Source.javapackage com.gary.testpublic cl

Spring三种注入方式(三)

通过接口方式注入

建议使用前两种方法

?

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;@Overridepublic void injectSource(Source source) {this.source = source;}public void sayHelloWorld(){source.helloWorld();}}

?

?

applicationContext.xml

?

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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" /><bean id="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;@BeforeClasspublic 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();}}@AfterClasspublic static void tearDownAfterClass() throws Exception {}@Testpublic void testSayHelloWorld() {target.injectSource(source);target.sayHelloWorld();}}

?

?

源码见附件

1 楼 eric_shi 2011-01-27   头像很可爱啊

热点排行