配置运行Spring 入门级Demo 和常见故障解决 (Spring in Action)

来源:互联网 发布:mac gdb 动态调试 编辑:程序博客网 时间:2024/04/28 21:13

spring demo编写过程中可以遇到以下错误

避免常见故障:

(1)java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

Spring依赖于Apache的通用日志组件包,下载并加入到build path

(2) No default constructor found

为实现类田间无参数构造函数

(3) java.io.FileNotFoundException

配置文件的路径有问题,放在工程的根目录可避免

1.编写接口类

package com.springinaction.chapter1.hello;

 

public interface GreetingService{

    void sayGreeting();

}

2.编写实现类

package com.springinaction.chapter1.hello;

 

public class GreetingServiceImpl implements GreetingService {

 

    private String greeting;

 

    // 一个无参数的构造函数

    public GreetingServiceImpl() {

 

    }

 

    public GreetingServiceImpl(String greeting) {

       this.greeting = greeting;

    }

 

    public void sayGreeting() {

       System.out.println(greeting);

    }

 

    public void setGreeting(String greeting) {

       this.greeting = greeting;

    }

}

3.编写依赖注入配置文件:

<?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.0.xsd">

  <bean id="greetingService"

      class="com.springinaction.chapter1.hello.GreetingServiceImpl">

    <property name="greeting" value="Buenos Dias!" />

  </bean>

</beans>

4..主函数

package com.springinaction.chapter1.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 factory = new XmlBeanFactory(new FileSystemResource(

              "config.xml"));

 

       GreetingService service = (GreetingService) factory

              .getBean("greetingService");

 

       service.sayGreeting();

    }

}

运行结果:

Buenos Dias!

 

5.为了使程序能够正常运行需要注意一下几点

(1) 设置好build path:加入spring包的dist下的jar

(2) 由于spring还依赖于apachecommon logging,还要加入commons-logging包的jar

(3) 配置文件的位置应该放在工程的根目录,否则文件路径不能这么写,会找不到文件发生IOException.

(4) 要为具体的实现类提供一个无参数的构造函数

配置好以上,一个一个简单的spring demo就完成了.

 

注意编程方式的特点.首先要编写一个接口类.然后真实的业务逻辑在实现接口的实体类中完成.

运行结果:在主函数中的程序设计完全面向接口编程,和具体实现完全没有依赖关系.依赖的注入通过读取config.xml文件获得.并通过springBeanFactory解析得到具体的实现.如果实现类更改了,只需要重新编译实现类和重新配置文件config.xml即可.完全面向接口编程的测试主函数类不需要重新编译.