第一个Spring工程

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。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值