Spring Ioc 之一 ---Spring版HelloWorld
第一步,先編寫(xiě)一個(gè)普通版的helloworld吧。很簡(jiǎn)單,代碼如下:
public class HelloWorld{
public void sayHello(){
System.out.println("Hello!");
}
}
第二步,開(kāi)始使用spring,加入spring的包spring.jar,同時(shí)還需要commons-logging.jar(在spring的lib\jakarta-commons下)。
上面的準(zhǔn)備工作做好后,開(kāi)始進(jìn)入實(shí)質(zhì)階段的第三步了。
3.1 Service編寫(xiě)。
在spring中需要建立面向接口編程的概念,所以我們能把上面的helloworld重構(gòu)為下面的一個(gè)類(lèi)和一個(gè)接口。使用接口,是為了解耦合,及我們的使用類(lèi)(即下面要編寫(xiě)的action)可以和service的實(shí)現(xiàn)類(lèi)無(wú)依賴(lài),而且在spring中還可以方便替換實(shí)現(xiàn)類(lèi)。
service接口
public interface IHelloService {
public void sayHello();
}
service實(shí)現(xiàn)類(lèi)
public class HelloServiceImpl implements IHelloService{
@Override
public void sayHello(){
System.out.println("Hello!");
}
}
3.2 Action編寫(xiě)
service編寫(xiě)完成了,開(kāi)始編寫(xiě)使用類(lèi)了,代碼如下:
Action 接口
public interface IHelloAction {
public void sayHello();
}
Action的實(shí)現(xiàn)類(lèi):
public class HelloAction implements IHelloAction{
private HelloService helloservice;
private String name ;
public void sayHello(){
helloservice.sayHello();
System.out.println(this.name);
}
public void setHelloservice(HelloService helloservice) {
this.helloservice = helloservice;
}
public void setName(String name) {
this.name = name;
}
}
這里在action中采用接口,是為了方便下面的測(cè)試,可以避免編寫(xiě)多個(gè)測(cè)試類(lèi)。另外在HelloAction 中還加了一個(gè)name,這是為了演示,spring在注入bean外,還可以直接注入?yún)?shù)。
3.3 spring 配置文件。
在src下建applicationContext.xml,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans
<bean id="helloService" class="org.yoo.service.HelloServiceImpl">
</bean>
<bean id="helloAction" class="org.yoo.service.SetterHelloAction">
<!-- setter injection using the nested <ref/> element -->
<property name="helloservice"><ref bean="helloService"/></property>
<!--可以不設(shè)置類(lèi)型 -->
<property name="name" value="yoo"></property>
</bean>
</beans>
applicationContext.xml中建立了2個(gè)bean:helloService和helloAction,helloAction中引用了helloService,還有name參數(shù)。
3.4 測(cè)試用例。
編寫(xiě)一個(gè)main函數(shù)來(lái)測(cè)試運(yùn)行。
public class SpringMain {
public static void main(String[] args) {
// 讀取配置文件,建立spring應(yīng)用程序上下文
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext-autowired.xml"});
//根據(jù)名稱(chēng)獲取helloAction bean
IHelloAction action = (IHelloAction)context.getBean("helloAction");
action.sayHello();
}
}
運(yùn)行程序,輸出如下:
...啟動(dòng)信息...
Hello!
yoo
posted on 2008-06-07 11:39 flyoo 閱讀(177) 評(píng)論(1) 編輯 收藏