在学习Spring源码时,发现源码在IDEA中为只读状态(File is read-only),无法编辑及增加注释,增加了我们学习源码的难度。
本文记录:如何将源码的只读状态变为编辑状态(增加注释来辅助理解源码)
1. 搭建简单的Spring项目
项目整体结构:
pom.xml:Spring的版本需与编译的源码版本一致
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.trytry</groupId>
<artifactId>spring-source-code</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.2.8.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<!-- 日志相关依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
</project>
spring.xml
<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"
default-lazy-init="false">
<bean id="student" class="cn.trytry.bean.Student" />
</beans>
cn.trytry.bean.Student
package cn.trytry.bean;
import lombok.Data;
@Data
public class Student {
private String username = "trytry";
}
cn.trytry.test.TestSpring
package cn.trytry.test;
import cn.trytry.bean.Student;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void test1() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Student bean = applicationContext.getBean(Student.class);
System.out.println(bean.getUsername());
}
}
启动并检查TestSpring.test1()是否正常运行:
2. 将编译后源码导入到搭建的项目中
此处以spring-context包为例
- File->Project Structure->Libraries->选中spring-context->选中右侧的Classes->点击+号
- 选中-> 编译后源码项目spring-contextuildlibsspring-context-5.2.8.RELEASE.jar
- 将之前Classes下的spring-context包删除
- 选中Sources->点击+号 ->选中整个spring-context包 -> OK -> OK
- 将之前Sources下的spring-context-sources包删除
- 此时就可以在源码中增加注释了
3. 编辑源码后,源码与包不一致的情况
增加注释后会出现,断点打到注释上面的情况,是因为源码与包不一致,此时应重新打包。
在源码工程中重新打Jar包(此处为spring-context包):双击jar即可重新打包
打包完成: