初学spring

星期五WYF发邮件让我 自己看一下spring,昨天在网上下了本书《spring开发指南》先从最简单的例子开始学习了。实施了2年数据库熟了JAVA却快忘光了。先建了一个java project

然后右键看工程属性加入需要的spring类包

spring.jar

spring 1.2 aop libraries

spring 1.2 core/context libraries

三个包如果只加spring.jar会报

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

这样的例外

下面开始按书上说的加一个接口

public interface Action {
 
 public String execute(String str);

}

接口的一个简单实现

public class SupperAction implements Action {

 private String message;
 
 public String getMessage(){
  return message;
 }
 
 public void setMessage(String str){
  message=str;
 }
 
 public String execute(String strtemp) {
  // TODO Auto-generated method stub
  return (getMessage()+strtemp).toUpperCase();
 }

}

和spring的简单的测试类

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class SpringTest {
 /**
  * @param args
  */
 public static void main(String[] args) {
      
  XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
  
  //use service bean:
  
  Action temp = (Action)factory.getBean("supperaction");
  
  System.out.println(temp.execute(" let fun!"));
  
 }

}

这里需要注意要加一个beans.xml名字不一定起这个名字但要和测试类中

new XmlBeanFactory(new ClassPathResource("beans.xml"));

字符串的文件名一致就可以

还要注意一点eclipse默认建立的xml文件是

<?xml version="1.0" encoding="UTF-8"?>
<xml-body>

</xml-body>

这种格式的如果这样按书上继续加就要抛出

 

Cannot find the declaration of element 'beans'异常

这里只需要把<xml-body>定义去掉然后加上

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " http://www.springframework.org/dtd/spring-beans.dtd">

就可以了

写好格式如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " http://www.springframework.org/dtd/spring-beans.dtd">

  <beans>
     <description>Spring test</description>
     <bean id="supperaction" class="SupperAction">
        <property name="message">
           <value>Hello</value>
        </property>
     </bean>
  </beans>


这样就可以直接对SpringTest 进行run as java application

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值