Spring系列之二——Spring初体验

首先,按照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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值