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

Spring三种流入方式(二)

2012-11-10 
Spring三种注入方式(二)通过访问器方法(set)注入此方法较为常用.在目标类中,定义要注入的属性,并添加访问

Spring三种注入方式(二)

通过访问器方法(set)注入

此方法较为常用.在目标类中,定义要注入的属性,并添加访问器方法,则spring会自动注入.

?

Source.java

?

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

?

Target.java

?

package com.gary.test;public class Target {private Source source;public void setSource(Source source) {this.source = source;}public Source getSource() {return source;}public void sayHelloWorld(){getSource().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" ref="source" /> --></bean></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 Target target = null;@BeforeClasspublic static void setUpBeforeClass() throws Exception {try{factory = new ClassPathXmlApplicationContext("applicationContext.xml");target = (Target) factory.getBean("target");}catch(Exception e){e.printStackTrace();}}@AfterClasspublic static void tearDownAfterClass() throws Exception {}@Testpublic void testSayHelloWorld() {target.sayHelloWorld();}}

?

运行结果

Hello World!

?

源码见附件

?

热点排行