作者:王斌 2005-04-02         Spring Framework是一个解决了许多在J2EE开发中常见的问题的强大框架,使用Spring Framework可以实现高效的独立的高度可复用性的解决方案!它基于功能强大的基于javaBeans的配置管理,它使组织应用变得容易和迅速。你的代码中不再充斥着单例垃圾,也不再有麻烦的属性文件。取而代之的一致和幽雅的方法的应用。 但是强大功能必然带来复杂的学习曲线,作者通过《SpringGuide》结合自身的学习经历,一步步引导你走进Spring Framework。本文中的IDE为Eclipse 1.下载SpringFramework的最新版本,并解压缩到指定目录。如e:\Spring 2. 在IDE中新建一个项目,并将e:\Spring\dist\下所有jar包加入项目。 3.Spring采用Apache common_logging,并结合Apache log4j作为日志输出组件。为了在 调试过程中能观察到Spring的日志输出,应在项目中加入这两个包,并且应把在CLASSPATH中新建log4j.properties配置文件(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 |  
 4.定义Action接口: Action 接口定义了一个execute 方法,在我们示例中,不同的Action 实现提供了各自的 execute方法,以完成目标逻辑。 Action.java package qs; public interface Action {  public String execute(String str); }
   |  
 5.实现Action接口,分别编写两个类UpperAction、LowerAction UpperAction.java  package qs; 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 package qs; 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();   }   }   |  
 5.定义Spring配置文件(bean.xml)  <beans> <description>Spring Quick Start</description> <bean id="TheAction" class="qs.UpperAction"> <property name="message"> <value>HeLLo:</value> </property> </bean> </beans> |  
 (请确保配置bean.xml位于工作路径之下,注意工作路径并不等同于CLASSPATH ,eclipse 的默认工作路径为项目根路径,也就是.project文件所在的目录,而默认输出目录/bin是项目 CLASSPATH的一部分,并非工作路径。) 6.测试代码,编写Test.java  package qs; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class Test {  public static void main(String[] args) {   ApplicationContext ctx=new    FileSystemXmlApplicationContext("bean.xml");    Action action = (Action) ctx.getBean("TheAction");    System.out.println(action.execute("Spring");  } }  |  
 运行测试代码Test.class,我们看到控制台输出: …… HELLO:SPRING 我们将bean.xml中的配置稍加修改: <bean id="TheAction" class="qs.LowerAction"/> 再次运行测试代码,看到: …… hello:spring 示例完成!
  
 
  |