学SF框架,第一步就是搭建学习SF环境。由于采用应用分析法,主要利用Maven来下载源码+eclipse快捷键追踪代码,不仅使环境搭建简单,而且学习非常高效。下面是windows10下搭建学习SpringFramework的源码环境的几个步骤:
1、安装Java8
2、安装并配置eclipse
3、搭建应用
安装Java8
1、下载Jdk1.8.0_121
2、配置系统环境变量:JAVA_HOME和PATH
安装并配置eclipse
1、下载安装
安装eclipse4.21或之后版本,笔者用的是 Eclipse IDE 2023‑03 版本。
下载地址:http://www.eclipse.org/downloads/packages
下载解压到一个目录即可。
2、配置
运行eclipse,设置路径:windows->preferences,配置如下图:
这样配置,当maven项目引用springframework时,会自动下载源代码到同一目录。如下图:
3、查看源码
在一个maven项目中,通过如下图方式查看springframework类或方法的实现即可看到源代码(第一次会找不到,通过外部文件选择源码包即可)
搭建应用
1、生成一个maven应用。
2、pom.xml配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.learnsf</groupId>
<artifactId>learnsfsc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.8</version>
</dependency>
</dependencies>
</project>
用springframework构建应用,springcontext(spring容器,或者spring上下文,前者更恰当)是应用运行的基础环境,因此第一个引入的就是spring-context。
3、第一个服务类
package com.learnsf.service;
public class HelloSFService {
public String helloSF(String name){
System.out.println("hello " + name +" ,welcome to learn spring-framework" );
return "ok";
}
}
4、第一个配置文件
<?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="HelloSFService" class="com.learnsf.service.HelloSFService"/>
</beans>
在xml中定义第一个bean,sf将通过这个文件加载服务类HelloSFService
5、第一个主程序
package com.learnsf.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learnsf.service.HelloSFService;
public class LearnMain {
public static void main(String[] args) {
//创建springframework容器,初始化文件为app.xml
ApplicationContext context = new ClassPathXmlApplicationContext("app.xml");
//从容器中获取一个类实例
HelloSFService service = (HelloSFService)context.getBean("HelloSFService");
//执行类方法
String result = service.helloSF("David");
System.out.println("hello result : " + result);
}
}
第一个实例就是:
1)基于配置文件创建SF容器
2)从容器中获取类实例
3)执行类实例方法
6、项目结构如下图:
其中pom.xml只引入了spring-context包,maven自动引入了依赖包,这些包就是SF最基础、最核心的包了。
7、运行看效果