spring

简单spring实例
第一步:下载spring.jar,commons-logging.jar包。并导入工程
导入步骤:右击工程--》Build Path--》Add External Archiyes...
:arrow:
第二步:工程中新建三个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文件的存放位置不正确:具体见第二步中文件三里的注释。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值