1、将Spring包导入为用户库,以便在项目中引用。
(1)安装Java JDK与Eclipse开发工具;
(2)在任意路径下创建springframework文件夹,然后在该文件夹之下再创建spring与dependency子文件夹;
(3)下载Spring框架jar包及其依赖jar包,并将这些jar包分别拷入spring与dependency子文件夹中;
(4)启动Eclipse并选择Window — Preferences打开Preferences对话框窗口;选择Java — Build Path — User Libraries 打开 User Libraries选项页;在该选项页中新建(New …)两个User Library,一个名为spring,另一个名为dependency,然后分别将Spring框架jar包及其依赖jar包加入(Add JARs …)其内;
2、使用Spring框架
(1)在Eclipse中创建Java工程,工程名为helloapp;
(2)在工程上右击右键并选择Properties,弹出工程属性对话框;在对话框中选择Java Build Path — Libraries;使用Add Libraries添加在第1步中所创建的两个User Library,即spring与dependency;
(3)在工程中编写以下类以及Spring配置文件,将配置文件放入Eclipse工程的src文件夹中即可;
package springlab.hello;
public interface Hello {
public void sayHello();
}
package springlab.hello;
public class HelloBean implements Hello{
private String someone;
private String title;
private String greetings;
public void setGreetings(String greetings) {
this.greetings = greetings;
}
public HelloBean(String title,String someone){
this.title = title;
this.someone=someone;
}
public void sayHello() {
System.out.println(greetings+", "+title+" "+someone + "!");
}
}
package springlab.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloApp {
public static void main(String args[]){
ApplicationContext context =
new ClassPathXmlApplicationContext("hellospring.xml");
Hello hello = (Hello)context.getBean("hello");
hello.sayHello();
}
}
<?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-3.0.xsd"> <bean id="hello" class="springlab.hello.HelloBean"> <constructor-arg value="Mr." /> <constructor-arg value="Lee" /> <property name="greetings" value="Good morning"/> </bean> </beans>
(4)只要点击点击Run便可运行项目了。将可以得到输出Good morning Mr. Lee。