IDEA imports spring source code


foreword

When we are learning the source code of spring, sometimes we need to add some code comments when reading the source code, or some insights into the source code. If we do not import the source code of spring into IDEA, we simply read the jar form through Maven. It is impossible to add some comment information. Even if you can add comments to the source code through some plug-ins like Private Notesthis , there are still limitations. First of all, this plug-in does not allow you to change the number of lines in the source code, so your private comments It can only be written in one line, and then import the source code. You can change the source code, such as printing something, which is more helpful to understand the source code.

The following content is the first time I used IDEA to import the Spring source code. I stepped on a lot of pitfalls. I also recorded the problems I encountered and the solutions, hoping to help you.


spring official website: https://spring.io/

1. Download the source code

We can download the source code of spring on github or gitee

Download on github:

spring-fremaworkYou can find it by searching on github : https://github.com/spring-projects/spring-framework

insert image description here

Download from gitee:

spring-fremaworkYou can find it by searching on gitee : https://gitee.com/mirrors/spring-framework?_from=gitee_search

insert image description here

Although it is said that you can git clone download the source code, it is not recommended (I stepped on the pit myself, and there are many problems), it is best to download ZIPthe compressed package directly here

I created /source-codesuch to manage my source code, and then unzip the downloaded source code into this folder. The version I am learning here isspring-framework-5.2.x

insert image description here


2. Install Gradle


1. Download Gradle

Gradle is a build tool, it is similar to that Meven, Spring is compiled with Gradle, so it would be better for us to download a Gradle.
insert image description here

To download Gradle, we must find a version compatible with the Spring source code you downloaded. You can find which version you should download in \spring-framework-5.2.x\gradle\wrapper\gradle-wrapper.propertiesthe fileGradle

insert image description here

So as specified in gradle-wrapper.propertiesthe file I should download gradle-5.6.4-bin.zipthis version ofGradle

Go to the official website to download https://services.gradle.org/distributions/

insert image description here

I created /gradlea folder to store the newly downloaded ones Gradle, and then decompress them

Both Gradle and Meven have a warehouse. For convenience, I .gradlecreated in this directory.

insert image description here


2. Configure environment variables

Right mouse button 我的电脑(此电脑)- select again属性 高级系统设置环境变量

add link description

Click 环境变量to come in like this, click新建

add link description

Configure as shown in the figure below. After the configuration is complete, click 确定Save Configuration

Configure GRADLE_HOME

Variable name: GRADLE_HOME
variable value: D:\gradle\gradle-5.6.4-bin\gradle-5.6.4(the installation directory of Gradle, which is the directory where the bin folder is located)

insert image description here

Placement GRADLE_USER_HOME

Variable name: GRADLE_USER_HOME
Variable value: D:\gradle\.gradle(Gradle repository directory)

insert image description here

At the same time, you also need to Pathadd the configuration, select Path, click编辑

add link description

新建Environment variables:

  • %GRADLE_HOME%\bin
  • %GRADLE_USER_HOME%

insert image description here

确定keep

Now cmdopen the command window and enter gradle -vthe command to check Gradlewhether the installation is successful

insert image description here

版本信息It's ok if you can see it


3. Preparation before import

In order to speed up the speed of gradledownloading dependent packages, we need to add the domestic mirror address in the build.gradleand settings.gradlethese two files.

insert image description here

build.gradle file

insert image description here

maven {
    
     url "https://maven.aliyun.com/nexus/content/groups/public/"}
maven {
    
     url "https://maven.aliyun.com/nexus/content/repositories/jcenter"}
maven {
    
     url "https://repo.springsource.org/plugins-release"}

settings.gradle file

insert image description here

maven{
    
     url "https://maven.aliyun.com/nexus/content/groups/public/"}

spring-framework\gradle\wrapper\gradle-wrapper.propertiesModify the in the file distributionUrlto be downloaded by yourself (PS: This step can be done or not

insert image description here

distributionUrl=file\:///D\:/gradle/gradle-5.6.4-bin.zip

4. Compile the source code


1. Import source code

open IDEA, select File->Open

insert image description here

Select the directory where the spring source code is located

insert image description here

It is imported like this

insert image description here

After the project is imported, check it first JDK 的配置, because Gradle JVMit needs to be used JDK 11, so 务必configuring JDK 11 can avoid many pitfalls

insert image description here

insert image description here

Then configureGradle

insert image description here

Check it git 配置(it will automatically detect git when compiling, so you need to check it)

insert image description here

Next, wait for the project to be built automatically, because this process Gradlewill download some jarpackages and it will take some time.

insert image description here

When you see that each project 右下角basically has one 蓝色方块, it means that the source code of Spring has been imported successfully.

If you encounter problems in the above process, you may wish to take a look below~~


2. The problem I encountered

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

insert image description here

It is very simple to solve this problem. Go to this directory, call it up Git Bash Here , and execute the following three lines of commands in sequence

git init
git add .
git commit -m "随便写点啥都行"

insert image description here

Just rebuild it in IDEA

  1. Gradle 版本导致 A problem occurred evaluating root project 'spring'. 等问题

insert image description here

I downloaded according to gradle.propertiesthis gradle-5.3-bin.zip, I thought it was enough, but I didn’t expect java-test-fixturesthese packages to be downloaded, there is no way, I can only gradle-wrapper.propertiesdownload gradle-5.6.4-bin.zipanother version based on

insert image description here

Reset IDEA Greadle's Specified locationand select the newly Gradle gradle-5.6.4-bin.zipdownloaded version

insert image description here

Therefore, it is still necessary gradle-wrapper.propertiesto Gradlerefer to the version specified by the file to avoid some pitfalls

  1. 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

insert image description here

I just rebuilt it, so there is nothing to say


5. Test


1. Create a module

Now that the source code is successfully imported, create a new module in the spring project to test it

Right-click the project root directory, New-> Modulecreate a module

insert image description here

To choose this Gradle, clickNext

insert image description here

Set the module name, clickFinish

insert image description here

it's ok

insert image description here


2. Write the test code

insert image description here

replace with

insert image description here

    testImplementation group: 'junit', name: 'junit', version: '4.13.1'
    testImplementation group: 'org.hamcrest', name: 'hamcrest-core', version: '1.3'
    compile(project(":spring-context"))

Here is a brief description of the following. If Gradle refers to a module in this project, use it compile(project(":moduleName)). If you use a third-party package, use testImplementation group:xxxx ' import

Test Results:

It can be seen that there is no problem, no error is reported, and the class used is from this project, which can be executed correctly

insert image description here

The test code is as follows:

UserController.calss

package com.mike.controller;

import com.mike.service.UserService;

public class UserController {
    
    

	private UserService userService;

	/**
	 * DI:set 方法注入
	 */
	public void setUserService(UserService userService) {
    
    
		this.userService = userService;
	}

	public String findAll() {
    
    
		return userService.findAll();
	}
}

UserService.java

package com.mike.service;

public interface UserService {
    
    

	String findAll();

}

UserServiceImpl.java

package com.mike.service.impl;

import com.mike.service.UserService;

public class UserServiceImpl implements UserService {
    
    

	@Override
	public String findAll() {
    
    
		return "返回所有用户信息";
	}

}

MainTest.java

package com.mike.test;

import com.mike.controller.UserController;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {
    
    

	@Test
	public void test() {
    
    
		// 获取 Spring 容器对象
		// 执行这行代码相当于启动了 Spring 容器,解析 spring.xml 文件,并且实例化所有的 bean 对象放到 spring 容器中
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml");
		// 获取 UserController 对象
		UserController userController = applicationContext.getBean("userController", UserController.class);
		// 执行方法
		String allUsers = userController.findAll();
		System.out.println("allUsers = " + allUsers);
	}
}

spring.xml

<?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">


	<!-- 使用 Spring IOC 和 ID 管理对象 -->
	<bean id="userService" class="com.mike.service.impl.UserServiceImpl"/>

	<bean id="userController" class="com.mike.controller.UserController">
		<property name="userService" ref="userService"/>
	</bean>

</beans>

If you encounter problems in the above process, you may wish to take a look below~~


3. The problem I encountered

  1. build.gradle 怎么配置第三方依赖

For example, in the test template I wrote junit, we can import it in the pom file like this

        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

But how do we write it in build.gradlethe file ?

In fact, the import method is provided the Maven warehouse , just copy it directlyGradle

insert image description here

  1. Kotlin: warnings found and -Weeror specified

After I've written the test code, MainTestrun test()the method in the class as reported by

insert image description here

This problem arises because缺少 cglib 和 objenesis 包

Solution: Call up the command line window in this directory

insert image description here

Enter the following two commands:

gradle objenesisRepackJar
gradle cglibRepackJar

insert image description here

  1. java: 找不到符 符号:变量 CoroutinesUtils

After solving the previous problem, MainTestrun test()the method reported in the class. This problem can be said to be encountered frequently, and it may occur every time the project is built.

insert image description here

This is because CoroutinesUtilsis kotlina tool class of , which cannot be read by the Spring source code package, so it needs to be manually added kotlin-coroutines-X.X.X.BUILD-SNAPSHOT.jarto Libraries.

Click File-> Project Structure-> - Libraries> -> +->Java

insert image description here

Then select spring-framework/spring-core/kotlin-coroutines/build/libs/kotlin-coroutines-X.X.X.BUILD-SNAPSHOT.jarclick OK(if there is no build directory in your kotlin-coroutines directory, skip to question 3)

insert image description here

Then a page for selecting modules will pop up, select spring.spring-core.mainand clickOK

insert image description here

  1. kotlin-coroutines 目录下没有 build 目录

If you're like me and haven't noticed

insert image description here

GradleClick -> Tasks-> -> other-> on the rightcomplieKotlin

insert image description here

After compiling, there is

  1. compileXXXX 时或者在运行时报错 PropertyComparator<capture#1, 共 ?>无法转换为java.util.Comparator<? super capture#1, 共 ?> 等各种泛型使用问题

For example, when compilingKontlin

D:\source-code\spring-framework-5.2.x\spring-framework-5.2.x\spring-beans\src\main\java\org\springframework\beans\support\PropertyComparator.java:138: ����: �����ݵ�����: PropertyComparator<CAP#1>�޷�ת��ΪComparator<? super CAP#1>
			source.sort(new PropertyComparator<>(sortDefinition));
			            ^
  ����, CAP#1�������ͱ���:
    CAP#1��?�IJ�����չObject

insert image description here

Or when running the main method, Test method

D:\source-code\spring-framework-5.2.x\spring-framework-5.2.x\spring-beans\src\main\java\org\springframework\beans\support\PropertyComparator.java:138:25
java: 不兼容的类型: org.springframework.beans.support.PropertyComparator<capture#1,?>无法转换为java.util.Comparator<? super capture#1,?>

insert image description here

This problem feels like a pit related to generics, so I changed the source code

insert image description here

After compiling again, this problem did not reappear, but a new problem appeared again.

D:\source-code\spring-framework-5.2.x\spring-framework-5.2.x\spring-messaging\src\main\java\org\springframework\messaging\handler\annotation\reactive\PayloadMethodArgumentResolver.java:236: ����: �����ݵ�����: lambda ���ʽ�еķ������ʹ���
							.onErrorResume(ex -> Flux.error(handleReadError(parameter, message, ex)));
							                               ^
    Flux<CAP#1>�޷�ת��ΪPublisher<? extends CAP#1>
  ����, CAP#1�������ͱ���:
    CAP#1��?�IJ�����չObject

insert image description here

It is also related to generics, so modifying the code here is not a good solution. If you change one, you will encounter many later, which is a temporary solution, not a permanent solution.

This problem occurs because gradle jvm 的版本没有使用 jdk 11导致的, so Gradle JVMbe sure to replace theJDK 11

insert image description here

ProjectThe JDK is also changed to11

insert image description here

It will be fine to compile again

insert image description here


6. Summary

The above is the whole process of using IDEA to import Spring source code. I have to say that there are really many pitfalls in IDEA importing Spring source code. I don’t know how many people who study source code are discouraged here~~

There are still some errors that I have not listed, because this is what I have summarized after optimization, so I have not encountered other errors so I will not write them here. I feel that the biggest obstacle in this process is the unfamiliarity Gradlewith , many problems are Gradlerelated to , but fortunately they were all solved in the end, and I hope this article can give you a good start in the process of learning source code.


Reference blog:
"Spring" first article IDEA imports Spring source code: https://blog.csdn.net/weixin_44167408/article/details/121769949
Zhihu: Spring source code compilation process and problems: https://zhuanlan.zhihu. com/p/378831634

Guess you like

Origin blog.csdn.net/xhmico/article/details/130612527