Spring是一个独立的框架,它不需要依赖于任何Web服务器或容器,既可在独立的Java SE项目中使用,也可在Java Web项目中使用。下面演示在Java SE项目中搭建简单的Spring框架。
环境:Eclipse、Java 11.0.2、Spring 5.0.4
需要用到两个依赖包spring-framework-5.0.4.RELEASE-dist.zip、日志包commons-logging-1.2.jar
实现步骤如下所示:
(1) 在Eclipse中,创建一个名为“spring-1”的Java项目。
选择Java Project,输入项目名称,其余选项默认设置
右键点击Spring-1,新建一个名为lib的文件夹
(2) 将四个Spring的基础包复制到lib目录中。
Spring四个基础包分别对应Spring核心容器的四个模块,spring-core-5.0.4.RELEASE.jar、spring-beans-5.0.4.RELEASE.jar、spring-context-5.0.4.RELEASE.jar、spring-expression-5.0.4.RELEASE.jar
基础包在spring-framework-5.0.4.RELEASE-dist下的libs目录中。
(3) 复制日志包commons-logging-1.2.jar。
复制好基础包的Spring-1目录:
(4) 将复制好的5个jar包全部添加到项目的构建路径中。
最简单的构建路径方法,右键jar包 Add to Build Path完成后,目录如下:
(5) 在项目中创建com.ssm包,并创建HelloSpring类。
*
package com.ssm;
public class HelloSpring {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
public void show() {
System.out.println(userName+":欢迎您来学习Spring框架!");
}
}
(6) 在项目src目录下创建applicationContext.xml文件。
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<!-- 配置一个bean,将指定类配置给Spring,让Spring来创建其对象的实例 -->
<bean id="helloSpring" class="com.ssm.HelloSpring">
<!-- 为属性赋值 -->
<property name="userName" value="张三"></property>
</bean>
</beans>
其中第2~5行是Spring的约束配置,可以在Sping的帮助文档中找到。路径:spring-framework-5.0.4.RELEASE\docs\spring-framework-reference\html5\core.html
(7) 在com.ssm包中创建测试类TestHelloSpring。
package com.ssm;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestHelloSpring {
public static void main(String[] args) {
//初始化Spring容器,加载applicationContext.xml文件
ApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml");
//通过容器获取配置中的helloSpring的实例
HelloSpring helloSpring=(HelloSpring) ctx.getBean("helloSpring");
System.out.println(helloSpring);
helloSpring.show();
}
}
到这里,我们的第一个Spring程序就写完了,点运行,控制台输出如下: