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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步