如何下载阅读Spring源码-全过程详解

这篇文章记录了下载spring源码和在IDEA中打开运行的全过程,并且记录了过程中遇到的问题和解决方案,适合需要学习spring源码的同学阅读。

1.spring源码下载地址

通过Git下载spring-framework项目源码:

git clone https://github.com/spring-projects/spring-framework.git

如何下载阅读Spring源码-全过程详解_第1张图片

2.使用IDEA构建spring-framework源码

笔者用的IDEA版本是社区版IDEA:IntelliJ IDEA 2020.34(Community Edition),用IDEA打开源码后,IDEA会自动加载Gradle项目依赖。

然后这里就遇到了第一个问题:

2.1 SSL证书验证不通过(无该问题可跳过)

SunCertPathBuilderException: unable to find valid certification path to requested target - Mkyong.com

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building_迷茫期。。。的博客-CSDN博客

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
	at sun.security.validator.Validator.validate(Validator.java:271)
	at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:312)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:221)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:128)
	at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:630)
	... 126 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)

> Task :buildSrc:compileJava FAILED
1 actionable task: 1 executed

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.
The remote build cache was disabled during the build due to errors.

2.1.1 新建InstallCert .java文件

/*
 - Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 -  - Redistribution and use in source and binary forms, with or without
 - modification, are permitted provided that the following conditions
 - are met:
 -  -   - Redistributions of source code must retain the above copyright
 -     notice, this list of conditions and the following disclaimer.
 -  -   - Redistributions in binary form must reproduce the above copyright
 -     notice, this list of conditions and the following disclaimer in the
 -     documentation and/or other materials provided with the distribution.
 -  -   - Neither the name of Sun Microsystems nor the names of its
 -     contributors may be used to endorse or promote products derived
 -     from this software without specific prior written permission.
 -  - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 - IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 - THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 - PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
import java.io.*;
import java.net.URL;
 
import java.security.*;
import java.security.cert.*;
 
import javax.net.ssl.*;
 
public class InstallCert {
 
    public static void main(String[] args) throws Exception {
    String host;
    int port;
    char[] passphrase;
    if ((args.length == 1) || (args.length == 2)) {
        String[] c = args[0].split(":");
        host = c[0];
        port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
        String p = (args.length == 1) ? "changeit" : args[1];
        passphrase = p.toCharArray();
    } else {
        System.out.println("Usage: java InstallCert [:port] [passphrase]");
        return;
    }
 
    File file = new File("jssecacerts");
    if (file.isFile() == false) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP
            + "lib" + SEP + "security");
        file = new File(dir, "jssecacerts");
        if (file.isFile() == false) {
        file = new File(dir, "cacerts");
        }
    }
    System.out.println("Loading KeyStore " + file + "...");
    InputStream in = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);
    in.close();
 
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();
 
    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println();
        System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
        System.out.println();
        e.printStackTrace(System.out);
    }
 
    X509Certificate[] chain = tm.chain;
    if (chain == null) {
        System.out.println("Could not obtain server certificate chain");
        return;
    }
 
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));
 
    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        System.out.println
            (" " + (i + 1) + " Subject " + cert.getSubjectDN());
        System.out.println("   Issuer  " + cert.getIssuerDN());
        sha1.update(cert.getEncoded());
        System.out.println("   sha1    " + toHexString(sha1.digest()));
        md5.update(cert.getEncoded());
        System.out.println("   md5     " + toHexString(md5.digest()));
        System.out.println();
    }
 
    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
        System.out.println("KeyStore not changed");
        return;
    }
 
    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);
 
    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();
 
    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println
        ("Added certificate to keystore 'jssecacerts' using alias '"
        + alias + "'");
    }
 
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
 
    private static String toHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 3);
    for (int b : bytes) {
        b &= 0xff;
        sb.append(HEXDIGITS[b >> 4]);
        sb.append(HEXDIGITS[b & 15]);
        sb.append(' ');
    }
    return sb.toString();
    }
 
    private static class SavingTrustManager implements X509TrustManager {
 
    private final X509TrustManager tm;
    private X509Certificate[] chain;
 
    SavingTrustManager(X509TrustManager tm) {
        this.tm = tm;
    }
 
    public X509Certificate[] getAcceptedIssuers() {
        throw new UnsupportedOperationException();
    }
 
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new UnsupportedOperationException();
    }
 
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        this.chain = chain;
        tm.checkServerTrusted(chain, authType);
    }
    }
 
}

2.1.2 编译InstallCert .java

javac InstallCert.java

2.1.3 运行InstallCert,生成jssecacerts文件

--输入命令(域名换成自己idea访问报错的域名或者ip)
java InstallCert ge.spring.io:443

命令执行后,会要求输入数字1,生成证书文件

如何下载阅读Spring源码-全过程详解_第2张图片

 出现如下信息就代表安装成功

如何下载阅读Spring源码-全过程详解_第3张图片

 2.1.4 将同目录下生成的jssecacerts文件添加到$JAVA_HOME/jre/lib/security

如何下载阅读Spring源码-全过程详解_第4张图片

2.1.5 重启IDEA(注意重启,不然可能不会生效)

这个问题这样就解决啦!

如果对你有帮助,麻烦帮忙点个赞吧,你的赞就是对我最大的鼓励

不过又出现了新的问题

2.2 KotlinConventions类编译失败

> Task :buildSrc:compileJava FAILED
D:\Users\project\spring-framework\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 ������

2.2.1 问题原因

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

笔者本地使用了jdk8,而spring源码现在已经使用了jdk 17,所以我本地的jdk不适用于spring-framework,需要重新下载jdk17

2.2.2 下载使用jdk 17

Java JDK下载与安装教程

安装之后,在Gradle设置里,使用我们下载的jdk17

如何下载阅读Spring源码-全过程详解_第5张图片

问题解决

2.3 无法获取到依赖的jar包

Could not download reactor-netty5-http-2.0.0-M3.jar (io.projectreactor.netty:reactor-netty5-http:2.0.0-M3)
Could not get resource 'https://repo.spring.io/milestone/io/projectreactor/netty/reactor-netty5-http/2.0.0-M3/reactor-netty5-http-2.0.0-M3.jar'.
Could not GET 'https://jfrog-prod-use1-shared-virginia-main.s3.amazonaws.com/aol-springsource/filestore/86/865933d3682c52611968163a012ff66b9872b71a?X-Artifactory-username=anonymous&X-Artifactory-repositoryKey=libs-milestone-local&X-Artifactory-artifactPath=io%2Fprojectreactor%2Fnetty%2Freactor-netty5-http%2F2.0.0-M3%2Freactor-netty5-http-2.0.0-M3.jar&X-Artifactory-projectKey=default&x-jf-traceId=4d07ec9a25940234&response-content-disposition=attachment%3Bfilename%3D%22reactor-netty5-http-2.0.0-M3.jar%22&response-content-type=application%2Fjava-archive&X-Amz-Security-Token=FwoGZXIvYXdzECIaDHVyEGk3w71HFKwaYiKlBFzfmjii%2Fj83al2YQhVAEsu3fvEqpDokpVyh7MRIlErCfyQgqa6VeIO5vFtEZjFWqd7hdrFH2xJHqfct1IFfzWuadfgyUIATPyd1fiAVGuTtqhuz3jn4rEPVgOkGZPYaOp9YGNXP7T5UB%2BYc8aftvD8ORRKbsNkaoB4EbWmpPRtGcSGnnQUPLpccRlDqpoIUKSyiEfwrpoeuWtaJp4Y%2FYQBG6UEpq9n2NYddnTaieE5t%2ByaipzZ3RRbJPteBcuud%2FMVxeWy%2BMR7mrezhQe6TRy7Au4AX7Dm1%2FFiboXC%2BLu06o82jTMLWHBx8uxXvrzhMJ6Rk0SlFEB2YhkHLy%2BJfSrRlrCfg3t0buTjeGosZ8W59yJXrHjKIQnTx04J2KlKUUHi6i7b%2BnyNlEwCEs61BnrWZsrd89QvCOgQ7I3yA4zFUii2ugr2gj0BGgvYTKjYO6PlwkDiYu2c5Tw8kUEmDLyOxqBaVH4tkrPBY0uu29ggvrBPTOgP6puhL45TsTW3MO6V9sHFQjJrIJ9rAuAc3tHK0CoN7aQ3MxCoezjvrUN6KB%2BXVxT7ZEia%2FP%2BNec%2BLL9b0CRM7tLnJ9ly6w59y5KrnmeeAQ6%2FjWgd6lmJqS2gknMXqvGTkIHu95RTHO7dSu2yaaeqqBGnQUc%2FmQG4d5tTQdvUOgAY2nVEzTe%2BVZhnUiVFMg%2F%2BmudQWCPKZxtAnNtxhgQelur%2FEe9eFd9oNta1DOCRlKVSj7s86fBjIrtSsd354CSxF%2FP23mYpHUuWchiZXrJzk6gk%2FsmBFsOA%2FfjApBVe1mZ3RB9Q%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230220T160636Z&X-Amz-SignedHeaders=host&X-Amz-Expires=60&X-Amz-Credential=ASIA6RUGCBMHDIGDGT7Q%2F20230220%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=eff0beab0b224964c11606d240a9ec4ce6aa4cbe60db666d5157c6dfafc1811d'.
Connection reset

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

这个要排除下是网络问题还是代理问题

先使用ping命令看下网络是不是通的

如何下载阅读Spring源码-全过程详解_第6张图片

这里看到,ping命令请求超时,但是直接浏览器访问,是没问题的,再看看是不是代理问题

打开IDEA设置setting,找到HTTP Proxy,选择Auto-detect proxy setting(自动发现代理设置),然后应用

如何下载阅读Spring源码-全过程详解_第7张图片

 重新刷新Gradle依赖,发现开始下载依赖包了,最后BUILD SUCCESSFUL,大功告成

如何下载阅读Spring源码-全过程详解_第8张图片

接下来就可以愉快的阅读源码啦!

后续我将会边学习边写源码阅读笔记,并同步到博客,欢迎大家多互相交流!

如果觉得这篇文章有帮助,麻烦点个赞鼓励一下,谢谢~

你可能感兴趣的:(手撕源码,spring,java,spring源码)