林炳文Evankaka原创做品。转载请注明出处http://blog.csdn.net/evankakaphp
本文将主讲了Spring在Eclipse下的配置,并用Spring运行了第一个HelloWorld.html
1、下载须要的文件
这里咱们已经配置好Java的运行环境和装好Eclipse了。java
下载Springspring
下载地址:http://maven.springframework.org/release/org/springframework/spring/apache
下载commons-logging编程
下载地址:http://commons.apache.org/proper/commons-logging/download_logging.cgiapp
将它们下载后解压到本身想放的位置,下载以前记得要看清楚是32位仍是64位maven
2、配置Spring
一、新建一个工程,就叫SpringHelloworld。post
二、添加Spring3.x的包,网上有不少不一样的方法。这里我只讲一种。ui
在Window->Preferences->Java->Build Path->User Libraries->New添加一个用户包的库,这里这么作的缘由是Spring包比较多,咱们这样作,配置一次后,之后每一个工程要用直接添加该库就好了
命名为Spring3.2,点击OK
添加成功后
添加到工程中来:
选择新建的工程-》Properties->Java Build Path->Add library
在跳出的窗口中选择User Library
而后又会跳出一个窗口,这时就能够选择咱们以前配置的用户库的包Spring3.2了,把沟打上。
添加成功
而后工程中就能够看到添加进来的Spring3.2了
3、添加commons-logging
选择工程-》Properties->Java Build Path->Add library
而后选择commons-logging所在的包就能够了
添加成功了
4、开始Spring编程
好了,上面的配置都弄好后,咱们就能够开始第一个HelloWorld了
1.首先在当前包下新建一个HelloWorld.java
-
package com.test;
-
/**
-
* Spring第一个HelloWorld
-
* @author 林炳文(邮箱ling20081005@126.com 博客:http://blog.csdn.net/evankaka)
-
* @time 2015.4.1
-
*/
-
public class HelloWorld {
-
private String info;
-
-
public String getInfo() {
-
return info;
-
}
-
-
public void setInfo(String info) {
-
this.info = info;
-
}
-
-
-
}
二、编写配置文件applicationContext.xml
在当前工程下
这就是添加成功后的
而后把applicationContext.xml内容改成以下:
-
"1.0" encoding="UTF-8" xml version=
-
<beans
-
xmlns= "http://www.springframework.org/schema/beans"
-
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
-
xmlns:p= "http://www.springframework.org/schema/p"
-
xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
<!-- 配置须要被Spring管理的Bean(建立,建立后放在了Spring IOC容器里面)-->
-
<bean id="hello" class="com.test.HelloWorld">
-
<!-- 配置该Bean须要注入的属性(是经过属性set方法来注入的) -->
-
<property name="info" value="Happy New Year!"/>
-
</bean>
-
</beans>
在Main.java中添加以下:
-
/**
-
* Spring第一个HelloWorld
-
* @author 林炳文(邮箱ling20081005@126.com 博客:http://blog.csdn.net/evankaka)
-
* @time 2015.4.1
-
*/
-
package com.test;
-
import org.springframework.beans.factory.BeanFactory;
-
import org.springframework.context.support.ClassPathXmlApplicationContext;
-
public class Main {
-
-
private String who = null;
-
-
public static void main(String[] args) {
-
//获取Spring的ApplicationContext配置文件,注入IOC容器中
-
//(Map: key:String, bean标签的id属性值 ==>value:Object, bean标签class属性所指类的实例)
-
BeanFactory factory = new ClassPathXmlApplicationContext( "applicationContext.xml");
-
HelloWorld hw1 = (HelloWorld)factory.getBean( "hello"); //map.get("hello")
-
System.out.println(hw1.getInfo());
-
System.out.println(hw1);
-
-
}
-
}
而后选择工程右键:
接下来就是输出结果啦:
林炳文Evankaka原创做品。转载请注明出处http://blog.csdn.net/evankaka