如何阅读Spring源码,阅读前需要做哪些准备

环境准备

下载源码

下载地址:https://github.com/spring-projects/spring-framework/tree/v6.0.3

选择版本:

选择spring源码版本

选择压缩包下载,直接通过git clone http地址下载比较慢,直接下载压缩包。

下载spring源码zip包

解压源码压缩包

spring源码目录结构

查看gradle对应版本,查看目录gradle-wrapper.properties文件(gradle->wrapper->gradle-wrapper.properties)

修改wrapper.properties配置文件

查看当前spring源码版本,所依赖的gradle版本

spring源码依赖的gradle

环境准备

Java环境:jdk17

Gradle环境:gradle-7.6-bin.zip

下载gradle,下载地址:https://gradle.org/releases/,选择上面spring框架依赖的版本

下载gradle

解压gradle

解压后的gradle

配置环境变量,执行命令 vim ~/.bash_profile

环境变量中添加gradle配置

使配置生效,执行:source ~/.bash_profile

查看gradle版本

查看gradle版本

修改镜像源

修改gradle镜像源

在build.gradle中添加阿里云镜像。

修改成阿里云镜像源

修改settings.gradle中的阿里云镜像

修改setting.gradle

修改settings.gradle阿里云仓库镜像配置

修改成阿里镜像源

maven { url "https://maven.aliyun.com/repository/public" } // 阿里云镜像仓库

编译源码

在项目根目录,进行预编译,./gradlew :spring-oxm:compileTestJava

编辑源码

编译中,编译需要一段时间。

源码编译中

编译完成

源码编译完成

需要注意的配置

preferences -> gradle 配置

修改idea中gradle配置

Project structure -> project

修改idea中Project structure配置

Project structure -> Modules

修改idea中Project structure配置

特别需要注意的配置文件

根目录settings.gradle

pluginManagement {
   repositories {
      maven { url "https://maven.aliyun.com/repository/gradle-plugin" }
      maven { url "https://maven.aliyun.com/repository/spring-plugin" }
      maven { url "https://maven.aliyun.com/repository/public" } // 阿里云镜像仓库
      mavenCentral()
      gradlePluginPortal()
      // maven { url "https://repo.spring.io/release" }
   }
}

plugins {
   id "com.gradle.enterprise" version "3.11.1"
   // id "io.spring.ge.conventions" version "0.0.7"
}

include "spring-aop"
//include "spring-aspects"
include "spring-beans"
include "spring-context"
include "spring-context-indexer"
include "spring-context-support"
include "spring-core"
include "spring-core-test"
include "spring-expression"
include "spring-instrument"
include "spring-jcl"
include "spring-jdbc"
//include "spring-jms"
//include "spring-messaging"
//include "spring-orm"
include "spring-oxm"
include "spring-r2dbc"
//include "spring-test"
include "spring-tx"
//include "spring-web"
//include "spring-webflux"
//include "spring-webmvc"
//include "spring-websocket"
include "framework-bom"
//include "framework-docs"
include "framework-platform"
//include "integration-tests"

rootProject.name = "spring"
rootProject.children.each {project ->
   project.buildFileName = "${project.name}.gradle"
}

settings.gradle.projectsLoaded {
   gradleEnterprise {
      buildScan {
         File buildDir = settings.gradle.rootProject.getBuildDir()
         buildDir.mkdirs()
         new File(buildDir, "build-scan-uri.txt").text = "(build scan not generated)"
         buildScanPublished { scan ->
            if (buildDir.exists()) {
               new File(buildDir, "build-scan-uri.txt").text = "${scan.buildScanUri}
"
            }
         }
      }
   }
}
include 'spring-renjie-001'
include 'spring-renjie-002'

根目录下build.gradle

plugins {
   id 'io.spring.nohttp' version '0.0.10'
   id 'io.freefair.aspectj' version '6.5.0.3' apply false
   // kotlinVersion is managed in gradle.properties
   id 'org.jetbrains.kotlin.plugin.serialization' version "${kotlinVersion}" apply false
   id 'org.jetbrains.dokka' version '1.7.20'
   id 'org.asciidoctor.jvm.convert' version '3.3.2' apply false
   id 'org.asciidoctor.jvm.pdf' version '3.3.2'  apply false
   id 'org.unbroken-dome.xjc' version '2.0.0' apply false
   id 'com.github.ben-manes.versions' version '0.42.0'
   id 'com.github.johnrengelman.shadow' version '7.1.2' apply false
   id 'de.undercouch.download' version '5.1.0'
   id 'me.champeau.jmh' version '0.6.8' apply false
}

