一个使用spring的最简单的例子。
1 准备工作
Spring采用Apache common_logging,并结合Apache log4j作为日志输出组件。为了在
调试过程中能观察到Spring的日志输出,在CLASSPATH中新建log4j.properties配置文件,
内容如下:
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n
我是用的IDE是Eclipse3.0, log4j.properties的位置在src目录下。
2 创建一个Bean类HelloAction
代码如下:
package net.garrey.test.action;
public class HelloAction {
private String greeting;
public static void HelloAction() {
}
public void setGreeting(String greeting){
this.greeting=greeting;
}
public String getGreeting(){
return this.greeting;
}
public void sayHello(){
System.out.println(getGreeting());
}
}
3 添加spring配置文件bean.xml
请确保配置bean.xml位于工作路径之下,注意工作路径并不等同于CLASSPATH ,eclipse
的默认工作路径为项目根路径,也就是.project文件所在的目录。(Jbuilder的工作目录也是classes的上一级目录)。
〈?xml version="1.0" encoding="UTF-8"?〉
〈!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"〉
〈beans〉
〈bean id="helloAction"
class="net.garrey.test.action.HelloAction"〉
〈property name="greeting"〉
〈value〉Hello Spring〈/value〉
〈/property〉
〈/bean〉
〈/beans〉
4 赶快测试一下
创建工具类HelloSpring:
package net.garrey.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import net.garrey.test.action.HelloAction;
public class HelloSpring {
public static void main(String[] args) {
ApplicationContext ctx=new FileSystemXmlApplicationContext("bean.xml");
HelloAction action = (HelloAction) ctx.getBean("helloAction");
action.sayHello();
}
}
5 打开console看看输出
... ...
Hello Spring
哈,是不是很简单,你可也看一下输出日志看看在在创建HelloAction实例前Spring到底都作了什么。