首先,按照Spring系列一中的环境搭建方式搭建好我们的开发环境,如下图所示:
从图中我们可以看到需要创建的包以及类和接口:
cs.csdn.Junit为JUnit测试包
cs.csdn.Service为服务类包
GreetingService接口源码:
1
2
3
4
5
6
7
|
package
cn.csdn.service;
public
interface
GreetingService {
void
sayGreeting();
}
|
GreetingServiceImpl接口实现类源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package
cn.csdn.service;
public
class
GreetingServiceImpl
implements
GreetingService{
private
String say;
@Override
public
void
sayGreeting() {
System.out.println(
"我说的是:"
+say);
}
/**通过set方法进行赋值*/
public
void
setSay(String say) {
this
.say = say;
}
}
|
GreetingTest测试类源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package
cn.csdn.juint;
import
org.junit.Test;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
cn.csdn.service.GreetingServiceImpl;
public
class
GreetingTest {
@Test
public
void
test(){
/**解析applicationContext.xml文件*/
ApplicationContext ac =
new
ClassPathXmlApplicationContext(
"applicationContext.xml"
);
/**调用getBean方法获取bean对象 需要强制造型*/
GreetingServiceImpl gsi = (GreetingServiceImpl) ac.getBean(
"greetingServiceImpl"
);
/**调用对象相应的方法*/
gsi.sayGreeting();
}
}
|
ApplicationContext.xml文件的配置:
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> 8 9 10 11 12 13 <bean id="greetingServiceImpl" class="cn.csdn.service.GreetingServiceImpl"> 14 15 <property name="say" value="Hello"></property> 16 17 </bean> 18 19 </beans>
运行JUnit测试类结果:
我说的是:Hello