ext {
   moduleProjects = subprojects.findAll { it.name.startsWith("spring-") }
   javaProjects = subprojects - project(":framework-bom") - project(":framework-platform")
}

configure(allprojects) { project ->
   repositories {
      maven{ url 'https://maven.aliyun.com/nexus/content/groups/public/'}
      maven{ url 'https://maven.aliyun.com/repository/public/'}
      maven{ url 'https://maven.aliyun.com/repository/google/'}
      maven{ url 'https://maven.aliyun.com/repository/spring/'}
      maven{ url 'https://maven.aliyun.com/nexus/content/repositories/jcenter'}
   }
   configurations.all {
      resolutionStrategy {
         cacheChangingModulesFor 0, "seconds"
         cacheDynamicVersionsFor 0, "seconds"
      }
   }
}

configure([rootProject] + javaProjects) { project ->
   group = "org.springframework"

   apply plugin: "java"
   apply plugin: "java-test-fixtures"
   apply plugin: "checkstyle"
   apply plugin: 'org.springframework.build.conventions'
   apply from: "${rootDir}/gradle/toolchains.gradle"
   apply from: "${rootDir}/gradle/ide.gradle"

   configurations {
      dependencyManagement {
         canBeConsumed = false
         canBeResolved = false
         visible = false
      }
      matching { it.name.endsWith("Classpath") }.all { it.extendsFrom(dependencyManagement) }
   }

   test {
      useJUnitPlatform()
      include(["**/*Tests.class", "**/*Test.class"])
      systemProperty("java.awt.headless", "true")
      systemProperty("testGroups", project.properties.get("testGroups"))
      systemProperty("io.netty.leakDetection.level", "paranoid")
      systemProperty("io.netty5.leakDetectionLevel", "paranoid")
      systemProperty("io.netty5.leakDetection.targetRecords", "32")
      systemProperty("io.netty5.buffer.lifecycleTracingEnabled", "true")
      systemProperty("io.netty5.buffer.leakDetectionEnabled", "true")
      jvmArgs(["--add-opens=java.base/java.lang=ALL-UNNAMED",
             "--add-opens=java.base/java.util=ALL-UNNAMED"])
   }

   checkstyle {
      toolVersion = "10.5.0"
      configDirectory.set(rootProject.file("src/checkstyle"))
   }

   tasks.named("checkstyleMain").configure {
      maxHeapSize = "1g"
   }

   tasks.named("checkstyleTest").configure {
      maxHeapSize = "1g"
   }

   dependencies {
      dependencyManagement(enforcedPlatform(dependencies.project(path: ":framework-platform")))
      testImplementation("org.junit.jupiter:junit-jupiter-api")
      testImplementation("org.junit.jupiter:junit-jupiter-params")
      testImplementation("org.junit.platform:junit-platform-suite-api")
      testImplementation("org.mockito:mockito-core")
      testImplementation("org.mockito:mockito-junit-jupiter")
      testImplementation("io.mockk:mockk")
      testImplementation("org.assertj:assertj-core")
      // Pull in the latest JUnit 5 Launcher API to ensure proper support in IDEs.
      testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
      testRuntimeOnly("org.junit.platform:junit-platform-launcher")
      testRuntimeOnly("org.junit.platform:junit-platform-suite-engine")
      testRuntimeOnly("org.apache.logging.log4j:log4j-core")
      testRuntimeOnly("org.apache.logging.log4j:log4j-jul")
      testRuntimeOnly("org.apache.logging.log4j:log4j-slf4j-impl")
      // JSR-305 only used for non-required meta-annotations
      compileOnly("com.google.code.findbugs:jsr305")
      testCompileOnly("com.google.code.findbugs:jsr305")
      checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:0.0.31")
   }

   ext.javadocLinks = [
         "https://docs.oracle.com/en/java/javase/17/docs/api/",
         "https://jakarta.ee/specifications/platform/9/apidocs/",
         "https://docs.oracle.com/cd/E13222_01/wls/docs90/javadocs/",  // CommonJ
         "https://www.ibm.com/docs/api/v1/content/SSEQTP_8.5.5/com.ibm.websphere.javadoc.doc/web/apidocs/",
         "https://docs.jboss.org/jbossas/javadoc/4.0.5/connector/",
         "https://docs.jboss.org/jbossas/javadoc/7.1.2.Final/",
         "https://www.eclipse.org/aspectj/doc/released/aspectj5rt-api/",
         "https://www.quartz-scheduler.org/api/2.3.0/",
         "https://fasterxml.github.io/jackson-core/javadoc/2.10/",
         "https://fasterxml.github.io/jackson-databind/javadoc/2.10/",
         "https://fasterxml.github.io/jackson-dataformat-xml/javadoc/2.10/",
         "https://hc.apache.org/httpcomponents-client-5.2.x/current/httpclient5/apidocs/",
         "https://projectreactor.io/docs/test/release/api/",
         "https://junit.org/junit4/javadoc/4.13.2/",
         // TODO Uncomment link to JUnit 5 docs once we have sorted out
         // the following warning in the build.
         //
         // warning: The code being documented uses packages in the unnamed module, but the packages defined in https://junit.org/junit5/docs/5.9.1/api/ are in named modules.
         //
         // "https://junit.org/junit5/docs/5.9.1/api/",
         "https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/",
         "https://javadoc.io/static/io.rsocket/rsocket-core/1.1.1/",
         "https://r2dbc.io/spec/1.0.0.RELEASE/api/",
         // The external Javadoc link for JSR 305 must come last to ensure that types from
         // JSR 250 (such as @PostConstruct) are still supported. This is due to the fact
         // that JSR 250 and JSR 305 both define types in javax.annotation, which results
         // in a split package, and the javadoc tool does not support split packages
         // across multiple external Javadoc sites.
         "https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/3.0.2/"
   ] as String[]
}

