一.下载和配置Spring开发环境:
首先的话,先下载jar包,把spring环境搭建起来:
下载一个spring版本,建议使用的版本暂时不要太高,避免在实验的时候出现其他错误,我这里用的是4.3.20.RELESE版本。
在谷歌浏览器或者其他浏览器之间输入这个网站 --> https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-local/org/springframework/spring
进入该网站后找到左侧一栏的spring点进去,然后点击spring-framework-4.3.2.RELEASE-dist.zip
然后点击下图的Download就行了。
commons-logging 这个包是需要额外去下载的,地址:http://commons.apache.org/proper/commons-logging/download_logging.cgi
我这里使用的是commons-logging-1.2.jar 版本
然后将必须的jar包如下导进入eclipse里面的lib目录下,接着不要忘了build Path,然后开始测试第一个spring程序。
二.编写第一个spirng程序:
先写一个用户类:
package henu.bean;
public class User {
private int id;
private String name;
//无参构造方法
public User() {
System.out.println("----------对象被创建-------");
System.out.println("------无参构造-------");
}
//getter和setter方法
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
然后在src下创建applicationContext.xml文件,一般是命名这样。
applicationContext.xml:
然后编写bean id, class:为用户类User包路径。
<?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.xsd">
<bean id="user" class="henu.bean.User" ></bean>
</beans>
接着写个测试类App:
package henu.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试类
*/
public class App {
public static void main(String[] args) {
// 1.得到IOC容器
ApplicationContext appc = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("---得到IOC容器-------");
// 2.从容器中获取对象
User user = (User) appc.getBean("user");
}
}
然后运行App类测试下,右键Run As Java application输出如下:
基本上spring环境初步搭建了。