本文是学习 Spring 源码的第一篇,下载 Spring 源码及编译运行并测试。
环境筹备
JDK11、Gradle、Maven、SpringFramework 5.2.0.RELEASE
下载源码及编译
进入 github :https://github.com/spring-pro...
在 Tags 中抉择须要的版本,随后右侧下载即可。
下载实现解压后,进入spring-framework-5.2.0.RELEASE
文件中,通过终端执行以下命令:
./gradlew :spring-oxm:compileTestJava
如果下载过慢能够应用阿里云镜像。
随后通过 IDEA 导入我的项目,gradle 会主动编译。
在编译中可能会报如下谬误:
POM relocation to an other version number is not fully supported in Gradle : xml-apis:xml-apis:2.0.2 relocated to xml-apis:xml-apis:1.0.b2.
批改引入形式,批改 bulid.gradle,搜寻 configurations.all,增加如下内容:
force 'xml-apis:xml-apis:1.4.01'
configurations.all { resolutionStrategy { cacheChangingModulesFor 0, "seconds" cacheDynamicVersionsFor 0, "seconds" force 'xml-apis:xml-apis:1.4.01' }}
随后咱们排除掉spring-aspects
模块,右键该模块抉择 Load/UnLoad Modules...
即可。
测试
咱们新建一个 gradle 模块我的项目 springdemo 进行测试。目录构造如下:
build.gradle 退出依赖,这里只退出 context 是因为 context 中曾经引入了 code、aop、beans 等外围模块。
dependencies { compile(project(":spring-context")) testCompile group: 'junit', name: 'junit', version: '4.12'}
先创立一个接口和实现类。
public interface WelcomeService { String sayHello(String name);}
@Servicepublic class WelcomeServiceImpl implements WelcomeService { @Override public String sayHello(String name) { System.out.println("欢送你:" + name); return "success"; }}
创立 spring 的配置文件,而后注册 bean。
<?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="welcomeService" class="cn.jack.service.impl.WelcomeServiceImpl"/></beans>
最初咱们创立启动类进行测试。
/** * @author 神秘杰克 * 公众号: Java菜鸟程序员 * @date 2022/3/14 * @Description 启动类 */public class Entrance { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/spring-config.xml"); WelcomeService welcomeService = (WelcomeService) applicationContext.getBean("welcomeService"); welcomeService.sayHello("Spring框架!"); }}
运行后果:
> Task :springdemo:Entrance.main()欢送你:Spring框架!BUILD SUCCESSFUL in 9s
OK,到这里就实现了 Spring 源码的下载编译及测试。