configure(moduleProjects) { project ->
   apply from: "${rootDir}/gradle/spring-module.gradle"
}

configure(rootProject) {
   description = "Spring Framework"

   apply plugin: "io.spring.nohttp"
   apply plugin: 'org.springframework.build.api-diff'

   nohttp {
      source.exclude "**/test-output/**"
      allowlistFile = project.file("src/nohttp/allowlist.lines")
      def rootPath = file(rootDir).toPath()
      def projectDirs = allprojects.collect { it.projectDir } + "${rootDir}/buildSrc"
      projectDirs.forEach { dir ->
         [ 'bin', 'build', 'out', '.settings' ]
            .collect { rootPath.relativize(new File(dir, it).toPath()) }
            .forEach { source.exclude "$it/**" }
         [ '.classpath', '.project' ]
            .collect { rootPath.relativize(new File(dir, it).toPath()) }
            .forEach { source.exclude "$it" }
      }
   }

   tasks.named("checkstyleNohttp").configure {
      maxHeapSize = "1g"
   }

}

gradle -> wrapper -> gradle-wrapper.properties

 distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=file:////Users/xxx/Downloads/gradle-7.6-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

阅读源码

新建模块

新建测试模块

添加配置

添加本地spring源码依赖

plugins {
    id 'java'
}

group 'org.springframework'
version '6.0.3'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
    api(project(':spring-context'))
    api(project(':spring-instrument'))

}

test {
    useJUnitPlatform()
}

文件目录

项目结构

添加类文件

package com.renjie;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author: renjie
 * @createTime: 2022年12月29日 10:58:40
 */
public class MyApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean.xml");
      User user = (User)context.getBean("user");
      System.out.println(user.toString());
   }
}


package com.renjie;

/**
 * @Author: renjie
 * @createTime: 2022年12月29日 11:02:04
 */
public class User {
   private String name;
   private String age;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getAge() {
      return age;
   }

   public void setAge(String age) {
      this.age = age;
   }

   @Override
   public String toString() {
      return "User{" +
            "name='" + name + ''' +
            ", age='" + age + ''' +
            '}';
   }
}

添加配置文件

<?xml version="1.0" encoding="UTF-8"?>


   
      
      
   

运行结果

新模块运行结果

编辑遇到的错误

问题一:版本不存在

Starting a Gradle Daemon (subsequent builds will be faster)

FAILURE: Build failed with an exception.

* Where:
Settings file '/Users/xxxx/Downloads/spring-framework-6.0.3/settings.gradle' line: 12

* What went wrong:
Plugin [id: 'io.spring.ge.conventions', version: '0.0.11'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'io.spring.ge.conventions:io.spring.ge.conventions.gradle.plugin:0.0.11')
  Searched in the following repositories:
    maven(https://maven.aliyun.com/repository/public)
    MavenRepo
    Gradle Central Plugin Repository

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 38s

io.spring.ge.conventions的0.0.11版本并不存在,修改成0.0.7

修改版本

修改版本

问题二:代码未上传代码仓库

fatal: not a git repository (or any of the parent directories): .git

> Task :buildSrc:compileJava FAILED
/Users/xxx/Downloads/spring-framework-6.0.3/buildSrc/src/main/java/org/springframework/build/KotlinConventions.java:44: 错误: 找不到符号
                freeCompilerArgs.addAll(List.of("-Xsuppress-version-warnings", "-Xjsr305=strict", "-opt-in=kotlin.RequiresOptIn"));
                                            ^
  符号:   方法 of(java.lang.String,java.lang.String,java.lang.String)
  位置: 接口 java.util.List
1 个错误

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':buildSrc:compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
1 actionable task: 1 executed
Build scan background action failed.
org.gradle.process.internal.ExecException: Process 'command 'git'' finished with non-zero exit value 128
        at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:415)
        at org.gradle.process.internal.DefaultExecAction.execute(DefaultExecAction.java:38)
        at org.gradle.process.internal.DefaultExecActionFactory.exec(DefaultExecActionFactory.java:202)
        at io.spring.ge.conventions.gradle.WorkingDirectoryProcessOperations.exec(WorkingDirectoryProcessOperations.java:45)
        at io.spring.ge.conventions.gradle.ProcessOperationsProcessRunner.run(ProcessOperationsProcessRunner.java:41)
        at io.spring.ge.conventions.core.BuildScanConventions.run(BuildScanConventions.java:166)
        at io.spring.ge.conventions.core.BuildScanConventions.addGitMetadata(BuildScanConventions.java:113)
        at io.spring.ge.conventions.gradle.GradleConfigurableBuildScan.lambda$background$0(GradleConfigurableBuildScan.java:104)
        at com.gradle.enterprise.gradleplugin.internal.extension.a$4.run(SourceFile:174)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

A build scan was not published as you have not authenticated with server 'ge.spring.io'.
For more information, please see https://gradle.com/help/gradle-authenticating-with-gradle-enterprise.

异常一:

org.gradle.process.internal.ExecException: Process 'command 'git'' finished with non-zero exit value 128, 错误是由于下载下来的源代码没有放到git仓库中,将代码放到在即的git仓库就行。

异常二:

A build scan was not published as you have not authenticated with server 'ge.spring.io'. 不做身份验证,注释对应包

注释

问题三:jdk版本不一致,spring6.0以上需要jdk版本为17

添加本地jdk17版本的jdk


build/KotlinConventions.java:44: 错误: 找不到符号

参考:https://www.cnblogs.com/haoxianrui/p/16975079.html


问题三:

Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':spring-core:javapoetRepackJar'.
> Could not resolve all dependencies for configuration ':spring-core:javapoet'.
   > Using insecure protocols with repositories, without explicit opt-in, is unsupported. Switch Maven repository 'maven3(http://repo.springsource.org/plugins-release)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols. See https://docs.gradle.org/7.6/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details. 

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
6 actionable tasks: 1 executed, 5 up-to-date

配置gradle的zip

问题四:Gradle下载的依赖包位置

Mac系统默认下载到:

/Users/(用户名)/.gradle/caches/modules-2/files-2.1 或 ~/.gradle/caches/modules-2/files-2.1

展开阅读全文

页面更新:2024-05-01

标签:源码   阿里   根目录   仓库   符号   模块   错误   版本   代码   环境

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top