Spring Ioc 之一 ---Spring版HelloWorld
第一步,先編寫一個普通版的helloworld吧。很簡單,代碼如下:
public class HelloWorld{
public void sayHello(){
System.out.println("Hello!");
}
}
第二步,開始使用spring,加入spring的包spring.jar,同時還需要commons-logging.jar(在spring的lib\jakarta-commons下)。
上面的準備工作做好后,開始進入實質階段的第三步了。
3.1 Service編寫。
在spring中需要建立面向接口編程的概念,所以我們能把上面的helloworld重構為下面的一個類和一個接口。使用接口,是為了解耦合,及我們的使用類(即下面要編寫的action)可以和service的實現類無依賴,而且在spring中還可以方便替換實現類。
service接口
public interface IHelloService {
public void sayHello();
}
service實現類
public class HelloServiceImpl implements IHelloService{
@Override
public void sayHello(){
System.out.println("Hello!");
}
}
3.2 Action編寫
service編寫完成了,開始編寫使用類了,代碼如下:
Action 接口
public interface IHelloAction {
public void sayHello();
}
Action的實現類:
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中采用接口,是為了方便下面的測試,可以避免編寫多個測試類。另外在HelloAction 中還加了一個name,這是為了演示,spring在注入bean外,還可以直接注入參數。
3.3 spring 配置文件。
在src下建applicationContext.xml,內容如下:
<?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>
<!--可以不設置類型 -->
<property name="name" value="yoo"></property>
</bean>
</beans>
applicationContext.xml中建立了2個bean:helloService和helloAction,helloAction中引用了helloService,還有name參數。
3.4 測試用例。
編寫一個main函數來測試運行。
public class SpringMain {
public static void main(String[] args) {
// 讀取配置文件,建立spring應用程序上下文
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext-autowired.xml"});
//根據名稱獲取helloAction bean
IHelloAction action = (IHelloAction)context.getBean("helloAction");
action.sayHello();
}
}
運行程序,輸出如下:
...啟動信息...
Hello!
yoo