Spring源码本地编译并执行测试
想要熟悉Spring从源码开始是非常重要的,同时Spring内部的优秀设计思想可以借鉴
准备工具
1、spring源码 下载地址:spring源码地址
2、gradle 5.6.4,gradle用来编译构建spring,和maven差不多的工具,配置有差异。下载地址:gradle下载地址
3、idea 我本地用的是2022版本
执行过程
1、spring源码根目录,打开import-into-idea.md
,里面有个先执行的命令,cmd执行gradlew.bat :spring-oxm:compileTestJava
,看到成功就行
2、GRADLE_HOME环境变量配置
path追加:
3、IDEA引入项目
File- Open- 选择项目打开就行了
4、控制台执行构建命令
./gradlew build -x checkstyleMain -x checkstyleTest -x test
这里checkstyleMain 、checkstyleTest 跳过一些无关紧要的错误检查,没关系
执行成功就是这个样子
遇到的错误解决:
1、fatal: not a git repository (or any of the parent directories):
这个是因为你是在一个非 git 仓库的目录执行了 gradle build ,但 spring-framework 的构建脚本某些地方需要使用 git 信息(比如版本号、提交信息)来完成构建 .git 找不到git仓库
本机安装git ,然后,进入spring源码根目录下执行
cd spring-framework-5.2.x
git init
git config --global user.name "Your Name" 随便写名字 email
git config --global user.email "you@example.com"
git add .
git commit -m "init"
2、会报错仓库http请求连不上的话 ,修改maven仓库,根目录settings.gradle
文件
repositories {gradlePluginPortal()// maven { url 'https://repo.spring.io/plugins-release' }maven { url 'https://maven.aliyun.com/repository/spring-plugin' }maven { url 'https://maven.aliyun.com/nexus/content/repositories/spring-plugin' }maven { url 'https://repo.spring.io/plugins-release'}}
创建测试demo
在spring项目上右键,创建新的Module,选择gradle,项目 ,DSL语法和spring保持统一Groovy DSL。
test-demo.gradle
apply plugin: 'java'dependencies {implementation project(':spring-context')testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'}sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceSets {test {java {srcDirs = ['src/test/java']}}
}test {useJUnitPlatform() // 启用 JUnit 5 平台(必要)
}
spring根目录settings.gradle增加include "test-demo"
编写类文件
package com;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class AppConfig {@Beanpublic HelloService helloService() {return new HelloService();}
}
package com;public class HelloService {public String sayHello() {return "Hello from Spring!";}
}
Test类,
package com;import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class HelloServiceTest {@Testpublic void testHelloServiceTest() {System.out.println("Hello from Spring!");AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);HelloService helloService = context.getBean(HelloService.class);System.out.println("Hello from Spring!");String result = helloService.sayHello();System.out.println("Hello from Spring!"+result);}
}
直接运行测试可能会出问题:
既没有报错 也没有执行代码 ,是gradle的测试什么机制导致的,不清楚
解决办法:
这样就可以解决测试问题了
还可能有一个问题:
Kotlin1.3版本已经废弃掉
你依赖的模块这个改下版本试试
仍然不管用,可以修改下spring根目录build.gradle
追加:
allprojects {afterEvaluate {tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {kotlinOptions {languageVersion = "1.4" // 可选,避开 1.3 警告apiVersion = "1.4"allWarningsAsErrors = false // 🚫 彻底关闭freeCompilerArgs += ["-Xsuppress-version-warnings"]}}}
}