星期五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