第二章 Spring 的一个小例子

来源:互联网 发布:淘宝首页哪有摇一摇 编辑:程序博客网 时间:2024/04/29 22:11

        让我们抛开那些烦琐的文件结构和IDE,我们用纯粹的手工代码来实现这个小例子,当然比较古老,但是更能透彻的明白问题所在。现在让我们开始吧:

        首先,你要到www.springframework.org下载spring的开发包,解压到你的本地硬盘,假设为 D:/spring。接下来你需要设置你的环境变量,在CLASSPATH中加上 D:/spring/dist/spring.jar ; D:/spring/lib/jakarta-commons/commons-logging.jar  ,在开发编译时需要用到这两个JAR文件。

        然后,建立个目录TEST,在下面依次建立文件为:

文件名:log4j.property

内容:

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

文件名:UpperAction.java

内容:

public class UpperAction implements Action{
 private String message;
 public String getMessage(){
  return message;
 }
 public void setMessage(String string){
  message=string;
 }
 public String execute(String str){
  return (getMessage()+str).toUpperCase();
 }
}

文件名:LowerAction.java

内容:

public class LowerAction implements Action{
 private String message;
 public String getMessage(){
  return message;
 }
 public void setMessage(String string){
  message=string;
 }
 public String execute(String str){
  return (getMessage()+str).toLowerCase();
 }
}

文件名:TestQuickStart.java

内容:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class TestQuickStart{
 public void test(){
  ApplicationContext ctx=new
   FileSystemXmlApplicationContext("bean.xml");
  Action action=(Action) ctx.getBean("TheAction");
  System.out.println(action.execute("Rod Johnson"));
 }
 
 public static void main(String[] args){
  TestQuickStart tqs=new TestQuickStart();
  tqs.test();
 }
}

文件名:bean.xml

内容:

<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://springframework/spring-beans.dtd">
<beans>
 <description>Spring Quick Start</description>
 <bean id="TheAction"
   class="UpperAction">
  <property name="message">
   <value>Hello   </value>
  </property>
 </bean>
</beans>

文件名:Action.java

内容:

public interface Action{
 public String execute(String str);
}

        好了,依次编译扩展名为.java的文件。OK,现在执行java TestQuickStart ,输出是大写的Hello Rod Johnson

,让我们修改 bean.xml文件  <bean id="TheAction"   class="UpperAction">修改为: <bean id="TheAction"   class="LowerAction">,现在怎么样,执行结果变成了小写的:hello rod johnson ,怎么样,体会到spring的强大之处了吧。

        让我们接着深入spring学习。