第一步,先编写一个普通版的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"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<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