spring in action 的Hello World

终于给我机会让我系统地看看spring,今天翻了一下《spring in action》,敲了那个经典的Hello world,发现书中有很多不地道的地方。

代码就用不着贴了,我只修改了那段不地道的HelloApp

package  com.springinaction.chapter01.hello;

import  org.springframework.beans.factory.BeanFactory;
import  org.springframework.beans.factory.xml.XmlBeanFactory;
import  org.springframework.core.io.FileSystemResource;

public   class  HelloApp  {
    
public static void main(String[] args){
        
//BeanFactory factorr = new XmlBeanFactory(new FileInputStream("hello.xml"));
        BeanFactory factory = new XmlBeanFactory(new FileSystemResource("hello.xml"));
        GreetingService greetingService 
= (GreetingService)factory.getBean("greetingService");
        greetingService.sayGreeting();   
    }

}

当我敲入BeanFactory factorr = new XmlBeanFactory(new FileInputStream("hello.xml"));时编译器提示这是个过时的方法,我改成了BeanFactory factory = new XmlBeanFactory(new FileSystemResource("hello.xml"));

运行后提示:Exceptioninthread"main"java.lang.NoClassDefFoundError:org/apache/commons/logging/LogFactory

没啥说的,指定时缺少了commons-logging.jar,我不明白为什么好多书中都没有在例子程序注明要导入这个包。

再次运行,报错:

2008-3-20 10:52:46 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [D:/eclipse/workspace2/SpringPro/hello.xml]
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [D:/eclipse/workspace2/SpringPro/hello.xml]; nested exception is java.io.FileNotFoundException: hello.xml (系统找不到指定的文件。)
java.io.FileNotFoundException: hello.xml (系统找不到指定的文件。)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.<init>(FileInputStream.java:106)
 at org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:57)
 at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:129)
 at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:88)
 at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:59)
 at com.springinaction.chapter01.hello.HelloApp.main(HelloApp.java:10)
Exception in thread "main"

看看提示,D:/eclipse/workspace2/SpringPro/hello.xml ,如信息所述,程序找不到SpringPro/hello.xml。将hello.xml直接放到工程SpringPro下,运行:

2008-3-20 10:29:40 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [D:/eclipse/workspace2/SpringPro/hello.xml]
2008-3-20 10:29:40 org.springframework.beans.factory.support.AbstractBeanFactory getBean
信息: Creating shared instance of singleton bean 'greetingService'
Hello world!

终于看到了那个具有传奇色彩的Hello world! 当然new FileSystemResource("hello.xml")的参数也可以写成绝对路径。

这个例子可以在eclipse中直接建立web工程,因为不用部署,也就无需修改web.xml,为了和书中一致,使用了spring1.1.3,导入两个jar包,commons-logging.jar和spring.jar。以上调试jdk1.4.2_07中进行,也可以使用jdk1.5。

你可能感兴趣的:(spring,exception,bean,action,import,Parsing)