spring
时间:2010-07-18 来源:sfwhhp
简单spring实例
第一步:下载spring.jar,commons-logging.jar包。并导入工程
导入步骤:右击工程--》Build Path--》Add External Archiyes...
第二步:工程中新建三个java文件
文件一:
文件二:
文件三:
第三步:新建hello.xml文件
hello.xml文件的具体存放位置,要看在第二步中helloworld.java文件用到的获取xml问价你的类。上面列举了三种。都有存放位置的注释。
遇到的问题一:
原因,没导入commons-logging.jar包
问题二:
hello.xml文件的存放位置不正确:具体见第二步中文件三里的注释。
第一步:下载spring.jar,commons-logging.jar包。并导入工程
导入步骤:右击工程--》Build Path--》Add External Archiyes...
第二步:工程中新建三个java文件
文件一:
package com.springination.chapter01.hello;
public interface IGreetingService {
public void sayGreeting();
}
文件二:
package com.springination.chapter01.hello;
public class GreetingServiceImpl implements IGreetingService {
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;
}
}
文件三:
package com.springination.chapter01.hello;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class Helloworld {
/**
* @param args
*/
public static void main(String[] args)
{
//方法一 FileSystemResource类,默认xml文件的路径在工程目录下
Resource resource = new FileSystemResource("hello.xml");
BeanFactory factory = new XmlBeanFactory(resource);
GreetingServiceImpl greetingService = (GreetingServiceImpl) factory.getBean("greetingService");
greetingService.sayGreeting();
//方法二 ClassPathXmlApplicationContext类,默认的寻找xml文件的路径就在src目录下
// ApplicationContext ac = new ClassPathXmlApplicationContext("hello.xml");
// GreetingServiceImpl greetingService = (GreetingServiceImpl) ac.getBean("greetingService");
// greetingService.sayGreeting();
//方法三 FileSystemXmlApplicationContext类,默认的寻找xml文件的路径就在src目录下
// ApplicationContext ac = new FileSystemXmlApplicationContext("hello.xml");
// GreetingServiceImpl greetingService = (GreetingServiceImpl) ac.getBean("greetingService");
// greetingService.sayGreeting();
}
}
第三步:新建hello.xml文件
<?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="greetingService"
class="com.springination.chapter01.hello.GreetingServiceImpl">
<property name="greeting">
<value>hello world</value>
</property>
</bean>
</beans>
hello.xml文件的具体存放位置,要看在第二步中helloworld.java文件用到的获取xml问价你的类。上面列举了三种。都有存放位置的注释。
遇到的问题一:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
原因,没导入commons-logging.jar包
问题二:
Caused by: java.io.FileNotFoundException: hello.xml (系统找不到指定的文件。)
hello.xml文件的存放位置不正确:具体见第二步中文件三里的注释。
相关阅读 更多 +










