IDEA阅读spring源码并调试
⽬标:搭建起Spring源码阅读和代码调试跟踪的环境,顺便建⽴⼀个简单的Demo,能够调试Spring的源代码
本节,主要介绍⼀下Spring源码阅读和调试的相关环境搭建,并使⽤MVN创建⼀个⾮常简单的Demo,以便可以跟踪和调试Spring的内核。
1、源码的下载
2、Spring源码的编译
Spring源码下载下来后,我这⾥⽐较习惯,先编译出来,⽽不是直接导⼊到相关的 IDE。⼤型的开源项⽬都是借助于⾃动化构建⼯具实现编译打包的,因此先编译有个好处,就是编译过程中,会⾃动的下载相关的依赖。现在⼤部分项⽬编译过程中出现的问题,⾸先都归结到项⽬依赖的问题。
①、编译环境
A、操作系统:我的源码和相关开发环境,都是在 mac 下的
B、JDK:安装好JDK1.8
C、由于Spring源码是采⽤Gradle这种⾃动化构建⼯具构建的,因此需要安装 Gradle ,安装过程就不多说了。
D、我使⽤的IDE是 IntelliJ IDEA,因此,需要安装 IntelliJ IDEA 旗舰版,免费30天
②、源码编译
在源码编译环境准备好后,编译源码之前,请先仔细看⼀下 Spring源码⽬录下的 README.md、import-into-idea.md  这两个⽂件。
README.md中,告知了整个编译过程和需要注意的地⽅。如果你使⽤Eclipse作为IDE的开发⼯具,那直接运⾏./import-into-eclipse.sh  或者 ./import-into-eclipse.bat ,就可以把源码导⼊到Eclipse中,如果使⽤IDEA作为开发⼯具,那么需要认真阅读 import-into-idea.md,它告诉了你导⼊IDEA的步骤。
A、先进⼊ …/spring-framework ⽬录,执⾏ ./gradlew :spring-oxm:compileTestJava  先对 Spring-oxm 模块进⾏预编译。
B、还是在 …/spring-framework ⽬录 ,执⾏ ./gradlew build -x test  编译,整个Spring的源码。后⾯的 -x test  是编译期间忽略测试⽤例,需要加上这个,Spring的测试⽤例,有些是编译不过的。编译过程时间,会随着⽹络的畅通程度⽽不同。
③、源码导⼊IDEA
编译通过后,就可以把源码导⼊到 IDEA中了
在IDEA中 File -> New -> Project from Existing Sources -> Navigate to directory ,选择Spring源码⽬录,导⼊,然后IDEA会⾃动的使⽤Gradle进⾏构建。构建完成之后,需要做如下设置:
排除 spring-aspects  项⽬,这个是Spring 的AOP体系集成了 aspects ,但在IDEA中⽆法编译通过,原因可以参见:
选中  spring-aspects  项⽬右键,选择“Load/Unload Moudules” 在弹出的窗体中进⾏设置(如下图所⽰):
3、简单的Demo的搭建
这⾥可以创建⼀个简单的Demo,该Demo依赖于Spring的源码,这样,就可以从外部,运⾏Demo,跟踪到Spring的内部源码了。为不失⼀般性,这⾥的Demo采⽤MVN进⾏构建,只不过,相关的Spring的源码依赖需要在IDEA中设置成本地源码
①、使⽤IDEA 在Spring的源码的Project⽬录下,创建⼀个Demo,可以直接使⽤MVN的⾻架
②、Demo的相关设置和简单的代码测试
A、设置⼀下l 中的 junit 依赖版本,修改为 4.12 否则Spring的单元测试,编译不通过
B、在IDEA设置Spring的项⽬依赖(设置Spring-core、Spring-beans、Spring-context、Spring-expression这⼏个module就可以了):
C、l中需要引⼊commons-logging的依赖,否则编译报不到LogginFactory的错误.配置静态资源路径(否则读取xml的时候,不到路径)
D、设置Spring的配置和编写简单的Spring代码
创建⼀个简单的登录接⼝ ILogin:
public interface ILogin {
String loginCheck(String userName,String password);
}
它有个实现类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
spring怎么读英文怎么读public class LoginImpl implements ILogin {
String id = "";
@Autowired(required = false)
public void setId(String id) {
this.id = id;
}
@Override
public String loginCheck(String userName, String password) {
System.out.println("boy登录...");
return "success";
}
}
然后,把该bean 注册到配置中(路径spring-debug/l):
import com.boy.login.ILogin;
import t.ApplicationContext;
import t.support.FileSystemXmlApplicationContext;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) {
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("l"); String XMLPath = "//Users/sky/Java/spring-framework/spring-debug/l"; ApplicationContext applicationContext = new FileSystemXmlApplicationContext(XMLPath);
ILogin login = (ILogin) Bean("loginService");
login.loginCheck("boy", "123");
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。